Java Programming: Fixing Scanner Issues

In summary: IgnoreCase( "false" ) ) return...false; else return...null; } while(true); // return false to abort the loop and exit the program. }}
  • #1
Coldie
84
0
Java's "Scanner"

Hello,

I own a Macintosh and was trying to write a simple Java program for one of my classes. However, I quickly discovered that it appeared that the Mac does not have the Scanner ability. I get an error on the "import java.util.Scanner" line saying

"cannot find symbol
symbol :class scanner
location: package java.util"

If I simply import the whole package, "import java.util.*", then I get the error when I try to use Scanner later. I've already installed Java 2 Standard Edition from Apple's site, which appears to be the most up-to-date package, and I'm running 10.4. What do I need to do to get scanner to work?

Thanks,
Coldie
 
Technology news on Phys.org
  • #2
Do a google search for twain and java
 
  • #3
Do you just need the ability to get user input from a keyboard? Or are you looking for something else in scanner?
 
  • #4
dduardo said:
Do a google search for twain and java
This really wasn't that helpful for me. I got a lot of information, but nothing I could really use to get Scanner working.

mattmns said:
Do you just need the ability to get user input from a keyboard? Or are you looking for something else in scanner?
Yes, all I need is the ability to accept keyboard input, and we were told that the new Scanner feature is the easiest way to do this.
 
  • #5
Hmm, not sure why it is not working then.

Try this program, which works on my computer (windows xp).

Code:
import java.util.*;

public class addThreeNumbers
{
    public static void main(String[] args)
    {
	System.out.println( "Hey, que pasa?" );
	System.out.println( "I am going to add three numbers." );
	System.out.println( "Enter three numbers:" );

	int n1, n2, n3;

	Scanner keyboard = new Scanner(System.in);
	n1 = keyboard.nextInt();
	n2 = keyboard.nextInt();
	n3 = keyboard.nextInt();

	System.out.println( "The sum of those three numbers is: " + (n1 + n2 + n3) );
    }
}

If that does not work then I have another method.

Put this file in the directory of the programs you want to compile, and name it: "TextReader.java"

Here is the code for TextReader.java
Code:
/**
  Class TextReader provides methods for reading character type data an input
  source, either the keyboard or a text file (characters such as digits and
  letters only).  TextReader can be constructed either from an InputStream
  such as System.in (the keyboard) and in fact is done automatically with

    TextReader keyboard = new TextReader( );

  or by specifying the name of a file as a String as in

    TextReader inputFile = new TextReader( "input.data" );

  Written by Stuart Reges at the Univerity of Arizona 6/11/98
  with modifications by Rick Mercer (Aug-98 to June 2000)
*/

import java.io.*;

public class TextReader
{
//--instance variables
  // PushbackReader used here to avoid bugs in the 1.1 BufferedReader class
  // It also allows for a "peek" method.
  private PushbackReader in;   // the input stream
  // true If from keyboard or false when input is from a file
  private boolean rePrompting; // users should be prompted, but not files

/**
  Construct an object used to obtain input from the keyboard
  */
  public TextReader(  )
  { // pre : input stream is open for reading
    // post: constructs a TextReader object associated with the keyboard
    in = new PushbackReader( new InputStreamReader( System.in ) );
    rePrompting = true;
  }

/**
  Construct an object used to obtain input from the disk file with
  only text data such as letters, digits and other characters like * % $
  */
  public TextReader( String fileName )
  { // pre : fileName is the name of a file that can be opened for reading
    // post: constructs a TextReader tied to the given file
    try {
      in = new PushbackReader(new FileReader(fileName));
      rePrompting = false;
    }
    catch( Exception e ) {
      System.out.println("Can't open input file '" + fileName + "', program terminated");
      System.exit(1);
    }
  }

