Input on console doesn't work with this java program - why?
With this program it skips past the inputs - and outputs this to the console:
C:\Users\User\workspace\ClassManager\bin>java AccessPupilData
What would you like to do?
l = list pupils -------- a = add pupil ---------
a
a
You want to add a pupil.
Enter your first name:
Enter your surname:
Firstname :null
Surname: null
Age :0
You created a pupil called null null who is aged 0
(I'm using a dos prompt to run the program in, not the eclipse console). Why don't I get to input when the scanner is called?
First the initial class that kicks off everything:
public class AccessPupilData {
public static void main (String arguments[]){
...
case 'a': Pupil pupil = new Pupil(); break;
And then the Pupil class that is where I want to collect all the information:
import java.util.Scanner;
public class Pupil {
private String surname;
private String firstname;
private int age;
public Pupil(){
Scanner in = new Scanner(System.in);
// Reads a single line from the console
// and stores into name variable
System.out.println("Enter your first name: ");
if(in.hasNext()){
this.firstname = in.nextLine();
}
System.out.println("Enter your surname: ");
if(in.hasNext()){
this.surname = in.nextLine();
}
// Reads a integer from the console
// and stores into age variable
if(in.hasNext()){
System.out.println("Enter your age: ");
this.age=in.nextInt();
}
in.close();
// Prints name and age to the console
System.out.println("Firstname :" +firstname);
System.out.println("Surname: " + surname);
System.out.println("Age :"+ age);
System.out.print("You created a pupil called " + this.firstname + " " + th开发者_Python百科is.surname + " who is aged " + this.age);
}
}
Use Console.readLine
Console c = System.console();
this.firstname = c.readLine("Enter your first name: ");
I would suggest using BufferedReader
Scanner is definitely very convenient to use but it is slower since it has to read the content of the stream every time next token in the stream is requested. While Buffered Reader buffers the tokens so that there is no need to read from the stream again.
Quoted from Scanner vs BufferedReader.
public static void main(String[] args) {
String firstName = getInput("Enter your first name: ");
System.out.println("Hello " + firstName);
}
public static String getInput(String prompt) {
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
System.out.print(prompt);
System.out.flush();
try {
return in.readLine();
} catch (IOException e) {
return "Error: " + e.getMessage();
}
}
精彩评论