Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/test/java/util/Scanner/ScanTest.java
38811 views
/*1* Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/**24* @test25* @bug 4313885 4926319 4927634 5032610 5032622 5049968 5059533 6223711 6277261 6269946 628882326* @summary Basic tests of java.util.Scanner methods27* @key randomness28* @run main/othervm ScanTest29*/3031import java.util.*;32import java.text.*;33import java.io.*;34import java.nio.*;35import java.util.regex.*;36import java.math.*;3738public class ScanTest {3940private static boolean failure = false;41private static int failCount = 0;42private static int NUM_SOURCE_TYPES = 2;4344public static void main(String[] args) throws Exception {45Locale reservedLocale = Locale.getDefault();46String lang = reservedLocale.getLanguage();47try {48if (!"en".equals(lang) &&49!"zh".equals(lang) &&50!"ko".equals(lang) &&51!"ja".equals(lang)) {52//Before we have resource to improve the test to be ready for53//arbitrary locale, force the default locale to be "English"54//for now.55Locale.setDefault(Locale.ENGLISH);56}57skipTest();58findInLineTest();59findWithinHorizonTest();60findInEmptyLineTest();61removeTest();62fromFileTest();63ioExceptionTest();64matchTest();65delimiterTest();66useLocaleTest();67closeTest();68cacheTest();69cacheTest2();70nonASCIITest();71resetTest();7273for (int j=0; j<NUM_SOURCE_TYPES; j++) {74hasNextTest(j);75nextTest(j);76hasNextPatternTest(j);77nextPatternTest(j);78booleanTest(j);79byteTest(j);80shortTest(j);81intTest(j);82longTest(j);83floatTest(j);84doubleTest(j);85integerPatternTest(j);86floatPatternTest(j);87bigIntegerPatternTest(j);88bigDecimalPatternTest(j);89hasNextLineTest(j);90nextLineTest(j);91singleDelimTest(j);92}9394// Examples95//example1();96//example2();97//example3();9899// Usage cases100useCase1();101useCase2();102useCase3();103useCase4();104useCase5();105106if (failure)107throw new RuntimeException("Failure in the scanning tests.");108else109System.err.println("OKAY: All tests passed.");110} finally {111// restore the default locale112Locale.setDefault(reservedLocale);113}114}115116public static void useCase1() throws Exception {117File f = new File(System.getProperty("test.src", "."), "input.txt");118Scanner sc = new Scanner(f);119sc.findWithinHorizon("usage case 1", 0);120String[] names = new String[4];121for (int i=0; i<4; i++) {122while(sc.hasNextFloat())123sc.nextFloat();124names[i] = sc.next();125sc.nextLine();126}127if (!names[0].equals("Frank"))128failCount++;129if (!names[1].equals("Joe"))130failCount++;131if (!names[2].equals("Mary"))132failCount++;133if (!names[3].equals("Michelle"))134failCount++;135sc.close();136report("Use case 1");137}138139public static void useCase2() throws Exception {140File f = new File(System.getProperty("test.src", "."), "input.txt");141Scanner sc = new Scanner(f).useDelimiter("-");142String testDataTag = sc.findWithinHorizon("usage case 2\n", 0);143if (!testDataTag.equals("usage case 2\n"))144failCount++;145if (!sc.next().equals("cat"))146failCount++;147if (sc.nextInt() != 9)148failCount++;149if (!sc.next().equals("dog"))150failCount++;151if (sc.nextInt() != 6)152failCount++;153if (!sc.next().equals("pig"))154failCount++;155if (sc.nextInt() != 2)156failCount++;157if (!sc.next().equals(""))158failCount++;159if (sc.nextInt() != 5)160failCount++;161sc.close();162report("Use case 2");163}164165public static void useCase3() throws Exception {166File f = new File(System.getProperty("test.src", "."), "input.txt");167Scanner sc = new Scanner(f);168String testDataTag = sc.findWithinHorizon("usage case 3\n", 0);169if (!testDataTag.equals("usage case 3\n"))170failCount++;171Pattern tagPattern = Pattern.compile("@[a-z]+");172Pattern endPattern = Pattern.compile("\\*\\/");173String tag;174String end = sc.findInLine(endPattern);175176while (end == null) {177if ((tag = sc.findInLine(tagPattern)) != null) {178String text = sc.nextLine();179text = text.substring(0, text.length() - 1);180//System.out.println(text);181} else {182sc.nextLine();183}184end = sc.findInLine(endPattern);185}186report("Use case 3");187}188189public static void useCase4() throws Exception {190File f = new File(System.getProperty("test.src", "."), "input.txt");191Scanner sc = new Scanner(f);192String testDataTag = sc.findWithinHorizon("usage case 4\n", 0);193if (!testDataTag.equals("usage case 4\n"))194failCount++;195196// Read some text parts of four hrefs197String[] expected = { "Diffs", "Sdiffs", "Old", "New" };198for (int i=0; i<4; i++) {199sc.findWithinHorizon("<a href", 1000);200sc.useDelimiter("[<>\n]+");201sc.next();202String textOfRef = sc.next();203if (!textOfRef.equals(expected[i]))204failCount++;205}206// Read some html tags using < and > as delimiters207if (!sc.next().equals("/a"))208failCount++;209if (!sc.next().equals("b"))210failCount++;211212// Scan some html tags using skip and next213Pattern nonTagStart = Pattern.compile("[^<]+");214Pattern tag = Pattern.compile("<[^>]+?>");215Pattern spotAfterTag = Pattern.compile("(?<=>)");216String[] expected2 = { "</b>", "<p>", "<ul>", "<li>" };217sc.useDelimiter(spotAfterTag);218int tagsFound = 0;219while(tagsFound < 4) {220if (!sc.hasNext(tag)) {221// skip text between tags222sc.skip(nonTagStart);223}224String tagContents = sc.next(tag);225if (!tagContents.equals(expected2[tagsFound]))226failCount++;227tagsFound++;228}229230report("Use case 4");231}232233public static void useCase5() throws Exception {234File f = new File(System.getProperty("test.src", "."), "input.txt");235Scanner sc = new Scanner(f);236String testDataTag = sc.findWithinHorizon("usage case 5\n", 0);237if (!testDataTag.equals("usage case 5\n"))238failCount++;239240sc.findWithinHorizon("Share Definitions", 0);241sc.nextLine();242sc.next("\\[([a-z]+)\\]");243String shareName = sc.match().group(1);244if (!shareName.equals("homes"))245failCount++;246247String[] keys = { "comment", "browseable", "writable", "valid users" };248String[] vals = { "Home Directories", "no", "yes", "%S" };249for (int i=0; i<4; i++) {250sc.useDelimiter("=");251String key = sc.next().trim();252if (!key.equals(keys[i]))253failCount++;254sc.skip("[ =]+");255sc.useDelimiter("\n");256String value = sc.next();257if (!value.equals(vals[i]))258failCount++;259sc.nextLine();260}261262report("Use case 5");263}264265public static void nonASCIITest() throws Exception {266String yourBasicTibetanNumberZero = "\u0f20";267String yourBasicTibetanFloatingNumber = "\u0f23.\u0f27";268String weirdMixtureOfTibetanAndASCII = "\u0f23.7";269String weirdMixtureOfASCIIAndTibetan = "3.\u0f27";270Scanner sc = new Scanner(yourBasicTibetanNumberZero);271int i = sc.nextInt();272if (i != 0)273failCount++;274sc = new Scanner(yourBasicTibetanFloatingNumber);275float f = sc.nextFloat();276if (f != Float.parseFloat("3.7"))277failCount++;278sc = new Scanner(weirdMixtureOfTibetanAndASCII);279f = sc.nextFloat();280if (f != Float.parseFloat("3.7"))281failCount++;282sc = new Scanner(weirdMixtureOfASCIIAndTibetan);283f = sc.nextFloat();284if (f != Float.parseFloat("3.7"))285failCount++;286report("Scanning non ASCII digits");287}288289public static void findWithinHorizonTest() throws Exception {290// Test with a string source291Scanner sc = new Scanner("dog cat cat dog cat");292try {293sc.findWithinHorizon("dog", -1);294failCount++;295} catch (IllegalArgumentException iae) {296// Correct result297}298if (sc.findWithinHorizon("dog", 2) != null)299failCount++;300if (!sc.findWithinHorizon("dog", 3).equals("dog"))301failCount++;302if (sc.findWithinHorizon("cat", 4) != null)303failCount++;304if (!sc.findWithinHorizon("cat", 5).equals("cat"))305failCount++;306if (sc.findWithinHorizon("cat", 7) != null)307failCount++;308if (sc.findWithinHorizon("dog", 7) != null)309failCount++;310if (!sc.findWithinHorizon("cat", 0).equals("cat"))311failCount++;312if (!sc.findWithinHorizon("dog", 0).equals("dog"))313failCount++;314if (!sc.findWithinHorizon("cat", 0).equals("cat"))315failCount++;316317// Test with a stream source318StutteringInputStream stutter = new StutteringInputStream();319for (int index=0; index<stutter.length(); index++) {320//System.out.println("index is now "+index);321sc = new Scanner(stutter);322String word = stutter.wordInIndex(index);323if (word != null) {324String result = sc.findWithinHorizon(word, index);325if ((result == null) || (!result.equals(word)))326failCount++;327}328stutter.reset();329word = stutter.wordBeyondIndex(index);330sc = new Scanner(stutter);331String result = sc.findWithinHorizon(word, index);332if ((result != null) && (index > 0))333failCount++;334stutter.reset();335}336337// We must loop to let StutteringInputStream do its magic338for (int j=0; j<10; j++) {339// An anchor at the end of stream should work340stutter.reset();341sc = new Scanner(stutter);342String result = sc.findWithinHorizon("phant$", 0);343if (!result.equals("phant"))344failCount++;345stutter.reset();346sc = new Scanner(stutter);347result = sc.findWithinHorizon("phant$", 54);348if (!result.equals("phant"))349failCount++;350// An anchor at the end of horizon should not351stutter.reset();352sc = new Scanner(stutter);353result = sc.findWithinHorizon("brummer$", 7);354if (result != null)355failCount++;356// An anchor at start should work357stutter.reset();358sc = new Scanner(stutter);359result = sc.findWithinHorizon("^brummer", 0);360if (!result.equals("brummer"))361failCount++;362}363364report("Find to horizon test");365}366367// StutteringInputStream returns 1 to 3 characters at a time368static class StutteringInputStream implements Readable {369StutteringInputStream() {370text = "brummer hisser tort zardzard rantrant caimagator phant";371datalen = 54;372}373StutteringInputStream(String text) {374this.text = text;375datalen = text.length();376}377Random generator = new Random();378String text;379int datalen;380int index = 0;381public int length() {382return datalen;383}384public void reset() {385index = 0;386}387public String wordInIndex(int index) {388if (index < 7) return null;389if (index < 14) return "brummer";390if (index < 19) return "hisser";391if (index < 28) return "tort";392if (index < 37) return "zardzard";393if (index < 48) return "rantrant";394return "caimagator";395}396public String wordBeyondIndex(int index) {397if (index < 7) return "brummer";398if (index < 14) return "hisser";399if (index < 19) return "tort";400if (index < 28) return "zardzard";401if (index < 37) return "rantrant";402if (index < 48) return "caimagator";403return "phantphant";404}405public int read(java.nio.CharBuffer target) throws IOException {406if (index > datalen-1)407return -1; // EOS408int len = target.remaining();409if (len > 4) // return 1 to 3 characters410len = generator.nextInt(3) + 1;411while ((index + len) > datalen)412len--;413for (int i=0; i<len; i++)414target.put(text.charAt(index++));415return len;416}417}418419public static void hasNextLineTest(int sourceType) throws Exception {420Scanner sc = scannerFor("1\n2\n3 3\r\n4 4 4\r5", sourceType);421if (!sc.hasNextLine()) failCount++;422if (!sc.nextLine().equals("1")) failCount++;423if (!sc.hasNextLine()) failCount++;424if (sc.nextInt() != 2) failCount++;425if (!sc.hasNextLine()) failCount++;426if (!sc.nextLine().equals("")) failCount++;427if (!sc.hasNextLine()) failCount++;428if (sc.nextInt() != 3) failCount++;429if (!sc.hasNextLine()) failCount++;430if (!sc.nextLine().equals(" 3")) failCount++;431if (!sc.hasNextLine()) failCount++;432if (sc.nextInt() != 4) failCount++;433if (!sc.hasNextLine()) failCount++;434if (sc.nextInt() != 4) failCount++;435if (!sc.hasNextLine()) failCount++;436if (!sc.nextLine().equals(" 4")) failCount++;437if (!sc.hasNextLine()) failCount++;438if (!sc.nextLine().equals("5")) failCount++;439if (sc.hasNextLine()) failCount++;440sc = new Scanner("blah blah blah blah blah blah");441if (!sc.hasNextLine()) failCount++;442if (!sc.nextLine().equals("blah blah blah blah blah blah"))443failCount++;444if (sc.hasNextLine()) failCount++;445446// Go through all the lines in a file447File f = new File(System.getProperty("test.src", "."), "input.txt");448sc = new Scanner(f);449String lastLine = "blah";450while(sc.hasNextLine())451lastLine = sc.nextLine();452if (!lastLine.equals("# Data for usage case 6")) failCount++;453454report("Has next line test");455}456457public static void nextLineTest(int sourceType) throws Exception {458Scanner sc = scannerFor("1\n2\n3 3\r\n4 4 4\r5", sourceType);459if (!sc.nextLine().equals("1"))460failCount++;461if (sc.nextInt() != 2)462failCount++;463if (!sc.nextLine().equals(""))464failCount++;465if (sc.nextInt() != 3)466failCount++;467if (!sc.nextLine().equals(" 3"))468failCount++;469if (sc.nextInt() != 4)470failCount++;471if (sc.nextInt() != 4)472failCount++;473if (!sc.nextLine().equals(" 4"))474failCount++;475if (!sc.nextLine().equals("5"))476failCount++;477sc = new Scanner("blah blah blah blah blah blah");478if (!sc.nextLine().equals("blah blah blah blah blah blah"))479failCount++;480report("Next line test");481}482483public static void singleDelimTest(int sourceType) throws Exception {484Scanner sc = scannerFor("12 13 14 15 16 17 ",485sourceType);486sc.useDelimiter(" ");487for (int i=0; i<6; i++) {488int j = sc.nextInt();489if (j != 12 + i)490failCount++;491for (int k=0; k<i; k++) {492String empty = sc.next();493if (!empty.equals(""))494failCount++;495}496}497report("Single delim test");498}499500/*501* The hasNextPattern caches a match of a pattern called the regular cache502* The hasNextType caches a match of that type called the type cache503* Any next must clear the caches whether it uses them or not, because504* it advances past a token thus invalidating any cached token; any505* hasNext must set a cache to what it finds.506*/507public static void cacheTest() throws Exception {508// Test clearing of the type cache509Scanner scanner = new Scanner("777 dog");510scanner.hasNextInt();511scanner.findInLine("777");512try {513scanner.nextInt();514System.out.println("type cache not cleared by find");515failCount++;516} catch (InputMismatchException ime) {517// Correct518}519520scanner = new Scanner("777 dog");521scanner.hasNextInt();522scanner.skip("777");523try {524scanner.nextInt();525System.out.println("type cache not cleared by skip");526failCount++;527} catch (InputMismatchException ime) {528// Correct529}530531// Test clearing of the regular cache532scanner = new Scanner("777 dog");533scanner.hasNext("777");534scanner.findInLine("777");535try {536scanner.next("777");537System.out.println("regular cache not cleared by find");538failCount++;539} catch (InputMismatchException ime) {540// Correct541}542543// Test two primitive next clearing of type cache544scanner = new Scanner("777 dog");545scanner.hasNextInt();546scanner.nextLong();547try {548scanner.nextInt();549System.out.println("type cache not cleared by primitive next");550failCount++;551} catch (InputMismatchException ime) {552// Correct553}554555// Test using both of them, type first556scanner = new Scanner("777 dog");557scanner.hasNext("777");558scanner.nextInt();559try {560scanner.next("777");561System.out.println("regular cache not cleared by primitive next");562failCount++;563} catch (InputMismatchException ime) {564// Correct565}566567// Test using both of them, regular first568scanner = new Scanner("777 dog");569scanner.hasNext("777");570scanner.hasNextInt();571scanner.next("777");572try {573scanner.nextInt();574System.out.println("type cache not cleared by regular next");575failCount++;576} catch (InputMismatchException ime) {577// Correct578}579report("Cache test");580}581582/*583* The hasNext<IntegerType>(radix) method caches a matched integer type584* with specified radix for the next next<IntegerType>(radix) invoke.585* The cache value should not be used if the next<IntegerType>(radix)586* has different radix value with the last hasNext<IntegerType>(radix).587*/588public static void cacheTest2() throws Exception {589// Test clearing of the type cache590Scanner scanner = new Scanner("10");591scanner.hasNextByte(16);592if (scanner.nextByte(10) != 10) {593System.out.println("wrong radix cache is used");594failCount++;595}596scanner = new Scanner("10");597scanner.hasNextShort(16);598if (scanner.nextShort(10) != 10) {599System.out.println("wrong radix cache is used");600failCount++;601}602scanner = new Scanner("10");603scanner.hasNextInt(16);604if (scanner.nextInt(10) != 10) {605System.out.println("wrong radix cache is used");606failCount++;607}608scanner = new Scanner("10");609scanner.hasNextLong(16);610if (scanner.nextLong(10) != 10) {611System.out.println("wrong radix cache is used");612failCount++;613}614scanner = new Scanner("10");615scanner.hasNextBigInteger(16);616if (scanner.nextBigInteger(10).intValue() != 10) {617System.out.println("wrong radix cache is used");618failCount++;619}620report("Cache test2");621}622623624public static void closeTest() throws Exception {625Scanner sc = new Scanner("testing");626sc.close();627sc.ioException();628sc.delimiter();629sc.useDelimiter("blah");630sc.useDelimiter(Pattern.compile("blah"));631for (int i=0; i<NUM_METHODS; i++) {632try {633methodCall(sc, i);634failCount++;635} catch (IllegalStateException ise) {636// Correct637}638}639report("Close test");640}641642private static int NUM_METHODS = 23;643644private static void methodCall(Scanner sc, int i) {645switch(i) {646case 0: sc.hasNext(); break;647case 1: sc.next(); break;648case 2: sc.hasNext(Pattern.compile("blah")); break;649case 3: sc.next(Pattern.compile("blah")); break;650case 4: sc.hasNextBoolean(); break;651case 5: sc.nextBoolean(); break;652case 6: sc.hasNextByte(); break;653case 7: sc.nextByte(); break;654case 8: sc.hasNextShort(); break;655case 9: sc.nextShort(); break;656case 10: sc.hasNextInt(); break;657case 11: sc.nextInt(); break;658case 12: sc.hasNextLong(); break;659case 13: sc.nextLong(); break;660case 14: sc.hasNextFloat(); break;661case 15: sc.nextFloat(); break;662case 16: sc.hasNextDouble(); break;663case 17: sc.nextDouble(); break;664case 18: sc.hasNextBigInteger(); break;665case 19: sc.nextBigInteger(); break;666case 20: sc.hasNextBigDecimal(); break;667case 21: sc.nextBigDecimal(); break;668case 22: sc.hasNextLine(); break;669default:670break;671}672}673674public static void removeTest() throws Exception {675Scanner sc = new Scanner("testing");676try {677sc.remove();678failCount++;679} catch (UnsupportedOperationException uoe) {680// Correct result681}682report("Remove test");683}684685public static void delimiterTest() throws Exception {686Scanner sc = new Scanner("blah");687Pattern test = sc.delimiter();688if (!test.toString().equals("\\p{javaWhitespace}+"))689failCount++;690sc.useDelimiter("a");691test = sc.delimiter();692if (!test.toString().equals("a"))693failCount++;694sc.useDelimiter(Pattern.compile("b"));695test = sc.delimiter();696if (!test.toString().equals("b"))697failCount++;698report("Delimiter test");699}700701public static void ioExceptionTest() throws Exception {702Readable thrower = new ThrowingReadable();703Scanner sc = new Scanner(thrower);704try {705sc.nextInt();706failCount++;707} catch (NoSuchElementException nsee) {708// Correct result709}710Exception thrown = sc.ioException();711String detail = thrown.getMessage();712if (!detail.equals("ThrowingReadable always throws"))713failCount++;714715report("IOException test");716}717718public static void bigIntegerPatternTest(int sourceType) throws Exception {719Scanner sc = scannerFor("23 9223372036854775817", sourceType);720if (!sc.nextBigInteger().equals(BigInteger.valueOf(23)))721failCount++;722if (!sc.nextBigInteger().equals(new BigInteger(723"9223372036854775817", 10)))724failCount++;725726// Test another radix727sc = new Scanner("4a4 4A4").useRadix(16);728if (!sc.nextBigInteger().equals(new BigInteger("4a4", 16)))729failCount++;730if (!sc.nextBigInteger().equals(new BigInteger("4A4", 16)))731failCount++;732733// Test alternating radices734sc = new Scanner("12 4a4 14 4f4");735if (!sc.nextBigInteger(10).equals(new BigInteger("12", 10)))736failCount++;737if (!sc.nextBigInteger(16).equals(new BigInteger("4a4", 16)))738failCount++;739if (!sc.nextBigInteger(10).equals(new BigInteger("14", 10)))740failCount++;741if (!sc.nextBigInteger(16).equals(new BigInteger("4f4", 16)))742failCount++;743744// Test use of a lot of radices745for (int i=2; i<17; i++) {746sc = new Scanner("1111");747if (!sc.nextBigInteger(i).equals(new BigInteger("1111", i)))748failCount++;749}750751report("BigInteger pattern");752}753754public static void bigDecimalPatternTest(int sourceType) throws Exception {755Scanner sc = scannerFor("23 45.99 -45,067.444 3.4e10", sourceType);756if (!sc.nextBigDecimal().equals(BigDecimal.valueOf(23)))757failCount++;758if (!sc.nextBigDecimal().equals(new BigDecimal("45.99")))759failCount++;760if (!sc.nextBigDecimal().equals(new BigDecimal("-45067.444")))761failCount++;762if (!sc.nextBigDecimal().equals(new BigDecimal("3.4e10")))763failCount++;764report("BigDecimal pattern");765}766767public static void integerPatternTest(int sourceType) throws Exception {768String input =769"1 22 f FF Z -3 -44 123 1,200 -123 -3,400,000 5,40 ,500 ";770Scanner sc = scannerFor(input, sourceType);771integerPatternBody(sc);772CharBuffer cb = CharBuffer.wrap(input);773sc = new Scanner(cb);774integerPatternBody(sc);775report("Integer pattern");776}777778public static void integerPatternBody(Scanner sc) throws Exception {779if (sc.nextInt() != 1) failCount++;780if (sc.nextShort() != 22) failCount++;781if (sc.nextShort(16) != 15) failCount++;782if (sc.nextShort(16) != 255) failCount++;783if (sc.nextShort(36) != 35) failCount++;784if (!sc.hasNextInt()) failCount++;785if (sc.nextInt() != -3) failCount++;786if (sc.nextInt() != -44) failCount++;787if (sc.nextLong() != 123) failCount++;788if (!sc.hasNextInt()) failCount++;789if (sc.nextInt() != 1200) failCount++;790if (sc.nextInt() != -123) failCount++;791if (sc.nextInt() != -3400000) failCount++;792try {793sc.nextInt();794failCount++;795} catch (InputMismatchException ime) {796// Correct result797}798sc.next();799try {800sc.nextLong();801failCount++;802} catch (InputMismatchException ime) {803// Correct result804}805sc.next();806try {807sc.next();808failCount++;809} catch (InputMismatchException ime) {810failCount++;811} catch (NoSuchElementException nse) {812// Correct result813}814}815816public static void floatPatternTest(int sourceType) throws Exception {817String input =818"090.090 1 22.0 -3 -44.05 +.123 -.1234 -3400000 56,566.6 " +819"Infinity +Infinity -Infinity NaN -NaN +NaN 5.4.0 5-.00 ++6.07";820Scanner sc = scannerFor(input, sourceType);821floatPatternBody(sc);822CharBuffer cb = CharBuffer.wrap(input);823sc = new Scanner(cb);824floatPatternBody(sc);825report("Float pattern");826}827828public static void floatPatternBody(Scanner sc) throws Exception {829if (sc.nextFloat() != 090.090f) failCount++;830if (sc.nextFloat() != 1f) failCount++;831if (sc.nextFloat() != 22.0f) failCount++;832if (sc.nextDouble() != -3d) failCount++;833if (sc.nextDouble() != -44.05d) failCount++;834if (sc.nextFloat() != .123f) failCount++;835if (sc.nextFloat() != -.1234f) failCount++;836if (sc.nextDouble() != -3400000d) failCount++;837if (sc.nextDouble() != 56566.6d) failCount++;838if (sc.nextDouble() != Double.POSITIVE_INFINITY) failCount++;839if (sc.nextDouble() != Double.POSITIVE_INFINITY) failCount++;840if (sc.nextDouble() != Double.NEGATIVE_INFINITY) failCount++;841if (!Double.valueOf(sc.nextDouble()).isNaN()) failCount++;842if (!Double.valueOf(sc.nextDouble()).isNaN()) failCount++;843if (!Double.valueOf(sc.nextDouble()).isNaN()) failCount++;844try {845sc.nextFloat();846failCount++;847} catch (NoSuchElementException nse) {848// Correct result849}850try {851sc.nextDouble();852failCount++;853} catch (NoSuchElementException nse) {854// Correct result855}856try {857sc.nextDouble();858failCount++;859} catch (NoSuchElementException nse) {860// Correct result861}862}863864public static void fromFileTest() throws Exception {865File f = new File(System.getProperty("test.src", "."), "input.txt");866Scanner sc = new Scanner(f).useDelimiter("\n+");867String testDataTag = sc.findWithinHorizon("fromFileTest", 0);868if (!testDataTag.equals("fromFileTest"))869failCount++;870871int count = 0;872while (sc.hasNextLong()) {873long blah = sc.nextLong();874count++;875}876if (count != 7)877failCount++;878sc.close();879report("From file");880}881882private static void example1() throws Exception {883Scanner s = new Scanner("1 fish 2 fish red fish blue fish");884s.useDelimiter("\\s*fish\\s*");885List <String> results = new ArrayList<String>();886while(s.hasNext())887results.add(s.next());888System.out.println(results);889}890891private static void example2() throws Exception {892Scanner s = new Scanner("1 fish 2 fish red fish blue fish");893s.useDelimiter("\\s*fish\\s*");894System.out.println(s.nextInt());895System.out.println(s.nextInt());896System.out.println(s.next());897System.out.println(s.next());898}899900private static void example3() throws Exception {901Scanner s = new Scanner("1 fish 2 fish red fish blue fish");902s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)");903for (int i=1; i<=s.match().groupCount(); i++)904System.out.println(s.match().group(i));905}906907private static void findInLineTest() throws Exception {908Scanner s = new Scanner("abc def ghi jkl mno");909Pattern letters = Pattern.compile("[a-z]+");910Pattern frogs = Pattern.compile("frogs");911String str = s.findInLine(letters);912if (!str.equals("abc"))913failCount++;914if (!s.hasNext(letters))915failCount++;916try {917str = s.findInLine(frogs);918} catch (NoSuchElementException nsee) {919// Correct920}921if (!s.hasNext())922failCount++;923if (!s.hasNext(letters))924failCount++;925str = s.findInLine(letters);926if (!str.equals("def"))927failCount++;928929report("Find patterns");930}931932private static void findInEmptyLineTest() throws Exception {933String eol = System.getProperty("line.separator");934Scanner s = new Scanner("line 1" + eol + "" + eol + "line 3" + eol);935int lineNo = 0;936while (s.hasNextLine()) {937lineNo++;938s.findInLine("3");939s.nextLine();940}941if (lineNo != 3)942failCount++;943report("findInEmptyLine test");944}945946private static void matchTest() throws Exception {947Scanner s = new Scanner("1 fish 2 fish red fish blue fish");948s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)");949950MatchResult result = s.match();951if (!result.group(1).equals("1"))952failCount++;953if (!result.group(2).equals("2"))954failCount++;955if (!result.group(3).equals("red"))956failCount++;957if (!result.group(4).equals("blue"))958failCount++;959960report("Match patterns");961}962963private static void skipTest() throws Exception {964Scanner s = new Scanner("abc def ghi jkl mno");965Pattern letters = Pattern.compile("[a-z]+");966Pattern spaceLetters = Pattern.compile(" [a-z]+");967Pattern frogs = Pattern.compile("frogs");968try {969s.skip(letters);970} catch (NoSuchElementException ime) {971failCount++;972}973String token = s.next(letters);974if (!token.equals("def")) {975System.out.println("expected def");976System.out.println("I found "+token);977failCount++;978}979try {980s.skip(letters);981failCount++;982} catch (NoSuchElementException ime) {983// Correct result984}985token = s.next(letters);986if (!token.equals("ghi")) {987System.out.println("expected ghi");988System.out.println("I found "+token);989failCount++;990}991try {992s.skip(letters);993failCount++;994} catch (NoSuchElementException ime) {995// Correct result because skip ignores delims996}997try {998s.skip(spaceLetters);999} catch (NoSuchElementException ime) {1000failCount++;1001}1002token = s.next(letters);1003if (!token.equals("mno")) {1004System.out.println("expected mno");1005System.out.println("I found "+token);1006failCount++;1007}1008try {1009s.skip(letters);1010failCount++;1011} catch (NoSuchElementException ime) {1012// Correct result1013}1014report("Skip patterns");1015}10161017private static void byteTest(int sourceType) throws Exception {1018String input = " 3 0 00 b -B 012 44 -55 12 127 129 -131 dog 0x12";1019Scanner s = scannerFor(input, sourceType);1020if (!s.hasNextByte()) failCount++;1021if (s.nextByte() != (byte)3) failCount++;1022if (!s.hasNextByte()) failCount++;1023if (s.nextByte() != (byte)0) failCount++;1024if (!s.hasNextByte()) failCount++;1025if (s.nextByte() != (byte)0) failCount++;1026if (!s.hasNextByte(16)) failCount++;1027if (s.nextByte(16) != (byte)11)failCount++;1028if (!s.hasNextByte(16)) failCount++;1029if (s.nextByte(16) != (byte)-11) failCount++;1030if (!s.hasNextByte()) failCount++;1031if (s.nextByte() != (byte)12) failCount++;1032if (!s.hasNextByte()) failCount++;1033if (s.nextByte() != (byte)44) failCount++;1034if (!s.hasNextByte()) failCount++;1035if (s.nextByte() != (byte)-55) failCount++;1036if (!s.hasNextByte()) failCount++;1037if (s.nextByte() != (byte)12) failCount++;1038if (!s.hasNextByte()) failCount++;1039if (s.nextByte() != (byte)127) failCount++;1040if (s.hasNextByte()) failCount++;10411042try {1043s.nextByte();1044failCount++;1045} catch (InputMismatchException ime) {1046// Correct result1047}1048if (s.hasNextByte()) failCount++;1049if (s.nextInt() != 129) failCount++;1050if (s.hasNextByte()) failCount++;1051try {1052s.nextByte();1053failCount++;1054} catch (InputMismatchException ime) {1055// Correct result1056}1057if (s.nextInt() != -131) failCount++;1058if (s.hasNextByte()) failCount++;1059try {1060s.nextByte();1061failCount++;1062} catch (InputMismatchException ime) {1063// Correct result1064}1065s.next(Pattern.compile("\\w+"));1066if (s.hasNextByte())1067failCount++;1068try {1069s.nextByte();1070failCount++;1071} catch (NoSuchElementException nsee) {1072// Correct result1073}1074s.next();1075if (s.hasNextByte())1076failCount++;1077try {1078byte bb = s.nextByte();1079failCount++;1080} catch (NoSuchElementException nsee) {1081// Correct result1082}1083report("Scan bytes");1084}10851086private static void shortTest(int sourceType) throws Exception {1087String input = " 017 22 00E -34 44,333 -53999 0x19 dog";1088Scanner s = scannerFor(input, sourceType);1089if (!s.hasNextShort()) failCount++;1090if (s.nextShort() != (short)17) failCount++;1091if (!s.hasNextShort()) failCount++;1092if (s.nextShort() != (short)22) failCount++;1093if (!s.hasNextShort(16)) failCount++;1094if (s.nextShort(16) != (short)14) failCount++;1095if (!s.hasNextShort()) failCount++;1096if (s.nextShort() != (short)-34) failCount++;1097for (int i=0; i<4; i++) {1098if (s.hasNextShort())1099failCount++;1100try {1101s.nextShort();1102failCount++;1103} catch (InputMismatchException ime) {1104// Correct result1105}1106s.next();1107}1108try {1109s.next();1110failCount++;1111} catch (InputMismatchException ime) {1112failCount++;1113} catch (NoSuchElementException nse) {1114// Correct result1115}1116report("Scan shorts");1117}11181119private static void intTest(int sourceType) throws Exception {1120Scanner s = scannerFor(1121"22 022 C -34 0x80000000 -2147483649 dog ", sourceType);1122if (!s.hasNextInt()) failCount++;1123if (s.nextInt() != 22) failCount++;1124if (!s.hasNextInt()) failCount++;1125if (s.nextInt() != 22) failCount++;1126if (!s.hasNextInt(16)) failCount++;1127if (s.nextInt(16) != 12) failCount++;1128if (!s.hasNextInt()) failCount++;1129if (s.nextInt() != -34) failCount++;1130for (int i=0; i<3; i++) {1131if (s.hasNextInt())1132failCount++;1133try {1134s.nextInt();1135failCount++;1136} catch (InputMismatchException ime) {1137// Correct result1138}1139s.next();1140}1141try {1142s.next();1143failCount++;1144} catch (InputMismatchException ime) {1145failCount++;1146} catch (NoSuchElementException nse) {1147// Correct result1148}1149report("Scan ints");1150}11511152private static void longTest(int sourceType) throws Exception {1153Scanner s = scannerFor(1154"022 9223372036854775807 0x8000000000000000 9223372036854775808 dog ",1155sourceType);1156if (!s.hasNextLong()) failCount++;1157if (s.nextLong() != (long)22) failCount++;1158if (!s.hasNextLong()) failCount++;1159if (s.nextLong() != 9223372036854775807L) failCount++;1160for (int i=0; i<3; i++) {1161if (s.hasNextLong())1162failCount++;1163try {1164s.nextLong();1165failCount++;1166} catch (InputMismatchException ime) {1167// Correct result1168}1169s.next();1170}1171try {1172s.next();1173failCount++;1174} catch (InputMismatchException ime) {1175failCount++;1176} catch (NoSuchElementException nse) {1177// Correct result1178}1179report("Scan longs");1180}11811182private static void floatTest(int sourceType) throws Exception {1183Scanner s = scannerFor(1184"0 0. 0.0 2 2. 2.0 2.3 -2 -2.0 -2.3 -. 2-. 2..3", sourceType);1185if (!s.hasNextFloat()) failCount++;1186if (s.nextFloat() != 0f) failCount++;1187if (!s.hasNextFloat()) failCount++;1188if (s.nextFloat() != 0f) failCount++;1189if (!s.hasNextFloat()) failCount++;1190if (s.nextFloat() != 0f) failCount++;1191if (!s.hasNextFloat()) failCount++;1192if (s.nextFloat() != 2f) failCount++;1193if (!s.hasNextFloat()) failCount++;1194if (s.nextFloat() != 2f) failCount++;1195if (!s.hasNextFloat()) failCount++;1196if (s.nextFloat() != 2f) failCount++;1197if (!s.hasNextFloat()) failCount++;1198if (s.nextFloat() != 2.3f) failCount++;1199if (!s.hasNextFloat()) failCount++;1200if (s.nextFloat() != -2f) failCount++;1201if (!s.hasNextFloat()) failCount++;1202if (s.nextFloat() != -2f) failCount++;1203if (!s.hasNextFloat()) failCount++;1204if (s.nextFloat() != -2.3f) failCount++;1205for (int i=0; i<3; i++) {1206if (s.hasNextLong())1207failCount++;1208try {1209s.nextFloat();1210failCount++;1211} catch (InputMismatchException ime) {1212// Correct result1213}1214s.next();1215}1216try {1217s.next();1218failCount++;1219} catch (InputMismatchException ime) {1220failCount++;1221} catch (NoSuchElementException nse) {1222// Correct result1223}1224report("Scan floats");1225}12261227private static void doubleTest(int sourceType) throws Exception {1228Scanner s = scannerFor(1229"0 0. 0.0 2 2. 2.0 2.3 -2 -2.0 -2.3 -. 2-. 2..3", sourceType);1230if (!s.hasNextDouble()) failCount++;1231if (s.nextDouble() != 0d) failCount++;1232if (!s.hasNextDouble()) failCount++;1233if (s.nextDouble() != 0d) failCount++;1234if (!s.hasNextDouble()) failCount++;1235if (s.nextDouble() != 0d) failCount++;1236if (!s.hasNextDouble()) failCount++;1237if (s.nextDouble() != 2d) failCount++;1238if (!s.hasNextDouble()) failCount++;1239if (s.nextDouble() != 2d) failCount++;1240if (!s.hasNextDouble()) failCount++;1241if (s.nextDouble() != 2d) failCount++;1242if (!s.hasNextDouble()) failCount++;1243if (s.nextDouble() != 2.3d) failCount++;1244if (!s.hasNextDouble()) failCount++;1245if (s.nextDouble() != -2d) failCount++;1246if (!s.hasNextDouble()) failCount++;1247if (s.nextDouble() != -2d) failCount++;1248if (!s.hasNextDouble()) failCount++;1249if (s.nextDouble() != -2.3d) failCount++;1250for (int i=0; i<3; i++) {1251if (s.hasNextLong())1252failCount++;1253try {1254s.nextDouble();1255failCount++;1256} catch (InputMismatchException ime) {1257// Correct result1258}1259s.next();1260}1261try {1262s.next();1263failCount++;1264} catch (InputMismatchException ime) {1265failCount++;1266} catch (NoSuchElementException nse) {1267// Correct result1268}1269report("Scan doubles");1270}12711272private static void booleanTest(int sourceType) throws Exception {1273Scanner s = scannerFor(1274" true false\t \r\n true FaLse \n True Tru", sourceType);1275if (!s.nextBoolean()) failCount++;1276if (!s.hasNextBoolean()) failCount++;1277if (s.nextBoolean()) failCount++;1278if (!s.nextBoolean()) failCount++;1279if (s.nextBoolean()) failCount++;1280if (!s.nextBoolean()) failCount++;1281if (s.hasNextBoolean()) failCount++;1282try {1283s.nextBoolean();1284failCount++;1285} catch (NoSuchElementException nsee) {1286// Expected result1287}1288report("Scan booleans");1289}12901291private static void hasNextTest(int sourceType) throws Exception {1292Scanner s = scannerFor(1293" blah blech\t blather alongblatherindeed", sourceType);1294if (!s.hasNext()) failCount++;1295if (!s.hasNext()) failCount++;1296String result = s.next();1297if (!result.equals("blah")) failCount++;1298if (!s.hasNext()) failCount++;1299if (!s.hasNext()) failCount++;1300result = s.next();1301if (!result.equals("blech")) failCount++;1302if (!s.hasNext()) failCount++;1303result = s.next();1304if (!result.equals("blather")) failCount++;1305if (!s.hasNext()) failCount++;1306if (!s.hasNext()) failCount++;1307result = s.next();1308if (!result.equals("alongblatherindeed")) failCount++;1309if (s.hasNext()) failCount++;1310try {1311result = s.next();1312failCount++;1313} catch (NoSuchElementException nsee) {1314// Correct result1315}1316report("Has next test");1317}13181319private static void nextTest(int sourceType) throws Exception {1320Scanner s = scannerFor(1321" blah blech\t blather alongblatherindeed", sourceType);1322String result = (String)s.next();1323if (!result.equals("blah")) failCount++;1324result = (String)s.next();1325if (!result.equals("blech")) failCount++;1326result = (String)s.next();1327if (!result.equals("blather")) failCount++;1328result = (String)s.next();1329if (!result.equals("alongblatherindeed"))1330failCount++;1331try {1332result = (String)s.next();1333failCount++;1334} catch (NoSuchElementException nsee) {1335// Correct result1336}1337report("Next test");1338}13391340private static void hasNextPatternTest(int sourceType) throws Exception {1341Scanner s = scannerFor(1342" blah blech\t blather alongblatherindeed", sourceType);1343Pattern p1 = Pattern.compile("\\w+");1344Pattern p2 = Pattern.compile("blech");1345if (!s.hasNext(p1)) failCount++;1346if (!s.hasNext(p1)) failCount++;1347if (s.hasNext(p2)) failCount++;1348String result = (String)s.next();1349if (!result.equals("blah")) failCount++;1350if (!s.hasNext(p1)) failCount++;1351if (!s.hasNext(p2)) failCount++;1352result = (String)s.next();1353if (!result.equals("blech")) failCount++;1354if (!s.hasNext(p1)) failCount++;1355if (s.hasNext(p2)) failCount++;1356result = (String)s.next();1357if (!result.equals("blather")) failCount++;1358if (!s.hasNext(p1)) failCount++;1359if (s.hasNext(p2)) failCount++;1360result = (String)s.next();1361if (!result.equals("alongblatherindeed")) failCount++;1362if (s.hasNext(p1)) failCount++;1363if (s.hasNext(p2)) failCount++;1364report("Has Next Pattern test");1365}13661367private static void nextPatternTest(int sourceType) throws Exception {1368Scanner s = scannerFor(1369" blah blech\t blather alongblatherindeed", sourceType);1370Pattern p1 = Pattern.compile("blah");1371Pattern p2 = Pattern.compile("blech");1372Pattern p3 = Pattern.compile("blather");1373Pattern p4 = Pattern.compile("alongblatherindeed");1374String result = null;1375try {1376result = (String)s.next(p2);1377failCount++;1378} catch (NoSuchElementException nsee) {1379// Correct result1380}1381result = (String)s.next(p1);1382if (!result.equals("blah"))1383failCount++;1384try {1385result = (String)s.next(p1);1386failCount++;1387} catch (NoSuchElementException nsee) {1388// Correct result1389}1390result = (String)s.next(p2);1391if (!result.equals("blech"))1392failCount++;1393try {1394result = (String)s.next(p4);1395failCount++;1396} catch (NoSuchElementException nsee) {1397// Correct result1398}1399result = (String)s.next(p3);1400if (!result.equals("blather"))1401failCount++;1402try {1403result = (String)s.next(p3);1404failCount++;1405} catch (NoSuchElementException nsee) {1406// Correct result1407}1408result = (String)s.next(p4);1409if (!result.equals("alongblatherindeed"))1410failCount++;1411try {1412result = (String)s.next();1413failCount++;1414} catch (NoSuchElementException nsee) {1415// Correct result1416}1417report("Next pattern test");1418}14191420private static void useLocaleTest() throws Exception {1421Scanner s = new Scanner("334.65").useLocale(Locale.ENGLISH);1422if (!s.hasNextFloat()) failCount++;1423if (s.nextFloat() != 334.65f) failCount++;14241425s = new Scanner("334,65").useLocale(Locale.FRENCH);1426if (!s.hasNextFloat()) failCount++;1427if (s.nextFloat() != 334.65f) failCount++;14281429s = new Scanner("4.334,65").useLocale(Locale.GERMAN);1430if (!s.hasNextFloat()) failCount++;1431if (s.nextFloat() != 4334.65f) failCount++;14321433// Test case reported from India1434try {1435String Message = "123978.90 $";1436Locale locale = new Locale("hi","IN");1437NumberFormat form = NumberFormat.getInstance(locale);1438double myNumber = 1902.09;1439Scanner scanner = new Scanner(form.format(myNumber).toString());1440scanner.useLocale(locale);1441double d = scanner.nextDouble();1442} catch (InputMismatchException ime) {1443failCount++;1444}1445report("Use locale test");1446}14471448public static void resetTest() throws Exception {1449Scanner sc = new Scanner("");1450int radix = sc.radix();1451Locale locale = sc.locale();1452Pattern delimiter = sc.delimiter();1453Pattern a = Pattern.compile("A");1454sc.useDelimiter(a);1455Locale dummy = new Locale("en", "US", "dummy");1456sc.useLocale(dummy);1457sc.useRadix(16);1458if (sc.radix() != 16 ||1459!sc.locale().equals(dummy) ||1460!sc.delimiter().pattern().equals(a.pattern())) {1461failCount++;1462} else {1463sc.reset();1464if (sc.radix() != radix ||1465!sc.locale().equals(locale) ||1466!sc.delimiter().pattern().equals(delimiter.pattern())) {1467failCount++;1468}1469}1470sc.close();1471report("Reset test");1472}14731474private static void report(String testName) {1475int spacesToAdd = 30 - testName.length();1476StringBuffer paddedNameBuffer = new StringBuffer(testName);1477for (int i=0; i<spacesToAdd; i++)1478paddedNameBuffer.append(" ");1479String paddedName = paddedNameBuffer.toString();1480System.err.println(paddedName + ": " +1481(failCount==0 ? "Passed":"Failed("+failCount+")"));1482if (failCount > 0)1483failure = true;1484failCount = 0;1485}14861487static Scanner scannerFor(String input, int sourceType) {1488if (sourceType == 1)1489return new Scanner(input);1490else1491return new Scanner(new StutteringInputStream(input));1492}14931494static class ThrowingReadable implements Readable {1495ThrowingReadable() {1496}1497public int read(java.nio.CharBuffer cb) throws IOException {1498throw new IOException("ThrowingReadable always throws");1499}1500}1501}150215031504