  private void error( String where )
  { // Have a standard way of displaying error messages
    System.out.println("\n***Failure in " + where + " message. Program terminated***" );
    System.exit( 1 );
  }

/**
  Allows user to read in a True or fAlSe value into a boolean variable.
  The case on input does not matter, but only the strings TRUE or FALSE are accepted
  */
  public boolean readBoolean()
  {  // return true
    do
    {
      String torf = readWord( );
      if( torf.equalsIgnoreCase( "true" ) )
        return true;
      else if( torf.equalsIgnoreCase( "false" ) )
        return false;
      else
       System.out.println( torf + " is not 'true' or 'false'. Try again");
    } while( true );
  }

/**
  Use this method to read in entire lines of data such as
  a persons full name or an address.  You can also use it to enter
  a string that maay or may not have blanks spaces.
  Precondition: The input is not at end-of-file of the input stream.
  @return All characters (including blank spaces) up until the enter
  key is entered.
  */
  public String readLine( )
  {
    String result = "";
    try {
      do
      {
        int next = in.read( );
        if( next == '\r' ) // skip carriage-return on Windows systems
          continue;
        if( next == -1 || next == '\n' )
          break;
        result += (char)next;
      } while(true);
    }
    catch( Exception e ) {
      error ( "readLine" );
    }
    return result;
  }

/**
  Returns the next character on the input stream. Same as read.
  Precondition: The input is not at end-of-file of the input stream.
  @return The next character in the input stream.
  */
  public char readChar()
  {
    return read( );
  }

/**
  Returns the next character on the input stream. Same as readChar.
  Precondition: The input is not at end-of-file of the input stream.
  @return The next character in the input stream.
  */
  public char read( )
  { // pre : not at end-of-file of the input stream
    // post: reads the next character of input and returns it

    char result = ' ';
    try {
      result = (char)in.read();
      if (result == '\r') // skip carriage-return on Windows systems
        result = (char)in.read();
    }
    catch( Exception e ) {
      System.out.println( "Failure in call on read method, program terminated." );
      System.exit( 1 );
    }
    return result;
  }

/**
  Puts the given character back into the input stream to be read again
  */
  public void unread( char ch )
  {
    try {
      in.unread((byte)ch);
    }
    catch( Exception e )
    {
      error( "unread" );
    }
  }

/**
  Use this to find out what the next character is when what you do depends
  on it. Especially useful when processing complex file input with unknown
  amounts of input data. The peek method allows for multiple sentinels
  @return the next character in the input stream without actually reading it.
  */
  public char peek( )
  {
    int next = 0;
    try {
      next = in.read( );
    }
    catch( Exception e ) {
      error( "peek" );
    }
    if( next != -1 )
      unread( (char)next );
    return (char)next;
  }

/**
  Reads one string (terminated by end-of-file or whitespace). This method
  will skip any leading whitespace.
  Precondition stream contains at least one nonwhitespace character
  @returns The next string in the input disk file or
  that is typed at the keyboard.
  */
  public String readWord()
  {
    String result = "";
    try {
      int next;
      do
      {
        next = in.read();
      } while( next != -1 && Character.isWhitespace( (char)next) );

      while (next != -1 && !Character.isWhitespace( (char)next ) )
      {
        result += (char)next;
        next = in.read();
      }

      while (next != -1 && next != '\n' && Character.isWhitespace((char)next))
      {
        next = in.read();
      }

      if (next != -1 && next != '\n')
        unread((char)next);
      } // end try
      catch (Exception e)
      {
        error( "readWord" );
      } // end catch

    return result;
  }

/**
   Reads an int and skips any trailing whitespace on current line.
   Keeps trying if floating point number is invalid.
   Precondition: next token in input stream is an int.
   @returns The next integer in the input disk file or that is typed
   at the keyboard.
  */
  public int readInt()
  {
    int result = 0;
    do // keep on trying until a valid double is entered
    {
      try
      {
        result = Integer.parseInt(readWord());
        break;  // result is good, jump out of loop down to return result;
      }
      catch (Exception e)
      {
        if(rePrompting)
          System.out.println("Invalid integer. Try again.");
        else
        {
          error( "readInt" );
          break;
        }
      }
    } while( true );
    return result;
  }

/**
   Reads an floating point numnber and skips any trailing whitespace on
   current line. Keeps trying if floating point number is invalid.
   Precondition: next token in input stream is an valid number (int or double).
   @returns The next floating point number in the input disk file or
   that is typed at the keyboard.
  */
  public double readDouble()
  { // pre : next token in input stream is a double
    // post: reads double and skips any trailing whitespace on current line
    //       Keeps trying if floating point number is invalid
    double result = 0.0;

    do  // keep on trying until a valid double is entered
    {
      try {
        result = new Double(readWord()).doubleValue();
        break;  // result is good, jump out of loop down to return result;
      }
      catch( Exception e )
      {
        if(rePrompting)
          System.out.println("Invalid floating-point number. Try again.");
        else
        {
          error("readDouble");
          break;
        }
      }
    } while( true );
    return result;
  }

/**
  Find out if the input stream has more data that can be read.
  This is especially useful when processing file data where the
  size of the file is not determined (or changes a lot).
  @returns true if input stream is ready for reading otherwise returns false
  */
  public boolean ready( )
  {
    boolean result = false;
    try {
      result = in.ready();
    }
    catch (IOException e) {
      error ( "ready" );
    }
    return result;
  }

