Scanner.next

Hi, i have am required to use the scanner class to get my input for an assisgnment, however when i used the codes below :
Scanner scanner = new Scanner(System.in);
String lineSeparator
= System.getProperty("line.separator");
scanner.useDelimiter(lineSeparator);
String quote;
System.out.print("Enter my quote:");
quote = scanner.next();
System.out.println("Your have entered:" + quote);
My drJava just give me an endless loop for input instead of showing what i have type which is "test testing testings". Can anyone help me and tell me what's wrong with these codes?
Thanks~!

Where is your breaking condition?
The code should be like this:
if(quote.equals("OK"))
break;
else
.......

Similar Messages

  • Scanner next method... wtf?

    Code:import java.io.*;
    import java.util.*;
    public class Test
         public static void main(String[] args)
              File file = new File("prob.in");
              Scanner scan = null;
              try{
                   scan = new Scanner(file);
              }catch(FileNotFoundException e){}
              ArrayList<Character> arr = new ArrayList<Character>();
              String[] keys = new String[10];
              keys[0] = "0";
              keys[1] = "@.?1";
              keys[2] = "ABC2";
              keys[3] = "DEF3";
              keys[4] = "GHI4";
              keys[5] = "JKL5";
              keys[6] = "MNO6";
              keys[7] = "PQRS7";
              keys[8] = "TUV8";
              keys[9] = "WXYZ9";
              String strtest = scan.next();
              System.out.print(strtest);
    }Make prob.in whatever you want, it doesn't matter, I just want to get a string from the first line of it. But when I try to run it I get a NullPointerException on line 25. Why is this?

    Ya, but even if it doesn't do anything there, I'll
    eventually get a NullPointerException down the line.What do you mean? Why do you think that? What does that have to do with anything?
    I figured out my problem. I just recently started
    using eclipse instead of JCreator, and I forgot to
    put the file in the project folder. But I was
    wondering, how can you get the whole line without it
    stopping on the spaces. For example, my prob file
    says 4433 555 555 666* 9666 777 555 3* 222 9992
    #555 8888777 *. When I use the next() method,
    it only returns "4433". Is there a way for it to get
    the whole line with the spaces, or am I going to have
    to make some loop?Have you looked through Scanner's methods to see if one of them might help you?
    Even if you find such a method though, how will it help? Are you going to process the whole line as a single piece? Or are you going to have to loop over its pieces anyway?

  • Reading a String with Scanner and ignoring whitespace

    Hi,
    This has probably been asked a million times, and I've searched Google and these forums, but I haven't found an answer that works for me.
    I have some class that needs to read user input from the command line, so I figured I'd use Scanner, since I've seen it used umpteen-hundred times in all the "do my homework" threads. I want to print out some line to the terminal, which will prompt the user to enter something. The user should then enter something and hit enter, and the Scanner should store the input in a variable of sorts.
    I've tried using Scanner.nextLine(), but that does not block for user input and the program terminates. I've tried Scanner.next() which does block for user input and allows the user to input something, but I cannot find a way to read the entire String; it will stop reading when it reaches whitespace. I've tried using a delimiter, but that seems to terminate the program when I prompt for the input, similar to Scanner.nextLine().
    Here's what I have at the moment:
    Scanner scanner = new Scanner(System.in); //I have also tried useDelimiter("\\s")
    System.out.print("Enter the desired command: ");
    String name = scanner.next();
    System.out.println("Command entered: " + name);The above code will work if the command is only one word, e.g. "connect". If the command is more than one word, it will only store the first word in the name variable. Again, I've tried using a delimiter for whitespace, but that hasn't worked.
    Is there a way to solve this problem? Perhaps I need to use another tool to read user input from the terminal? Am I just missing something? Do I need to explain more?
    Any advice is appreciated.
    Thanks

    I don't know why scanner.nextLine() doesn't work for you, it does for me with the following (copied) code:
    import java.util.Scanner;
    class Z
        public static void main(String[] args)
            Scanner scanner = new Scanner(System.in); //I have also tried useDelimiter("\\s")
            System.out.print("Enter the desired command: ");
            String name = scanner.nextLine();
            System.out.println("Command entered: " + name);
        }

  • How to use the scanner class to ask for a character?

    Hey guys, this is my assignment:
    Ask the user for a single letter and a sentence, and print out the
    number of times that letter shows up in the sentence.
    Please tell me how to scan for a character. I tried this:
    import java.util.Scanner;
    public class Frequencies
        public static final void main(String[] args)
            Scanner scanner = new Scanner(System.in);
            Scanner scan = new Scanner(System.in);
            System.out.println("Enter a sentence");
            String x = scanner.next();
            System.out.println("Enter a letter to look for");
            String y = scan.next();
            char z = y.charAt(0);
            int chara = 0;
            for(int i = 0; i<x.length(); i++){
                    if(z==y.charAt(i)){
                            chara = chara++;
            System.out.println("There are " + chara + " " + z + "s in the sentence");
    }and got the error after Running (not compiling):
    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
            at java.lang.String.charAt(String.java:687)
            at Frequencies.main(Frequencies.java:16)I thought this meant that I was asking for the character in postition 1 of string y, but in my code I wrote position 0
    when I tried inserting words in the character place (just to see what happened, not expecting functionallity, I got
    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: [NUMBER OF CHARACTERS]
            at java.lang.String.charAt(String.java:687)
            at Frequencies.main(Frequencies.java:16)Please help.
    The assignment isn't due nor graded, this is just killing me lol.
    Thanks in advance
    Edited by: Sevan on Oct 18, 2008 4:40 PM

    jverd wrote:
    Skydev2u wrote:
    I've used this method for a while now and it gets the job done.
    import java.util.Scanner;
    public class ReadInput {
    public static void main(String[] args) {
    Scanner UserInput = new Scanner(System.in);
    char letter = UserInput.findWithinHorizon(".", 0).charAt(0);
    I know you're trying to help, but this isn't really doing it. It does nothing to address the source of the OP's problem. The way he's doing it now is almost right. He just needs to do a tiny bit of detective work to fix a small bug. Tossing off a totally different approach, with no explanation, is not particularly helpful.Your right jverd I skimmed the OP's problem too quick;y and in tern didn't understand it fully. After reading the post thoroughly I saw that the problem can be solved by taking the sentence the user enters and then converting it into a array of characters. Then searching for the specific letter the user enters is achieved by comparing it to each individual element of the char array. Then incrementing a counter variable each time a match is made. I hope this example code solve your problem.
    * @author skydev
    import java.util.Scanner;
    public class SentenceReader {
        public static void main(String[] args) {
            int counter = 0; //Amount of time the letter appears in the sentence
            char letter;    //Letter the user search for
            char[] sentenceArray; //char array to hold the elements of the string the user inputs
            String sentence; //sentence the user inputs
            Scanner UserInput = new Scanner(System.in);
            System.out.println("Please enter a sentence! ");
            sentence = UserInput.nextLine();
            sentenceArray = sentence.toCharArray(); //splits up the users sentence into a array of char
            System.out.println("Please enter a letter to search for ");
            letter = UserInput.findWithinHorizon(".", 0).charAt(0);
             for(int i = 0; i < sentence.length(); i++){
                    if(letter == sentenceArray){ //search to see if the letter of interest equals to each char (letter) of the array
    counter++; //increments the amount of time the letter appears, set to 0 by default
    System.out.println("The letter appeared " + counter + " times in the sentence"); //Displays the result :) I love programming

  • Scanner input error

    I want to make a very simple program that allows the user to enter a key/character and have the corresponding unicode value returned. The problem is that I receive an error after the input of any character.
    Here is the code:
    import java.util.Scanner;
    public class KeyMap
    public static void main (String args[])
    int number; //the future unicode value.
              System.out.print ("Enter the key you want the unicode number of: ");
              Scanner scan = new Scanner (System.in);
              number = scan.nextInt();
              char key = (char)number;
              System.out.print ("The number for key " + key + " is " + number);
    And I get this error in the run log after the character is entered:
    Exception in thread "main" java.util.InputMismatchException
         at java.util.Scanner.throwFor(Scanner.java:819)
         at java.util.Scanner.next(Scanner.java:1431)
         at java.util.Scanner.nextInt(Scanner.java:2040)
         at java.util.Scanner.nextInt(Scanner.java:2000)
         at KeyMap.main(KeyMap.java:11)
    KeyMap has exited with status 1.
    Thanks for any help!

    Exception in thread "main"
    java.util.InputMismatchException
         at java.util.Scanner.throwFor(Scanner.java:819)
         at java.util.Scanner.next(Scanner.java:1431)
         at java.util.Scanner.nextInt(Scanner.java:2040)
         at java.util.Scanner.nextInt(Scanner.java:2000)
         at KeyMap.main(KeyMap.java:11)Well that's coz your listening for an Integer input.
    the error should happen if you input non-integer data type.
    Nywled

  • Error when importing java.util.Scanner

    Agh! I'm in an introduction to computer science course, and I am writing a program as an assignment that's due tomorrow.
    I have imported java.util.Scanner before, but I've only run it on the Windows PCs in the lab, whereas I am currently on a Mac. I've updated to the latest version of Java (through the software update), and I'm running Tiger (also fully updated).
    I'm using Dr. Java to write the programs, but I tried using the very same thing in Eclipse and it didn't work. Here's my program:
    import java.util.Random;
    import java.util.Scanner;
    public class Password {
    public static void main(String[] args) {
    //create a Scanner object to read from the keyboard:
    String password;
    Scanner scanner = new Scanner(System.in);
    Random randomizer = new Random();
    System.out.println("Please enter a string containing candidate characters.");
    String input = scanner.next();
    int charLength = length(input);
    System.out.print("Random password: ");
    System.out.print(input.substring(randomizer.nextInt(charLength)));
    System.out.print(input.substring(randomizer.nextInt(charLength)));
    System.out.print(input.substring(randomizer.nextInt(charLength)));
    System.out.println(input.substring(randomizer.nextInt(charLength)));
    And, here's my errors:
    4 errors found:
    File: /Users/brianmoore/Desktop/Password.java [line: 11]
    Error: cannot resolve symbol
    symbol : class Scanner
    location: package util
    File: /Users/brianmoore/Desktop/Password.java [line: 18]
    Error: cannot resolve symbol
    symbol : class Scanner
    location: class Password
    File: /Users/brianmoore/Desktop/Password.java [line: 18]
    Error: cannot resolve symbol
    symbol : class Scanner
    location: class Password
    File: /Users/brianmoore/Desktop/Password.java [line: 22]
    Error: cannot resolve symbol
    symbol : method length (java.lang.String)
    location: class Password
    Any ideas?

    Ok. I figured it out. On the Dr. Java page, this is what helped me:
    Please verify the following:
    - Open "/Applications/Utilities/Java/J2SE 5.0/Java
    Preferences";
    make sure "J2SE 5.0" is at the top of the list under
    "Java
    Application Runtime"
    - Open DrJava; go to Edit->Preferences; make sure
    "Tools.jar
    Location", "JSR-14 Location", and "JSR-14
    Collections Path"
    are all blank
    - Open the Help->About dialog box; make sure the "DrJava
    Version" listed is 20050601-0007 or later (that is, later
    than
    June 1, 2005)
    - Go to the "System Properties" tab in the
    "About" box; make
    sure "java.version" is 1.4.2.
    Let us know what you find out if you're still having
    trouble.
    Thanks for your help!

  • Opening a file with Scanner FUNNY CODE

    public class ScanXan {
    public static void main(String[] args) throws IOException {
    Scanner s = null;
    Scanner t = null;
    try {
    s = new Scanner(new BufferedReader(new FileReader("cd79.txt")));
    t = new Scanner(new BufferedReader(new FileReader("local41.txt")));
    while (s.hasNext()) {
    String tempS = s.next();
    while (t.hasNext()){
    if (tempS.equals(t.nextLine())) {
    System.out.println("Repeated: " + t.next());
    catch (IOException e) {
    e.printStackTrace();
    finally {
    if (s != null) {
    s.close();
    ANYTHING WRONG WITH THIS? I'M TRYING TO COMPARE THE FIRST LINE OF A TXT FILE WITH ALL THE lines from the other file. HOWEVER, When i run it, t.hasNext() STARTS READING FROM THE 4TH LINE OF THE FILE.
    I can't figure it out. help please
    thanks
    Edited by: lsn67a02j3 on Mar 21, 2009 7:35 PM
    Edited by: lsn67a02j3 on Mar 21, 2009 7:38 PM

    (When you post code, use the "code" tags. Either highlight your code and click the button with the label "CODE" or put {code} at the start of your code and the same thing again at the end. This makes the code readable.)
    When i run it, t.hasNext() STARTS READING FROM THE 4TH LINE OF THE FILEHow do you know this? It is often a good idea to lard your code with System.out.println() statements (or use a debugger) so that you can tell, objectively, what is happening. It may help, too, to make sure your two input files are chosen so that they have readily identifiable lines.
    while (s.hasNext()) {
        String tempS = s.next();
        while (t.hasNext()){This looks odd. You want to compare the line returned by s with all of the lines returned by t. But think about what will happen the second time around the loop: t.hasNext() is going to be false right from the start. It would be better to create a new Scanner each time around the outer loop.
    if (tempS.equals(t.nextLine())) {
        System.out.println("Repeated: " + t.next());
    }In the event of a match this results in two scanner "next" calls. Is this what you mean to do?

  • Scanner Pattern...please help

    Hi everybody....I?m new to Java and having some problems....
    this is my Program ( I didn't finish all of it)
    import java.util.Scanner;
    public class Winkel
         //Attribute
         int grad;
         int minuten;
         double sekunden;
         //Konstruktoren
         public Winkel(int g,int m,double s)
              this.grad=g;
              this.minuten=m;
              this.sekunden=s;
         public Winkel(int g,int m)
              this.grad=g;
              this.minuten=m;
         public Winkel(int g)
              this.grad=g;
         public Winkel()
              this.grad=0;
         public Winkel(String str)
              Scanner s = new Scanner(str).useDelimiter("[&#9702; ?\"]");
              this.grad = s.nextInt();
              this.minuten = s.nextInt();
    /*          this.sekunden=sc.nextDouble();*/
         public void setze(int g,int m,double s)
              grad=g;
              minuten=m;
              sekunden=s;
         public double alsDouble()
              return (double)this.grad;
         public static void main(String argv[])
              Winkel w=new Winkel("5? 7' 8\" ");
              System.out.println(w.alsDouble());
    when I try to compile it i get this fehler
    ymnrad@ymnrad:~/Desktop> java Winkel
    Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:817)
    at java.util.Scanner.next(Scanner.java:1431)
    at java.util.Scanner.nextInt(Scanner.java:2040)
    at java.util.Scanner.nextInt(Scanner.java:2000)
    at Winkel.<init>(Winkel.java:36)
    at Winkel.main(Winkel.java:56)
    where is my mistake .......can u plz help me...

    Ymnrad wrote:
    Ok, I tried what u said but the answer I got was the first element ( 5) and I didnt get the next one??
    Scanner s = new Scanner("5? 7' 8\" ").useDelimiter("[\\D]+");
    while(s.hasNextInt()) System.out.println(s.nextInt());
    {code}
    Details:
    [http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Scanner can't read CTRL-I?

    Hi All,
    I'm trying to read input in from the command line using Scanner. I need to be able to read both Strings and control characters. I'm only expecting certain kinds of input so I have an array of Strings and control characters that correspond to those inputs. The problem is that the CTRL-I input does not work. All of the other control characters are read correctly except for CTRL-I. Does anyone know why this could be?
    Here's a sample test class that shows what I'm doing:
    import java.util.Scanner;
    import java.util.regex.Pattern;
    public class ScannerTest {
        public static String[] patterns = new String[]{"\\cX", "\\cI", "str1", "str2", "\\cU", "\\cT", "\\cV"};
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()) {
                Integer command = getNext(scanner);
                switch (command) {
                    case 0:
                        System.out.println("Control-x found");
                        break;
                    case 1:
                        System.out.println("Control-i found");
                        break;
                    case 2:
                        System.out.println("str1 found");
                        break;
                    case 3:
                        System.out.println("str2 found");
                        break;
                    case 4:
                        System.out.println("Control-u found");
                        break;
                    case 5:
                        System.out.println("Control-t found");
                        break;
                    case 6:
                        System.out.println("Control-v found");
                        break;
                    default:
                        System.out.println("Unknown command");
                        scanner.next();
                        break;
            System.out.println("done.");
        public static Integer getNext(Scanner scanner) {
            Integer ret = -1;
            Pattern p = null;
            for (int i = 0; i < patterns.length; i++) {
                p = Pattern.compile(patterns);
    try {
    scanner.next(p);
    return i;
    } catch (Throwable t) {
    return ret;
    }Thanks for your help.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    sabre150 wrote:
    This following code results in 'true' so the problem would seem to be scanner or System.in.
            Pattern p = Pattern.compile("\\cI");
    System.out.println(p.matcher("\t").find());Some simple tests indicate that \t is included in the set of separators so one can never get a value from next(Pattern p) that >includes a \t .
    Edited by: sabre150 on Mar 18, 2009 5:39 PMThat makes sense.
    >
    But if you doscanner.useDelimiter(" +");then it works as you expect.
    Edited by: sabre150 on Mar 18, 2009 5:43 PMThat didn't work for me and it broke the other control characters. Can you tell me what " +" is intended to do as a delimiter?
    Thanks for your reply.

  • Problems with scanner

    Hi I'm trying to do a make this simple program:
    import java.util.Scanner;
    public class quadrGlgApp
    public static void main(String[] args)
    double a, b, c;
    Scanner scan = new Scanner(System.in);
    a = scan.nextDouble();
    b = scan.nextDouble();
    c = scan.nextDouble();
    GlgLoesen(a,b,c);
    protected static void GlgLoesen(double a,double b,double c)
    double x1, x2, D;
    System.out.println("");
    System.out.println(a+"(x^2)+"+b+"x+"+c+"=0");
    if (a==0)
    if (b==0)
    if (c==0){
    System.out.println("=> x kann jeden beliebigen Wert annehmen!");
    }else
    System.out.println("=> Es existiert keine Loesung fuer x!");
    }else{
    x1=-(c/b);
    System.out.println("=> x="+x1);
    }else{
    D= ((b*b)-4*a*c);
    if(D>0)
    D= Math.sqrt(D);
    x1=(-b+D)/2*a;
    x2=(-b-D)/2*a;
    System.out.println("=> x1="+x1);
    System.out.println("=> x2="+x2);
    }else{
    if(D==0)
    x1=-b/2*a;
    System.out.println("=> x="+x1);
    }else
    System.out.println("=> Es existiert keine reelle Loesung!");
    It's running, but if I try to write something in a, let`s take for example 2.0, this is the result:
    2.0
    Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:819)
    at java.util.Scanner.next(Scanner.java:1431)
    at java.util.Scanner.nextDouble(Scanner.java:2335)
    at quadrGlgApp.main(quadrGlgApp.java:17)
    Process completed.
    What is wrong? Please help, me.
    p.s.:please excuse my bad english

    One thread's enough.
    http://forum.java.sun.com/thread.jspa?threadID=773139

  • Static class containing scanner throws java.util.NoSuchElementException

    I use the scanner class pretty often in my coding and recently i have been trying to create a static method i can put in an external class to do the scanning for me and trap any errors.
    I seem to be able to create the class successfully but i have a slight problem in that i cannot use the method twice in the same program without having it throw a java.util.NoSuchElementException
    If anyone could figure out what error i have made and suggest a way to fix it i would be very grateful
    code is as follows:
    Scan.java:
    // name information removed for privacy
      // class info removed for privacy
      Assignment: 4.3,
      File Name: /ASSIGNMENTS/ASSIGNMENT_4/Part3/Scan.java
    import java.util.Scanner;
    public class Scan
      public static double nextDouble (String prompt)
        // variable to hold the result
        double result = 0.0;
        // variable to determine if input was ok
        Boolean inputOK = false;
        // do-while loop to get some input
        do
          // print the prompt. what do you want to ask for?
          System.out.print ( prompt );
          // Try to scan and capture the input and catch the exception
          try
            // create the scanner object
            Scanner scan = new Scanner (System.in);
            // parse the input`
            result = scan.nextDouble();
            // if we reach this step then good. we got good input let's exit the loop
            inputOK = true;
            // close the scanner
            scan.close();
          // oops we got an error!
          catch (java.util.InputMismatchException e)
            // inform the user of the error
            System.out.println ("That is not a number! Try again. \n");
            // input was not ok so we can't exit the loop yet
            inputOK = false;
        // keep looping as long as inputOK is false
        } while (!inputOK);
        // return out result
        return result;
    }Mathematics.java:
    // name information removed for privacy
    // class information removed for privacy
    * Assignment: 4.3
    * File Name: ASSIGNMENTS/ASSIGNMENT_4/Part3/Mathematics.java
    // Import Scanner class
    import java.util.Scanner;
    //Class Body
    public class Mathematics{
    // Main method. AUTO EXECUTE
      public static void main(String[] args)
    // additional variable declarations removed for brevity
        // Create double precision floating point variables
          double  coeff4 = 0.0, coeff3 = 0.0, coeff2 = 0.0, coeff1 = 0.0, cons = 0.0;
        coeff4 = Scan.nextDouble("Enter the coefficient of x^4 (0.0 if none): ");
        coeff3 = Scan.nextDouble("Enter the coefficient of x^3 (0.0 if none): ");
        coeff2 = Scan.nextDouble("Enter the coefficient of x^2 (0.0 if none): ");
        coeff1 = Scan.nextDouble("Enter the coefficient of x (0.0 if none): ");
        cons = Scan.nextDouble("Enter the constant (0.0 if none): ");
    // do fun things with input (code removed for brevity)
    }output looks like this
    dragonfly@Home:~/ASSIGNMENTS/ASSIGNMENT_4/Part3$ java Mathematics
    Enter the coefficient of x^4 (0.0 if none): hello boys!
    That is not a number! Try again.
    Enter the coefficient of x^4 (0.0 if none): 1.2.
    That is not a number! Try again.
    Enter the coefficient of x^4 (0.0 if none): d
    That is not a number! Try again.
    Enter the coefficient of x^4 (0.0 if none): 1
    Enter the coefficient of x^3 (0.0 if none): Exception in thread "main" java.util.NoSuchElementException
            at java.util.Scanner.throwFor(Scanner.java:817)
            at java.util.Scanner.next(Scanner.java:1431)
            at java.util.Scanner.nextDouble(Scanner.java:2335)
            at Scan.nextDouble(Scan.java:23)
            at Mathematics.main(Mathematics.java:34)
    dragonfly@Home:~/ASSIGNMENTS/ASSIGNMENT_4/Part3$

    Through trial and error i seem to have hit upon a solution to my problem. i am stress testing it now but i think it will hold up admirably
    import java.util.Scanner;
    public class Scan
    // scan in a double without a prompt. catch and handle any exceptions
    public static double nextDouble ()
        return nextDouble("");
    // give the user a prompt and then scan in a double. catch and handle any exceptions
    public static double nextDouble (String prompt)
        // variable to hold the result
        double result = 0.0;
        // variable to determine if input was ok
        boolean inputOK = false;
        // do-while loop to get some input
        do
          // print the prompt. what do you want to ask for?
          System.out.print ( prompt );
          // Try to scan and capture the input and catch the exception
          try
          // Call private method to do the actual scanning
            result = scanDouble();
            // if we reach this step then good. we got good input let's exit the loop
            inputOK = true;
          // oops we got an error!
          catch (java.util.InputMismatchException e)
            // inform the user of the error
            System.out.println ("That is not a number! Try again. \n");
            // input was not ok so we can't exit the loop yet
            inputOK = false;
        // keep looping as long as inputOK is false
        } while (!inputOK);
        // return out result
        return result;
    // Helper method to nextDouble
      private static double scanDouble()
      // hold the result
        double result=0.0;
      // create the scanner object
        Scanner scan = new Scanner (System.in);
      // parse the input
          // If input was not of proper type this call will fail with :
          // java.util.InputMismatchException
          // and return control to calling method
        result = scan.nextDouble();
      // Return our findings
        return result  ;
    }

  • Dumbfounded by Scanner processing String using regular expression

    I was reading Bruce Eckel's book when I came across something interesting: extending Scanner with regular expressions. Unfortunately, I was confronted with an issue that doesn't make much sense to me: if the String that I am scanning contains a hyphen, the Scanner doesn't produce anything. As soon as I take it out, it all works like a charm. Here is my example:
    import java.util.Scanner;
    import java.util.regex.*;
    public class StringScan {
    public static void main (String [] args){
         String input = "there's one caveat when scanning with regular expressions";
         Scanner scanner = new Scanner (input);
         String pattern = "[a-z]\\w+";
         while (scanner.hasNext(pattern)){
              scanner.next(pattern);
              MatchResult match = scanner.match();
              String output = match.group();
              System.out.println(output);
    }What could be the reason? I imagined it could be because the hyphen for some reason gets given a special meaning but when I tried escaping it, it still didn't work.

    Thanks for your prompt reply.
    I have figured out what was wrong with my code, by the way. Since a single quote is not a word character, it does not match w+. And as the very first input token does not match, the scanner stops immediately. I rewrote my regex to "[a-z].*" and now it does work.

  • How to store the string scanned by the scanner class

    try {
           Scanner scanner = new Scanner(new File("D:\\textfile.txt"));
           String sb;
           scanner.useDelimiter("\\t");
           while (scanner.hasNext()== true)
           System.out.println(scanner.next());
              scanner.close();
           catch (FileNotFoundException e)
           e.printStackTrace();
         }Output i get is
    Hi
    how
    are
    you
    I would like to store each word in a different string.What changes do i need to make in the code given above?

    warnerja wrote:
    But what if the text file contains "Trolls are annoying"? Then your solution fails.No warnerjav - this is not so.
    Solution still nearly works but assigns "Trolls" to variable 'hi', "are" to variable 'how' and "annoying" to variable 'are'.
    But you are right to point out that we must now trap exception for call to
    String you = scanner.next();in order to fix the javs for the sentence you suggest because there will be no more words in the scanner darkly.
    Best thankyou for you pointing this out to me for the hlep of us all learning more about the Javs we love.
    Best greetings,
    Bob Gateaux.

  • Scanner issue

    So I'm having a problem with working a scanner.
    The input that my program is trying to read comes in a line by line basis of the form:
    sell x shares at y each
    buy x shares at y each
    etc...
    So, assuming s is a scanner and x and y are ints, this is my code
              while (s.hasNext()) {
                   if (s.next().equals("buy")) {
                        System.out.println("check");
                        x = s.nextInt();
                        y = s.nextInt();
                        stock = new stockEntry(y,x); // I just store info
                        buyQueue.insert(stock,0); // I just store info
                        buyQueue.exchangeShares(sellQueue,0); // I just store info
                        s.nextLine(); // I just store info
                   if (s.next().equals("sell")) {
                        System.out.println("mate");
                        x = s.nextInt();
                        y = s.nextInt();
                        stock = new stockEntry(y,x); // I just store info
                        sellQueue.insert(stock,1); // I just store info
                        sellQueue.exchangeShares(buyQueue, 1); // I just store info
                        s.nextLine();
    Input:
    sell 10 shares at 30 each
    buy 70 shares at 15 each
    Output:
    check
    Exception in thread "main" java.util.InputMismatchException
         at java.util.Scanner.throwFor(Unknown Source)
         at java.util.Scanner.next(Unknown Source)
         at java.util.Scanner.nextInt(Unknown Source)
         at java.util.Scanner.nextInt(Unknown Source)
         at AuctionApp.main(AuctionApp.java:32)
    I really don't understand why this is happening. If someone could help me, that would be great. Thanks a bunch.

    buy x shares at y each
    If that is you line of text then your code
    x = s.nextInt();
    y = s.nextInt();is reading the x value and assigning it to the x variable and then trying to read "shares" as an int and assign it to the y variable.

  • Quick scanner question !

    scanner = new Scanner(file + a + txt);
                StringBuilder sb = new StringBuilder();
                while (scanner.hasNextLine()) {
                    sb.append(scanner.next());
                          System.out.println(sb.toString());I am doing this to read the input from a text file, but it doesnt want to be read correct.
    I made it work like 2 hours ago, but a stupid Windows crash lost all my data.... and this piece is puzzling me .
    i remember i had to add one more line something like
    sb.append(System.properties(" " );
    but nothing makes me read the whole document
    Some help would be crucial here !

    file = A sting "log"
    a = A string that is sent, a time stamp
    txt = ".txt"
    so it will create the text log1345.txt
    the log is correct , as below i can write into it.
    and that i how it was used some time ago :(
    The nextLine() as well was also used but still after a space it would just stop reading .....

Maybe you are looking for

  • How to access a method in webservice catalogued component in BPM Process

    Hi Can anyone explain me how to access a method in webservice catalogued component in BPM Process using an imported jsp in bpm process. Thanks & Regards Ashish

  • MBP Display Parameters for Running Soloris in Parallels

    I just got Solaris installed through Parallels. Thing is, Soloris doesn't recognize any of the video parameters through Parallels. I have to go in there and put them in manually. Currently, the res is stuck at 1600x1200 which is too big for my displa

  • Looping a segment in DMEE

    Hi, I have created a DMEE format for which, during a payment run, I require one particular node to execute continuously as the number of vendor , the payment has been made to. Basically I need a segment to be LOOPed. Is there option available through

  • Inventory Org Security R12

    Hi Could anyone confirm, how we could restrict the List of Values in the "Change Organisation Window", so that access to Inventory Orgs can be restricted. The idea is to restrict access to Organizations basing on the role. So, we cannot use Organizat

  • External Service data

    Dear Friends, I am in the process of preparing a report which contains all the details pertaining to a workorder . It is just an ALV form of document flow for a maintenance order . I don't know how to retrieve the service related data from the table