Scanner Class Help

Hi, in a program I'm writing, I've read a line using the scanner class, and after finding a character that's not a digit (using an if(! Character.isDigit) ), I need to go back to the initial position and read the integer. But, since I've already used Scanner to scan the line, I can't seem to get it to go back without closing the file stream and re-opening it. Is there any way around this?

right, that's what i've done, and then i examine that string until i find a character that's not a digit... so i need to set it as a delimiter (which i know how to do) and then read the integer before it... but i have no idea how many digits the integer before it will have (probably at most 3, but my program's supposed to encompass a large amount of possibilities)
[edit]
And I don't know of any string methods that will let me read an integer from the string...
Edited by: Hawx on Oct 11, 2007 12:13 PM

Similar Messages

  • Help with using Scanner Class

    Hi there - I'm a newbie to Java and may have posted this in the wrong forum previously.
    I am trying to modify a program so instead of using a BufferReader, a scanner class will be used. It is basically a program to read in a name and then display the variable in a line of text.
    Being new to Java and a weak programmer, I am getting in a mess with this and missing something somewhere. I don't think I'm using scanner in the correct way.
    Any help or pointers would be good. There are 2 programs of code being used. 'Sample' and 'Run Sample'
    Thanks in advance.
    Firstly, this program will run named 'Sample'
    <code>
    * Sample.java
    * Class description and usage here.
    * Created on 15 October 2006
    package internetics;
    * @author John
    * @version 1.2
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    // import com.ralph.*;
    public class Sample extends JFrame
    implements java.awt.event.ActionListener{
    private JButton jButton1; // this button is for pressing
    private JLabel jLabel1;
    private String name;
    /** Creates new object ChooseFile */
    public Sample() {
    initComponents();
    name = "";
    selectInput();
    public Sample(String name) {
    this();
    this.name = name;
    private void initComponents() {
    Color bright = Color.red;
    jButton1 = new JButton();
    jLabel1= new JLabel();
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent evt) {
    exitForm(evt);
    getContentPane().setLayout(new java.awt.GridLayout(2, 1));
    jButton1.setBackground(Color.white);
    jButton1.setFont(new Font("Verdana", 1, 12));
    jButton1.setForeground(bright);
    jButton1.setText("Click Me!");
    jButton1.addActionListener(this);
    jLabel1.setFont(new Font("Verdana", 1, 18));
    jLabel1.setText("05975575");
    jLabel1.setOpaque(true);
    getContentPane().add(jButton1);
    getContentPane().add(jLabel1);
    pack();
    public void actionPerformed(ActionEvent evt) {
    System.out.print("Talk to me " name " : ");
    try {
    jLabel1.setText(input.readLine());
    } catch (IOException ioe) {
    jLabel1.setText("Ow! You pushed my button");
    System.err.println("IO Error: " + ioe);
    /** Exit this Application */
    private void exitForm(WindowEvent evt) {
    System.exit(0);
    /** Initialise and Scan input Stream */
    private void selectInput() {
    input = new Scanner(new InputStreamReader(System.in));
    /**int i = sc.nextInt(); */
    /** Getter for name prompt */
    public String getName() {
    return name;
    /** Setter for name prompt */
    public void setName(String name) {
    this.name = name;
    * @param args the command line arguments
    public static void main(String args[]) {
    new Sample("John").show();
    </code>
    and this is the second program called 'RunSample will run.
    <code>
    class RunSample {
    public static void main(String args[]) {
    new internetics.Sample("John").show();
    </code>

    The compiler I'm using is showing errors in these areas of the code. I've read the tutorials and still can't get it. They syntax for the scanner must be in the wrong format??
    the input.readLine appears incorrect below.
      public void actionPerformed(ActionEvent evt) {
        System.out.print("Talk to me " +name+ " : ");
        try {
            jLabel1.setText(input.readLine());
        } catch (IOException ioe) {
          jLabel1.setText("Ow! You pushed my button");
          System.err.println("IO Error: " + ioe);
        }and also here...
    the input is showing errors
      /** Initialise and Scan input Stream */
      private void selectInput() {
        input = new Scanner(new InputStreamReader(System.in));
       /**int i = sc.nextInt(); */
      }Thanks

  • Help using scanner class to count chars in file

    Hi all, I am learning Java right now and ran into a problem. I need to use the Scanner class to accurately count the number of chars in a file including the line feed chars 10&13.
    This what I have and it currently reports a 201 byte file as having 194 chars:
         File file = new File(plainFile);
         Scanner inputFile = new Scanner(file);
         numberOfChars = 0;
         String line;
         //count characters in file
         while (inputFile.hasNextLine())
              line = inputFile.nextLine();
              numberOfChars += line.length();
    I know there are other ways using BufferedReader, etc but I have to use Scanner class to do this.
    Thanks in advance!

    raichle wrote:
    Wow guys, thanks for the help! I've got a RTFMWell, what's wrong to have a look at the API docs for the Scanner class?
    and directions that go against the specs I said.Is that so strange to suggest a better option? What if I ask a carpenter "how do I build a table with a my stapler?". Should I give the man an attitude if he tells me I'd better use a saw and hammer?
    I'm also aware that it "eats" those chars and obviously looking for a way around that.
    I've looked through the java docs, but as I said, I'm new to this and they're difficult to understand. The class I am auditing req's that this be done using Scanner, but I don't see why you demand an explanation.
    Can anybody give me some constructive help?Get lost?

  • Help needed regarding Scanner class

    hello
    i'm really desperate for help, i'll mention that this is homework,but i need a small guidance.
    i need to code a calculator,we need to use the Scanner class to break the expression to tokens(we CANNOT use other classes).
    my main problem is about getting those tokens from the input string.
    i tried breaking a string to tokens for hours but just couldnt do it.
    a legal expression is something like:
    xyzavbx1111+log(abc11*(2+5))+sin(4.5)
    iilegal is : xx333aaaa111+2 or log()+2
    where the alphanumerics are variables(sequence of letters followed by numbers)
    i managed to get the tokens out of a string that looks like that:
    String expression = "ax11111+32/3+4*2^2"
    by doing:
    _token = new Scanner(expression);
    while(hasNext(_token)) getNextToken(_token,"\\d+(\\.\\d+)?|(\\+)|(\\-)|(\\*)|(\\/)|(\\^)|([a-zA-Z]+(\\d+));
    public static boolean hasNext(Scanner s) {
    return s.hasNext();
    public static String getNextToken(Scanner s,String str) {
    return s.findInLine(str);
    but i can't get the tokens when i have sin ,cos or log in the expression
    either it just ignores it or i'm looping infinitely.
    my question is how can i make the regular expression include the sin log and cos?
    I also know that when i'll use the "matches" method ,i'll be able to spot illegal arguments like 5//2+ because it doesnt match the pattern.
    so any help conecrning the regular expression would be great thanks alot.

    thx , but i already got it,after trying tons of combinations
    i'll post the format i used in case someone will find this thread in the future ,while looking for something similar
    the format is:
    "(\\s)|(log)|(sin)|(cos)|(\\d+(\\.\\d+)?)|(\\+)"+
    "|(\\-)|(\\*)|(\\/)|(\\^)|([a-zA-Z]+(\\d+))|(\\()|(\\))|(\\s)";
    which includes white spaces between arguments and operators

  • Help using scanner.class someone help me

    ive been working on some code and the thing is i am stuck on how do i count the number of intergers between 1 and 5. for example lets say i inputted using a scanner.class 1,2,2,3,3,3 i want my program to then say how many 2's I have entered and and how many 3's i have entered. So basically if using a scanner.class (keyboard class) in java instead of hardwiring the numbers into an array how do i count out the number of intergers and display them in my output

    hardwiring the numbers into an array how do i count
    out the number of intergers and display them in my
    outputTry this.
            Scanner sc = new Scanner(System.in);
            System.out.println("Enter numbers:");
            int i = 0;
            int count = 0;
            Map <Integer, Integer> intMap = new TreeMap <Integer, Integer>();
            while( true ) {
                i = sc.nextInt();
                if(i < 0 || i > 5) break;
                // Code to count the numbers entered.
                if(intMap.containsKey(new Integer(i))) {
                    count = intMap.get(new Integer(i)).intValue();
                    count++;
                } else {
                    count = 1;
                intMap.put(new Integer(i), new Integer(count));
            System.out.println(intMap);At forum users: Pardon me for all my variable names and poor coding style and lack of comments and...

  • Scanner class and Ready to Program

    Hi I have only been programming for about 3 years. I have always used Ready to Program as my environment and I rly like it. I used to always used the BufferedReader to read in inputs from the keyboard. now I am in university and we always use the Scanner class to read in the inputs and i have unfortunately had to conform because my narrow minded professors don't want to help me when I code my way, ughhh, but ya.
    pretty much, I believe when i have gone in the properties of Ready to Program it says it is using JDK 1.4. so I'm guessing it is styll using that version of Java or something ( I have never had to go into the propeties of java to change anything so I am not sure if there is a way to import the new version of Java or not) but basically I went to Ready's site and it said that a new Beta is out that I have to wait for them to email to recieve. http://www.holtsoft.com/ready/support/ . and the beta is version 1.6 so I am asumming that it is the one that comes packaged with 1.6. my question, as I believe it will be a while before i recieve the link, is there anyway to import and make java look at my jdk 1.6 at all. I have put them in the same folder but I don't know where to put the JDK or JRE 1.6 folders to allow Ready to read it.

    oh, and has anyone recieved the new Ready to program beta v1.6? I was wondering if I could get a copy because its taking so long ot get it, I think i applied about a week and a half ago

  • Scanner class

    i m very new to Java..i have Netbeans 5 to compile and run my Java programs.....when i try to run the following program
    import java.util.Scanner;
    class EchoLine {
    public static void main(String args[]) {
    Scanner myScanner = new Scanner(System.in);
    System.out.println(myScanner.nextLine());
    i get some errors saying...
    D:\Java\Projects\JavaApplication12\src\javaapplication12\Main.java:11: cannot resolve symbol
    symbol : class Scanner
    location: package util
    import java.util.Scanner;
    D:\Java\Projects\JavaApplication12\src\javaapplication12\Main.java:19: cannot resolve symbol
    symbol : class Scanner
    location: class javaapplication12.EchoLine
    Scanner myScanner = new Scanner(System.in);
    D:\Java\Projects\JavaApplication12\src\javaapplication12\Main.java:19: cannot resolve symbol
    symbol : class Scanner
    location: class javaapplication12.EchoLine
    Scanner myScanner = new Scanner(System.in);
    3 errors
    BUILD FAILED (total time: 0 seconds)
    i also get same kind of error while compiling it in JCreator.
    Can anybody help me in this matter to expalin this knid of behavoiur??
    Thanking in advance!!

    after downloading JDK 5 update 7 from
    http://java.sun.com/j2se/1.5.0/download.jsp
    i still cannot use Scanner class.....
    Java doesn't like you sorry. It's hopeless. We try and talk to Java and make her understand that she shouldn't be so flighty but you know... it just isn't going to work out. She hopes you can remain friends but she's just not interested in a more intimate relationship at this time.

  • Problem with 1.5 Scanner class

    I'm trying to learn to use the new Scanner class in Java 1.5. I wrote this little program:
    import java.util.*;
    public class Howdy {
      public static void main(String[] args) {
        Scanner reader = Scanner.create(System.in);
        String name = reader.readLine();
        System.out.println("Hello, " + name);
    }When I try to compile it, I get these complaints:
    Howdy.java:5: cannot find symbol
    symbol  : method create(java.io.InputStream)
    location: class java.util.Scanner
        Scanner reader = Scanner.create(System.in);
                                ^
    Howdy.java:6: cannot find symbol
    symbol  : method readLine()
    location: class java.util.Scanner
        String name = reader.readLine();
                            ^
    2 errorsI know I have the 1.5 goodies turned on, because I can (for example) use the enhanced for loop.
    What's the problem?

    Can someone tell me what I'm doing wrong here.....I have a input file that has 7 rows and 10 columns. I posted the error I'm getting below. Thanks.
    import java.util.Scanner;
    import java.io.File;
    import java.io.IOException;
    public class windChill
    public static void main(String[] args) throws IOException
    File inputFile = new File("input.txt");
    Scanner fscan = new Scanner ( inputFile );
    Scanner lscan;
    lscan = new Scanner(fscan.nextLine());
    int [][] chill = new int [7][10];
    for (int i = 0;i < 7; i++)
    for (int j = 0;j < 10; j++)
    chill[i][j] = lscan.nextInt();
    lscan = new Scanner(fscan.nextLine());
    System.out.println(chill[1][9]);          
    ----jGRASP exec: java windChill
    Exception in thread "main" java.util.NoSuchElementException: No line found
         at java.util.Scanner.nextLine(Unknown Source)
         at windChill.main(windChill.java:37)
    ----jGRASP wedge2: exit code for process is 1.
    ----jGRASP: operation complete.

  • Problems with the Scanner class and the decimal point

    I'm creating a GUI so to get the user input (double value) I use a jText field and the Scanner to read that value:
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
            String time = jTextTime.getText();
           double t = new Scanner(time).nextDouble();
            String cy = Double.toString(t);
            jTextCycles.setText(cy);
        }                                  The problem is that the decimal point it's a comma so if I write:
    1.2
    t = (Error InputMismatchException)
    1.236
    t = 1236.0
    1,2
    t = 1.2
    So I try using the parse method to get the double value:
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
            String time = jTextTime.getText();
           double t = Double.parseDouble(time);
            String cy = Double.toString(t);
            jTextCycles.setText(cy);
        }                            In this case the method parseDouble() takes the dot as the decimal point so if i write:
    1.2
    t = 1.2
    1.236
    t = 1.236
    1,2
    t = (Error InputMismatchException)
    � What can I do to Scanner class to accept the dot as the decimal point?
    I think that the problem is becouse in some countries (I'm from Colombia) the decimal point is a comma and in others is the dot.
    Thanks

    From the Javadocs for Scanner:
    Localized numbers
    An instance of this class is capable of scanning numbers in the standard formats as well as in the formats of the scanner's locale. A scanner's initial locale is the value returned by the Locale.getDefault() method; it may be changed via the useLocale(java.util.Locale) method.
    If you change your locale to one of those that does use a comma for a decimal point, it should work.

  • Scanner class not recognized

    A little background: I've decided to teach myself java after being given the book "Java Software Solutions" by Lewis and Loftus (fourth edition). I'm reading through it, working the examples. This is definitely a newbie question.
    I'm trying to input some text using the scanner class. I'm running java 5.0, and have no other versions of java running on the computer. When I try and compile the following code, I get the message "cannot find symbol ... symbol: method create(java .io.InputStream) ... class java.util.Scanner ..."
    Here is my code:
    import java.util.Scanner;
    public class ScannerTest {
        public static void main(String[] args){
            int a;
            Scanner scan = Scanner.create(System.in);
            System.out.println("Please enter an integer --> ");
            a = scan.nextInt();
            System.out.println("You entered " + a);My class path is set correctly, so that's not the problem. Also, I'm able to use the random class by importing java.util.Random. I've tried to import the entire util class (import java.util.*), but this won't work.
    What am I missing? Thanks in advance.

    Thanks, I have it working now. Frustrating though,
    because the code came STRAIGHT out of the book (page
    129 and throughout).Ought to tell you something about the book... :o)
    It may have been written when 1.5 was still beta - I don't know if that method was available then. It'd be prudent to check the errata online, though. Either way, glad you got it working, and good luck with your progress!

  • Anyone use the scanner class?

    The scanner class makes command line input easy:
    Scanner input = new Scanner(System.in);
    input.nextLine() returns the string
    My result always appears before the input is shown. For example:
    Please enter a string: You entered this is a string
    this is a string<--the user input isn't displayed after the prompt.
    How do I make the user input appear right after the prompt? Thank you.

    ShaqDiesel wrote:
    The scanner class makes command line input easy:
    Scanner input = new Scanner(System.in);
    input.nextLine() returns the string
    My result always appears before the input is shown. For example:
    Please enter a string: You entered this is a string
    this is a string<--the user input isn't displayed after the prompt.
    How do I make the user input appear right after the prompt? Thank you.What? I don' understand your post. What is expected result, and what do you get?
    Kaj

  • Nuances of the Scanner Class

    I'm having trouble with the Scanner class... here is a snippet of code from a program I am writing.
    ==========
    1 System.out.print("Enter the name of the new passenger-> ");
    2      String passengerName = scan.nextLine();
    3      System.out.println(passengerName);
    4      
    5      System.out.print("Enter the ticket type (E or F)-> ");
    6      String desiredClassType = scan.nextLine();
    7      System.out.println(desiredClassType);
    8      char desiredClassTypeCode = (desiredClassType.toUpperCase()).charAt(0);
    9      
    10
    11      System.out.print("Enter the desired row-> ");
    12      int desiredRow = scan.nextInt();
    13      System.out.println(desiredRow);
    14      
    15      System.out.print("Enter the desired seat-> ");
    16      String desiredSeat = scan.nextLine();
    17      System.out.println(desiredSeat);
    18      char desiredSeatCode = desiredSeat.charAt(0);
    19      
    20      System.out.print("Smoking or non-smoking (S or N)-> ");
    21      String desiredSmoking = scan.nextLine();
    22      System.out.println(desiredSmoking);
    23      char desiredSmokingCode = (desiredSmoking.toUpperCase()).charAt(0);
    ==========
    The problem is, after the scan.nextInt() on line 12, the user never gets a chance to enter input for the scan.nextLine() on line 16. The program just plows right on through and returns the following error at line 18:
    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
    If I change the scan.nextLine() in line 16 to scan.next(), it works alright until the next time I call a scan.nextLine at line 21. Then the same error message appears at line 23. Is there something I'm missing? I can't just change everything to scan.next because some inputs require a string that includes whitespace. However, scan.nextLine keeps giving me these errors...?

    when the program asks you to enter a number, you enter a number and press enter. The nextInt method reads the number but leaves the line feed. Next, the program calls nextLine. What will it return? It will return the 0-length string from where the number ended until the line feed, and removes the line feed from the stream. This is why the user never gets a chance to enter anything: he's already entered what the program was looking for.
    To get rid of the line feed, call nextLine directly after calling nextInt and throw away the return value.
    int desiredRow = scan.nextInt();
    scan.nextLine(); // throw away rest of line

  • Scanner class refuses to work

    Hi, I am having a really big pain in the butt issue with java, (ive tried using eclipse, jgrasp and bluej, all giving me same error)
    I am trying to read from a .dat file (which can easily be opened with wordpad or notepad to reveal contents)
    I am using scanner class
    Scanner key = new Scanner (new File ("file.dat"));
    no matter what i do, i keep getting the same error message FileNotFound Exception, i have gotten java to print out the directory it is searching for, i have put the file into that directory and i am still getting nothing....ive have been at this for two days now, and it is driving me nuts, nothing is making sense and i have asked everyone i know, they say that is the code you need to use to get it to read.
    P.S i have also tried
    File abc = new File ("file.dat");
    Scanner key = new Scanner (abc); same result
    I even got a little hopeful and tried just plain old
    Scanner key = new Scanner ("file.dat); and i get nada, same error, im wondering if anyone has seen this before.

    public static void populate(){
    Scanner keyb= new Scanner(new File("city.dat"));
    for(int j=0;j<=18;j++){
         int x = keyb.nextInt();
         String abr=keyb.next();
         int h = convert(abr);
         String name=keyb.next();
         int pop=keyb.nextInt();
         int alt = keyb.nextInt();
         city[x]=new cities(name,pop,alt);
         }Error Message: Exception in thread "main" java.lang.Error: Unresolved compilation problems:
         Unhandled exception type FileNotFoundException
         Unhandled exception type FileNotFoundException
         at Main.populate(Main.java:45) Line 45 is Scanner keyb= new Scanner(new File("city.dat"));
         at Main.main(Main.java:34) Line 34 is a call to the populate method.

  • Scanner class with char

    How do i make this work?Scanner class doesnt seem to have anything to input a char from the keyboard?Do i have to turn it inot a string or something?
    import java.util.Scanner;
    public class Char
      public static void main(String[] args)
              char letter ;
           int count = 0 ;
           System.out.println (" Enter first character : " );
              Scanner myScanner = new Scanner (System.in);
          letter = myScanner.getChar();
           while ( letter != '!')
                System.out.println(letter);
                count++ ;
                System.out.print("Enter next  character : ") ;
                letter = myScanner.nextchar();
           System.out.println(" Number of characters was " + count);
    }

    Try a java.util.Pattern with the next() method.
    import java.util.NoSuchElementException;
    import java.util.Scanner;
    class Z
        public static void main(String[] args)
            Scanner sc = new Scanner(System.in);
            String s = "";
            try
                s = sc.next(".");
            catch (NoSuchElementException e)
                System.out.println("Only single characters allowed");
            System.out.println("Valid input: " + s);
            sc.close();
    }

  • I'm trying to scan but instead of the scan a message comes up from PS saying "An error occurred while communicating with the scanner." help- I cannot scan!

    I'm trying to scan but instead of the scan a message comes up from PS saying "An error occurred while communicating with the scanner." help- I cannot scan!

    Best practices: Usage
    Supply pertinent information for quicker answers
    The more information you supply about your situation, the better equipped other community members will be to answer. Consider including the following in your question:
    Adobe product and version number
    Operating system and version number
    The full text of any error message(s)
    What you were doing when the problem occurred
    Screenshots of the problem
    Computer hardware, such as CPU; GPU; amount of RAM; etc.

Maybe you are looking for