  public static void main( String[] args )
  {
     System.out.print( "Enter password: " );

     String pass = "";
     TextReader k = new TextReader( );
     while( true )
     {
       char ch = k.peek();
       if(ch == '\n')
         break;
       pass += ""+ch;
//       k.unread( '*' );
     }
     System.out.println( pass );
  }

}



Here is a sample program on how to use the TextReader class

Code:
/**
 * Example class showing how to use TextReader to read in text from the keyboard
 * into your java program.
 * @author Andree Jacobson
 * @version 1.0 (9/9/2005)
 */

public class UsingTextReader {

  public static void main ( String[] argv ) {

    // Create a new TextReader object - Necessary
    TextReader keyboard = new TextReader();

    System.out.print ( "Hello! Please write your name here: " );
    
    // Read a String from the keyboard (wait for user to press return)
    String name = keyboard.readLine();
    
    System.out.println ( "Hello " + name + "!\n");
    
    System.out.print ( "How old are you? Age: " );
    
    // Read an integer from the keyboard (wait for user to press return)
    int age = keyboard.readInt();
    
    // Print out some intersting message using this information
    System.out.println ( "Wow... " + name + ", are you really " + age + "?");
    System.out.print ( "That means, five years from now you will be "); 
    System.out.println ( (age+5) + " years young!");
  }

}



Note: I only wrote the first program. The other two I got from my prof.
 
  • #6
Thanks for trying to help, but, as I explained, the problem is that I own a Macintosh, and the Scanner component does not seem to be present in java.util. Though I understand there are far more complex ways of taking keyboard input, I just want to know how to get Scanner onto my computer so that I can use programs which call it. I've already fully updated Java directly from Apple's site, so I believe I'll just have to manually install it wherever it's supposed to go. That's what I'm asking for help about.
 
  • #7
Well, the linux servers at our school are not up to date so that is why we use the TextReader class, which works exactly the same as the Scanner class as far as I know. Our prof uses an ibook w/ OSX and seems to have no problem using the TextReader class.
 

What is Java Programming?

Java Programming is a popular and widely used computer programming language. It is an object-oriented language that is used to create various types of software and applications.

What are Scanner Issues in Java Programming?

Scanner Issues in Java Programming refer to common errors or problems encountered when using the Scanner class to read user input from the keyboard or a file. These issues can cause the program to crash or produce unexpected results.

How can I fix Scanner Issues in Java Programming?

To fix Scanner Issues in Java Programming, you can check for common mistakes such as using the wrong data type, not closing the Scanner object, or not handling exceptions properly. You can also use debugging tools to identify and fix any errors in your code.

What is the Scanner class in Java Programming?

The Scanner class in Java Programming is used to read user input from the keyboard or a file. It provides various methods for reading different types of input, such as strings, integers, and doubles. It is part of the java.util package and must be imported before use.

Can I use a different class instead of Scanner in Java Programming?

Yes, there are other classes in Java Programming that can be used to read user input, such as BufferedReader and Console. However, the Scanner class is specifically designed for user input and is the most commonly used class for this purpose.

Similar threads

  • Programming and Computer Science
Replies
8
Views
1K
  • Programming and Computer Science
Replies
2
Views
841
  • Programming and Computer Science
Replies
2
Views
1K
  • Programming and Computer Science
Replies
1
Views
6K
  • Programming and Computer Science
Replies
4
Views
3K
  • Programming and Computer Science
Replies
11
Views
2K
  • Programming and Computer Science
Replies
2
Views
2K
  • Programming and Computer Science
Replies
2
Views
1K
  • Programming and Computer Science
Replies
28
Views
3K
  • Programming and Computer Science
Replies
3
Views
2K
Back
Top