Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

java - Scanner and nextInt discard integer

I am using Scanner for taking user input in java. when i use nextInt() and the user inputs "2 5", then the value "2" is assigned and 5 is thrown away. What if I want to display that such an input is an error? One solution that comes to my mind is that i can use nextString() instead of nextInt() and then work my way out. But can anybody suggest a better solution?

i realized that it is not throwing away the integer after space, instead it is using it for the next input.

import java.util.Scanner;
class Test{
static Scanner in=new Scanner(System.in);
static void trial(){
    int k=in.nextInt();
    System.out.println(k);
    System.out.println(k);
}

public static void main(String[] args){     
    int k=in.nextInt();
    System.out.println(k);
    System.out.println(k);
    trial();        
}
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

1. First use nextLine() to read the entire line.

2. Use Integer.parseInt() method to validate the integer input.

Eg:

Scanner scan = new Scanner(System.in);
String s = scan.nextLine();

try{
    Integer.parseInt(s);
}
catch(NumberFormatException ex){
    System.out.println("Its not a valid Integer");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...