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?

Similar Messages

  • Sun:Iterating the cursor ! Is this bad logic. i.e, using crs.next() method

    Hi friends,
    I have been using crs.next() method for comparing the given string in textbox and in database are equal. If they are equal then it must redirect to other page otherwise it must remain in the same page.
    Please tell me wheter it is bad logic or not.If it is bad logic then tell me the alternate one.
    Thanking you in Advance.

    Are you refering your code in:
    http://forum.java.sun.com/thread.jspa?threadID=5121734&tstart=75 ?
    I don't know about bad logic or not in using crs.next().
    But I am just curious why do you have to iterate the rowset when you can set a query criteria in the rowset? Suppose you have 100 records in your table, sure it is faster to use query criteria for that., execute the rowset, and then check whether the rowset contains a record or not.
    Another alternative is to use tableDataProvider.findFirst(), and then check the existence of the record. That if you use tableDataProvider instead of the rowset directly. (You may find it in JumpStartCycle sample project).
    Also instead of writing these lines:
    // set the rowset to use the Employee database
    rs.setDataSourceName("java:comp/env/jdbc/Employee");
    rs.setCommand("SELECT * FROM srni.EMPLOYEE");
    rs.setTableName("EMPLOYEE");in the login_action(), you may visually create the rowset() and put it in sessionbean.
    That is what I've found in JSC sample projects. In JumpStartCycles sample (you may create it via file-new projects-samples), there is a login.jsp which is quite similar to your login form. Not exactly the same, but the logic is the same.
    rgds

  • Control the loop of resultset.next( ); (method)

    Hai, guys
    I am using the ODBC database connection to (Excel Sheet) and i wanna get the records from it. My code is scucess but there is a problem in resultset.next() method.
    The thing is it retrieving all the data including the none data fields (null null), so finally it became a never ending loop.
    pls help me to get the data rang's records
    Statement stmnt = connexl.createStatement();
    String query = "SELECT * FROM [IJTS$]";
    stmnt.execute(query);
    ResultSet rsxl = stmnt.getResultSet();
    while(rsxl.next()) {
    String excelname = rsxl.getString(1);
    String excelcate = rsxl.getString(2);
    System.out.print(rsxl.getString(1));
    System.out.println(" "+rsxl.getString(2));
    }

    if null implies it has reached the last row, maybe you could check for null and break from the loop
    for example:
    while (rsxl.next()) {
      String excelname = rsxl.getString(1);
      String excelcate = rsxl.getString(2);
      if (excelname == null && excelcate == null) {
        break;
      } else {
        System.out.println(excelname + " " + excelcate);
    }

  • 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
    .......

  • ResultSet not responding to next() method

    Please Help i have this result set object that is not null sure of it because i checked by using if(reslt!=null) then i used a while loop to go through the object but to no avail i even debuged by using System.out.println(). Help !!.
    [if(evnt.getSource()==okBtn){
                   ResultSet resltset=null;
                   try{
                        DataBaseConnecter dataBaseConnecter=new DataBaseConnecter();
                        resltset =dataBaseConnecter.executeQuery(query);
                        if(resltset!=null&&resltset.next()){
                             System.out.println("Iam not null");
                             while(resltset.next()){
                                  System.out.println("I got here ");
                                  String sdr=resltset.getString(1);
                   }catch(SQLException sqlex){
                        sqlex.printStackTrace();
                   catch(NullPointerException npe){
                        npe.printStackTrace();
                   }]

    if(evnt.getSource()==okBtn){
    ResultSet resltset=null;
    try{
    DataBaseConnecter dataBaseConnecter=new DataBaseConnecter();
    resltset =dataBaseConnecter.executeQuery(query);
    if(resltset!=null&&resltset.next()){
    System.out.println("Iam not null");
    while(resltset.next()){
    System.out.println("I got here ");
    String sdr=resltset.getString(1);
    }catch(SQLException sqlex){
    sqlex.printStackTrace();
    catch(NullPointerException npe){
    npe.printStackTrace();
    }One big problem with this statement is that you are not testing to see if a resultset was returned, you are just confirming that the reference variable resltset points to an object in memory, as it should.
    if(resltset!=null&&resltset.next()){
    A better statement would be,
    if (resltset.first()) {
    ... because if this method returns true then you are moved automatically to the first row, and if it returns false then the ResultSet object is empty and you skip the code block.
    Also, you are getting the TYPE_FORWARD exception because the ResultSet is set to TYPE_FORWARD only.

  • How to make for loop pass only once in a next() method

    Good Day!
    Can anyone help me or suggest any idea to resolve my problem with the below code, wherein it will only pass the for loop only once. I already tried inserting the for loop in side the if (sqlset4.isFirst()) condition but the problem is it only retrieved the first row of the resultset.
    Cheers!
                   Statement sOutput = consrc.createStatement();
                            ResultSet sqlset4 = sOutput.executeQuery(xquery);
                            ResultSetMetaData rsMetaData = sqlset4.getMetaData();
                            int numberOfColumns = rsMetaData.getColumnCount();
                            String writefld = "";
                            while (sqlset4.next()) {
                                 writefld = "";
                                 for (int i = 1; i <= numberOfColumns; i++) {
                                     if (xxformatid.equals("1") || xxformatid.equals("3")) {
                                         writefld = writefld + "sqlset4.getString(" + i + ").trim()" + "|";
                                writefld = writefld.substring(0, writefld.length() - 1) + ")";
                                output.write("\r\n");
                                output.write(writefld);
                            output.close();I am using Netbean IDE 6.8
    Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - 64bi

    Hi everyone!
    What I actually trying to do is that I have a multiple tables and from these tables I'm going to write each of it into a flatfile that is a pipe delimeted that is why I have to make a loop to know how many fields I am going to write. The code that was attached are actually working, my only concern is that it will take a longer time of processing cause every record of a table it will pass to the for loop(checking how many column) wherein number of column/ were already known on the first loop.
    Hi kajbj,
    I think what your trying to explain is almost the same with below code which i had already tried. The problem with this is that the every loop of the outer loop data retrieve is only the data of the first record.
                   Statement sOutput = consrc.createStatement();
                            ResultSet sqlset4 = sOutput.executeQuery(xquery);
                            ResultSetMetaData rsMetaData = sqlset4.getMetaData();
                            int numberOfColumns = rsMetaData.getColumnCount();
                            String writefld = "";
                            while (sqlset4.next()) {
                                 writefld = "";
                                 if (sqlset4.isFirst()) {
                                    for (int i = 1; i <= numberOfColumns; i++) {
                                        if (xxformatid.equals("1") || xxformatid.equals("3")) {
                                            writefld = writefld + "sqlset4.getString(" + i + ").trim()" + "|";
                                writefld = writefld.substring(0, writefld.length() - 1) ;
                                output.write("\r\n");
                                output.write(writefld);
                            output.close();

  • Problem in class moving to next method

    thank you to all those who helped me with dealing with time in my Movie class. My other problem is I can't return the charges (val) once a movie is hired. I need my Movie class to output the following when applied to the TestMovie class.
    Movie MOV456 is hired to PC00034
    Movie MOV456 cannot be hired to PC10101
    Movie MOV456 is returned by PC00034
    Total Charges = 16.5
    Movie MOV456 cannot be hired to PC98456
    Movie MOV456 is hired to PC99999
    Movie: MOV456
    Description: The Fellowship of the ring
    Classification: PG
    Status: H
    Rate per day: 5.5
    Hirer=PC99999
    Date/time of hire: 2007/3/19 - 18:30
    Here is my Movie class:
    //CPT12 - Assignment2
    //Written by Suzanne Howarth, 88886, Tutor - Clemens Meyr
    //This is the class of an object orientated programme to manage the hiring of movies
    import java.util.*;
    import java.text.*;
    //Defined instance variables set to private
    public class Movie {
    //Defined constuctor for the Movie class
        public Movie(String movieID, String description, String classification, float dailyRate) {
            ID = movieID;
            this.description = description;
            this.classification = classification;
            status = 'A';
            this.dailyRate = dailyRate;       
             private String ID;
             private String description;
             private String classification;
             private float dailyRate;
             private char status;
             private String hirer;
             private String s;
             private GregorianCalendar dob;
             private GregorianCalendar d;
             private GregorianCalendar dC;
             private double val;
             private long daysHired;
             private long age;
             private boolean valid;
    //Defined accessors for the Movie class
        public String getID() {
            return ID;
        public String getDescription() {
            return description;
        public String getClassification() {
            return classification;
        public float getDailyRate() {
            return dailyRate;
        public char getStatus() {
            return status;
        public boolean hire(String hirerID, GregorianCalendar hirerDOB, GregorianCalendar dateTime) {
            hirer = hirerID;
            dob = hirerDOB;
            d = dateTime;
            boolean valid = false;
        if (status == 'A') {
                if (classification.equals("PG")) {
             valid = true;
            else {
             if (age<18) {
                valid = true;
        if (valid) {
         status = 'H';
        return valid;
        public String getHirer() {
            return hirer;
        public GregorianCalendar getDob() {
            return dob;
        public GregorianCalendar getD() {   
            return d;        
        public String getS() {
            Date date = d.getTime();
            DateFormat df = DateFormat.getDateTimeInstance();
            s = df.format(date);
            return s;
        public long getAge() {
            age = (d.getTimeInMillis() - dob.getTimeInMillis())/(365*24*60*60*1000);
            return age;
        public double hireComplete(GregorianCalendar date_time2) {
            dC = date_time2;
            if ((status == 'H') && (val > 0.0))
                return val;
            else
                return val = -1.0;
        public long getDaysHired() {
            daysHired = (dC.getTimeInMillis() - d.getTimeInMillis())/(24*60*60*1000);
            return daysHired;
        public GregorianCalendar getDC() {
            return dC;
        public double getVal() {
            val = daysHired * dailyRate;       
            return val;
        public void print() {  
            System.out.println("Movie ID - " + ID);
            System.out.println("Movie - " + description);
            System.out.println("Classification - " + classification);
            System.out.println("Status - " + status);
            System.out.println("Daily Rate - " + dailyRate);
            System.out.println("Hirer ID - " + hirer);
            System.out.println("Date and Time of hire - " + s);
    }and here is the MovieTest class:
    import java.util.GregorianCalendar;
    public class TestMovie
       public static void main(String args[])
          Movie mov = new Movie("MOV456", "The Fellowship of the ring", "PG", 5.50f);     
          String hirer1ID = "PC00034";     
          // GregorianCalendar date below correspond to 15th March 2007, 1.30 pm
          GregorianCalendar d1 = new GregorianCalendar(2007,3,15,13,30);
          GregorianCalendar dob1 = new GregorianCalendar(1989,01,22,15,15);
          if (mov.hire(hirer1ID, dob1, d1) == true)
             System.out.println("Movie " + mov.getID() + " is hired to " + mov.getHirer());  
          else
             System.out.println("Movie " + mov.getID() + " could not be hired to " + hirer1ID);
          // Another attempt to hire the movie (after the movie has already been hired)
          GregorianCalendar d2 = new GregorianCalendar(2007,3,15,15,30);
          GregorianCalendar dob2 = new GregorianCalendar(1989,12,20,10,12);
          String hirer2ID = "PC10101";
          if (mov.hire(hirer2ID, dob2, d2) == true)
             System.out.println("Movie " + mov.getID() + " is hired to " + mov.getHirer());  
          else
             System.out.println("Movie " + mov.getID() + " cannot be hired to " + hirer2ID);
          // Completing the hiring of the movie
          GregorianCalendar d1C = new GregorianCalendar(2007,3,18,10,30);
          double val = mov.hireComplete(d1C);
          if ( val > 0.0 )
             System.out.println("Movie " + mov.getID() + " is returned by " + mov.getHirer());  
             System.out.println("Total Charges = " + val);  
          Another attempt to hire the movie (after earlier hire is completed,
          but with hirer too young to hire a PG rated movie)
          GregorianCalendar d3 = new GregorianCalendar(2007,3,19,16,30);
          GregorianCalendar dob3 = new GregorianCalendar(1995,12,20,10,12);
          String hirer3ID = "PC98456";
          if (mov.hire(hirer3ID, dob3, d3) == true)
             System.out.println("Movie " + mov.getID() + " is hired to " + mov.getHirer());  
          else
             System.out.println("Movie " + mov.getID() + " cannot be hired to " + hirer3ID);
          // Hiring the movie with the correct age again        
          GregorianCalendar d4 = new GregorianCalendar(2007,3,19,18,30);
          GregorianCalendar dob4 = new GregorianCalendar(1985,12,20,10,12);
          String hirer4ID = "PC99999";
          if (mov.hire(hirer4ID, dob4, d4) == true)
             System.out.println("Movie " + mov.getID() + " is hired to " + mov.getHirer());  
          else
             System.out.println("Movie " + mov.getID() + " cannot be hired to " + hirer4ID);  
          // Printing the details of Movie object referred by mov  
          mov.print();          
    }The problem must be with how I coded my Movie class. It just won't output that the movie has been returned and the total charges.
    Any help would be very much appreciated.

    Do u mean to put it like this:
    //CPT12 - Assignment2
    //Written by Suzanne Howarth, 88886, Tutor - Clemens Meyr
    //This is the class of an object orientated programme to manage the hiring of movies
    import java.util.*;
    import java.text.*;
    //Defined instance variables set to private
    public class Movie {
    //Defined constuctor for the Movie class
        public Movie(String movieID, String description, String classification, float dailyRate) {
            ID = movieID;
            this.description = description;
            this.classification = classification;
            status = 'A';
            this.dailyRate = dailyRate;       
             private String ID;
             private String description;
             private String classification;
             private float dailyRate;
             private char status;
             private String hirer;
             private String s;
             private GregorianCalendar dob;
             private GregorianCalendar d;
             private GregorianCalendar dC;
             private double val;
             private long daysHired;
             private long age;
             private boolean valid;
    //Defined accessors for the Movie class
        public String getID() {
            return ID;
        public String getDescription() {
            return description;
        public String getClassification() {
            return classification;
        public float getDailyRate() {
            return dailyRate;
        public char getStatus() {
            return status;
        public boolean hire(String hirerID, GregorianCalendar hirerDOB, GregorianCalendar dateTime) {
            hirer = hirerID;
            dob = hirerDOB;
            d = dateTime;
            boolean valid = false;
        if (status == 'A') {
                if (classification.equals("PG")) {
             valid = true;
            else {
             if (age<18) {
                valid = true;
        if (valid) {
         status = 'H';
        return valid;
        public String getHirer() {
            return hirer;
        public GregorianCalendar getDob() {
            return dob;
        public GregorianCalendar getD() {   
            return d;        
        public String getS() {
            SimpleDateFormat formatter = new SimpleDateFormat("d");
            GregorianCalendar d = new GregorianCalendar();
            s = formatter.format(d.getTime());
            return s;
        public long getAge() {
            age = (d.getTimeInMillis() - dob.getTimeInMillis())/(365*24*60*60*1000);
            return age;
        public double hireComplete(GregorianCalendar date_time2) {
            dC = date_time2;
            if ((status == 'H') && (val > 0.0)) {
                val = daysHired * dailyRate;
                return val;
            else
                return val = -1.0;
        public long getDaysHired() {
            daysHired = (dC.getTimeInMillis() - d.getTimeInMillis())/(24*60*60*1000);
            return daysHired;
        public GregorianCalendar getDC() {
            return dC;
        public double getVal() {            
            return val;
        public void print() {  
            System.out.println("Movie ID - " + ID);
            System.out.println("Movie - " + description);
            System.out.println("Classification - " + classification);
            System.out.println("Status - " + status);
            System.out.println("Daily Rate - " + dailyRate);
            System.out.println("Hirer ID - " + hirer);
            System.out.println("Date and Time of hire - " + s);
    }I must be wrong because I am still not getting the desired output.

  • 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

  • Create(java.io.InputStream) in Scanner cannot be applied to (java.io.File)

    Ahhh!!!
    Ahem, when I try to compile the file below, "PhoneDirectory.java", I get the following compilation error message:
    PhoneDirectory.java:12: create(java.io.InputStream) in Scanner cannot be applied to (java.io.File)
        Scanner fin = Scanner.create(file);After quite a bit of tweaking... I'm right back where I started. I'm a seasoned programmer, as far as concepts are concerned, but rather new to JAVA.
    The error seems to be occuring where a new instance of "Scanner" is supposed to be created. It uses file I/O, and I had only used the Scanner class for the keyboard input in the past.
    Looking at the Scanner class, everything seems to be right to me. I'm probably missing some simple fundamental concept, and I've been pulling my hair out trying to get it... Please help me shed some light on this situation!
    =========
    PhoneDirectory.java
    =========
    import java.io.*;
    // Read a file of names and phone numbers
    // into an array. Sort them into ascending
    // order using bubble sort.
    // Print names and numbers before and after sort.
    public class PhoneDirectory {
      public static void main (String[] args) {
        PhoneEntry[] directory = new PhoneEntry[200];
        File file = new File("c:\\jessica\\phonenum.txt");
        Scanner fin = Scanner.create(file);
        int numberEntries = 0;
        // read array from file
        while (fin.hasNextInt())
          directory[numberEntries++] = new PhoneEntry(fin);
        // print array as read
        for (int i=0; i<numberEntries; i++)
          System.out.println(directory);
    // sort by ordering defined in PhoneEntry,
    // in this case lastName firstName
    bubbleSort(directory, numberEntries);
    // print sorted array
    System.out.println(
    "============================================");
    for (int i=0; i<numberEntries; i++)
    System.out.println(directory[i]);
    static void bubbleSort(PhoneEntry[] a, int size) {
    // bubbleSortr: simple to write, but very inefficient.
    PhoneEntry x;
    for (int i=1; i<size; i++)
    for (int j=0; j<size-i; j++)
    if (a[j].compareToIgnoreCase(a[j+1]) > 0) {
    // swap
    x = a[j]; a[j] = a[j+1]; a[j+1] = x;
    =========
    PhoneEntry.java
    =========
    class PhoneEntry {
    // number, name entry for a line in a Phone Directory
      protected int area;
      protected int prefix;
      protected int number;
      protected String firstName;
      protected String lastName;
      public String toString() {
      // format name and phone number to printable string
        String x = lastName + ", " + firstName;
        x = x +
        " . . . . . . . . . . . . . . .".substring(x.length())
        + "(" + area + ") " + prefix + "-" + number;
        return x;
      public int compareToIgnoreCase(PhoneEntry v) {
      // alphabetically compare names in this to names in v
      // return negative for this < v, 0 for ==,
      //        positive for this > v
        int m = lastName.compareToIgnoreCase(v.lastName);
        if (m == 0) m = firstName.compareToIgnoreCase(v.firstName);
        return m;
      public PhoneEntry(Scanner fin) {
      // input a PhoneDirectory entry. Must be space delimited
      // area prefix suffix lastname firstname
        // number
        area = fin.nextInt();
        prefix = fin.nextInt();
        number = fin.nextInt();
        // read rest of line
        String name = fin.nextLine();
        // split name into lastName firstName
        int p = name.indexOf(' ');
        if (p > 0) {
            lastName = name.substring(0,p);
            firstName = name.substring(p+1);
        else {
            lastName = name;
            firstName = "";
    }=========
    Scanner.java
    =========
        This class does input from the keyboard.  To use it you
        create a Scanner using
        Scanner stdin = Scanner.create(System.in);
         then you can read doubles, ints, or strings as follows:
        double d; int i; string s;
        d = stdin.nextDouble();
        i = stdin.nextInt();
        s = stdin.nextLine();
        An unexpected input character will cause an exception.
        You cannot type a letter when it's expecting a double,
        nor can you type a decimal point when it's expecting an int.
    import java.io.*;
    public class Scanner {
    // Simplifies input by returning
    // the next value read from the
    // keyboard with each call.
      private String s;
      private int start=0, end = 0, next;
      private BufferedReader stdin;
      Scanner(InputStream stream) {
        start = end = 0;
        // set up for keyboard input
        stdin = new BufferedReader(
        new InputStreamReader(stream));
      public static Scanner create(InputStream stream) {
        return new Scanner(stream);
      double nextDouble() {
         if (start >= end)
           try {
            s = stdin.readLine().trim() + " ";
              start = 0;
             end = s.length();
          catch (IOException e) {System.exit(1);}
         next = s.indexOf(' ',start);
         double d = Double.parseDouble(s.substring(start,next));
         start = next+1;
         return d;
      public int nextInt() {
         if (start >= end)
           try {
            s = stdin.readLine().trim() + " ";
              start = 0;
             end = s.length();
          catch (IOException e) {System.exit(1);}
         next = s.indexOf(' ',start);
         int d = Integer.parseInt(s.substring(start,next));
         start = next+1;
         return d;
      public String nextLine() {
         if (start >= end)
           try {
            s = stdin.readLine().trim() + " ";
              start = 0;
             end = s.length();
          catch (IOException e) {System.exit(1);}
         String t = s.substring(start,s.length()-1);
         start = end = 0;
         return t;
    }=========
    phonenum.txt
    =========
    336 746 6915 Rorie Tim
    336 746 6985 Johnson Gary
    336 781 2668 Hoyt James
    606 393 5355 Krass Mike
    606 393 5525 Rust James
    606 746 3635 Smithson Norman
    606 746 3985 Kennedy Amy
    606 746 4235 Behrends Leonard
    606 746 4395 Rueter Clarence
    606 746 4525 Rorie Lonnie

    I don't see a Scanner.create() method in the Scanner class but I do see a constructor with the signature you want. Change
    Scanner fin = Scanner.create(file);
    to
    Scanner fin = new Scanner(file);

  • Passing Array to Another Method

    Hello, I created a program with an array in one of the methods. I have been trying to figure out how to correctly pass the array to another method in the same class. I know my problem is in my method delcaration statements. Could someone please show me what I am doing wrong? Please let me know if you have any questions. Thanks for your help.
    import javax.swing.*;
    import java.util.*;
    class Bank1 {
         public static void main(String[] args) {
              Bank1 bank = new Bank1();
              bank.menu();
         //Main Menu that initializes other methods
         public void menu( ) {
              Scanner scanner = new Scanner(System.in);
              System.out.println("Welcome to the bank.  Please choose from the following options:");
              System.out.println("O - Open new account");
              System.out.println("T - Perform transaction on an account");
              System.out.println("Q - Quit program");
              String initial = scanner.next();
              char uInitial = initial.toUpperCase().charAt(0);
              while (uInitial != 'O' && uInitial != 'T' && uInitial != 'Q') {
                   System.out.println("That was an invalid input. Please try again.");
                   System.out.println();
                   initial = scanner.next();
                   uInitial = initial.toUpperCase().charAt(0);
              if (uInitial == 'O') newAccount();
              if (uInitial == 'T') transaction();
         //Method that creates new bank account
         public Person[] newAccount( ) {
              Person[] userData = new Person[1];
              for (int i = 0; i < userData.length; i++) {
                   Scanner scanner1 = new Scanner(System.in);
                   System.out.println("Enter your first and last name:");
                   String name = scanner1.next();
                   Scanner scanner2 = new Scanner(System.in);
                   System.out.println("Enter your address:");
                   String address = scanner2.next();
                   Scanner scanner3 = new Scanner(System.in);
                   System.out.println("Enter your telephone number:");
                   int telephone = scanner3.nextInt();
                   Scanner scanner4 = new Scanner(System.in);
                   System.out.println("Enter an initial balance:");
                   int balance = scanner4.nextInt();
                   int account = i + 578;
                   userData[i] = new Person( );
                   userData.setName               ( name );
                   userData[i].setAddress          ( address );
                   userData[i].setTelephone     ( telephone );
                   userData[i].setBalance          ( balance     );
                   userData[i].setAccount          ( account     );
                   System.out.println();
                   System.out.println("Your bank account number is: " + userData[i].getAccount());
              return userData;
              menu();
         //Method that gives transaction options
         public void transaction(Person userData[] ) {
              System.out.println(userData[0].getBalance());

    Thank you jverd, I was able to get that to work for me.
    I have another basic question about arrarys now. In all of the arrary examples I have seen, the array is populated all at once using a for statement like in my program.
    userData = new Person[50];
    for (int i = 0; i < userData.length; i++) In my program though, I want it to only fill the first array parameter and then go up to the main menu. If the user chooses to add another account, the next spot in the array will be used. Can someone point me in the right direction for doing this?

  • 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!

  • Question about using class Scanner

    Hi, everyone. I am a newbie of Java. I am writing a simple program to let user input 3 integers by using Scanner.
    I know Scanner will igrone if more than 3.
    But if i want to tell user if they were wrong when they input more than 3 integers,
    is it possible if just use nextInt() to read?
    Thank you!
    Edited by: AlexChanMC on Feb 21, 2010 12:44 PM

    AlexChanMC wrote:
    javadoc said hasNext and next methods may block waiting for further input
    that is why after i input 3 integers press enter and without response, then i need to input 4th thing to continue?
    so how can i make the program response normally (print out) after input 3 integers and pressing enter and tell user they are wrong if they input 4 integers?
    Edited by: AlexChanMC on Feb 21, 2010 5:39 PMHmmm. I don't think I've ever used a Scanner to read from the standard input ... usually, from files, like so:
          Scanner sc = new Scanner(new File("myNumbers"));
          while (sc.hasNextLong()) {
              long aLong = sc.nextLong();
          }Perhaps you can just get the whole line, and see if it matches the regular expression
    "^(\\d+) (\\d+) (\\d+)$" // may need to trim the input line firstIf not, you don't have exactly three integers. That way, you only do a single nextLine() on the scanner.
    {?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Passing argstrings[1] to another method

    Hello I want to pass argstrings[1] to another method. Other stuff is being passed there to. Before I passed argstrings[1] the other stuff worked, now it does not.
    Please tell me why I am getting compilation errors.
    Thanks
    public static void main(String[] argStrings)
            String filePath = null;
            if(argStrings.length != 0)
                 filePath = argStrings[0];
            else
                 System.out.println("Enter a directory please");// Else you have to enter a directory
                 Scanner scan = new Scanner(System.in);
                    filePath = scan.nextLine();
            String copyDate = argStrings[1];
            Date dateToLookFor = new Date(copyDate);
            listFiles(filePath);// this no longer works as of the new log(datetolookfor)
            log(dateToLookFor);// just wanna pass this to the next method
       private static void log(File[] files, Date dateToLookFor)
       {

    Well i only get one compile error, cheers.
    So please could you help me what i have to do to this mess in order for it to work:
    Or just edit the code as I dont think there is much to do:
    Thanks
    import java.lang.*;
    import java.io.*;
    import java.util.*;
    * This application identifies files which could potentially be archived
    * and copied. A file is to be archived if the last modified date is more
    * than 100 days ago. A file is to be copied if it has been modified since
    * a given time. Only nominated extensions are to be considered. The java.
    * util.Calendar class contains relevant methods for comparing times and dates.
    * For instance, a command line of: java CrawlerApp Knuth 2005-12-28 php html
    * Will nominate for archiving or copying only php or html files in the Knuth
    * directory tree. It will only nominate for copying files modified after
    * midnight on the 28th of December, 2005.
    * The output from this application is two files (called archive.txt and copy.txt)
    * containing the names of files to be archived, and those which may be copied.
    * The names will follow the convention specified in the create application.
    * These two text files must appear in the root directory (Knuth, in this example).
    public class Crawler
       public static void main(String[] argStrings)
            String name = null;
            if(argStrings.length != 0)
                 name = argStrings[0];
            else
                 System.out.println("Enter a directory please");// Else you have to enter a directory
                 Scanner scan = new Scanner(System.in);
                    name = scan.nextLine();
            String copyDate = argStrings[1];
            listFiles(name, copyDate);
       private static void log(String copyDate, File[] files)
            PrintStream archivePS = null;
            PrintStream copyPS = null;
            try
                 archivePS = new PrintStream("archive.txt");
                 copyPS = new PrintStream("copy.txt");
                 // instantiate cutoff Calendar instance to test files with
                   Calendar cutoff = Calendar.getInstance();
                   // time now
               Date now = new Date();
                   // set cutoff time with current time
                   cutoff.setTime(now);
                   // subtract 100 days from current time
                   cutoff.add(Calendar.DAY_OF_YEAR, -100);//
                 Calendar calendar = Calendar.getInstance();
                 for(int j = 0; j < files.length; j++)
                      // get last modified time of file
                      long lastModified = files[j].lastModified();
                      // convert lastModified to a date
                      Date lastMod = new Date(lastModified);
                      // set the time for the Calendar instance with lastMod
                      calendar.setTime(lastMod);
                      // test against cutoff Calendar instance variable
                     if(lastMod.before(cutoff.getTime()))
                           archivePS.println(files[j]);
                         if(lastMod.before(cutoff.getTime()))
                              copyPS.println(files[j]);
                         // I will do copy later, just want to see if this works
            catch(FileNotFoundException fnfe)
                 System.err.println("Log error: " + fnfe.getMessage());
            catch(IOException ioe)
                 System.err.println("I/O exception: " + ioe.getMessage());
       private static void listFiles(String name, String copyDate)
           File f = new File(name);// Try to get a list of files in the directory
           File[] files = f.listFiles();// Make array of all the files in that directory
           log(files, copyDate);
           if(f.isDirectory())// If the argStrings[0] is a directory then do the following
               File[] children = f.listFiles(HTMLfilter);// Make an array of html files
               System.out.println("HTML files in " + name + " directory = " + children.length);
               File[] phpFiles = f.listFiles(PHPFilter);// Make an array of php files
               System.out.println("PHP files in " + name + " directory = " + phpFiles.length);
       private static FileFilter HTMLfilter = new FileFilter()
           public boolean accept(File f)// Accept directory Knuth
               //if(f.isDirectory()) return true;
               String name = f.getName().toLowerCase();
               return name.endsWith("html");
               //if(file is 100 days old)
       private static FileFilter PHPFilter = new FileFilter()
            public boolean accept(File f)
                 //if(f.isDirectory()) return true;
                 String name = f.getName().toLowerCase();
                 return name.endsWith("php");
    }

  • Scanner input question.

    I have an scanner which prompts the user to
    type some data into it.
    for example
    Lets say I have four strings.
    String id
    string name // this includes first and last name
    string address //this includes the full address.
    string price...
    When the first scanner prompts the user they type in
    DW123 and hits return
    the next scanner prompts the user to type i the name
    James Brown. and hits return.
    when this happens I will get the next scanner running together
    example
    enter your address==>,enter the price==>
    yet if I were to enter the name as JamesBrown it will work.
    is there away around this.
    any help would be great
    red

    Probably because you are calling the next method, which only returns a single token, not the nextLine method.
    Further, if you were to print out the address, I'm sure it would display "Brown".

  • 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();
    }

Maybe you are looking for

  • How can I get Apple to send my iTunes security question answers to my new email?

    Originally, I had my Apple account set up to a gmail account. But then, I deleted my gmail and connected my account to my hotmail instead. I'm going to lose this laptop soon for a new laptop swapout, and this is the only device that lets me use my iT

  • Office 2013 Multilanguage Deployment

    Hello, I have to deploy Office 2013 to our French users, English users and Italian users through SCCM 2012; they should have Office 2013 installed with same OS language. I already know how to do it on SCCM 2012, but I'd like to ask for your opinion.

  • Windows on a mac i not working

    Hi, I got a new iMac the other day and I went to installwindows using boot camp. Boot camp worked and all, but when I went to installgames and other software's I get this message that tells me that "windows cantuse the graphics that are installed bec

  • No response

    Hello, Have been trying to get some one from Verizon to respond to numerous emails sent. Has any one ever got any response from Verizon? Chat seems to be down all the time. (I was not surprised) The ordering service feature from the the web seems to

  • How and where do i download camera raw for cs6 64bit

    how and where do i download camera raw for cs6 64bit