import java.util.Scanner;
public class Solution {
//java program for accepting an integer, an double and a set of string from the user.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
double d= scan.nextDouble();
String s= scan.nextLine();
scan.next();
scan.nextLine();//clearing input buffer.
//printing the inputs taken from the user.
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
}
答案 0 :(得分:-1)
按enter键时,\n
特殊字符将保留在缓冲区中。因此,在double d= scan.nextDouble();
之后,缓冲区将保留\n
并将其存储在行String s= scan.nextLine();
中的字符串s中。要摆脱它,只需修改你的代码:
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
double d= scan.nextDouble();
// this will clear the '\n'
scan.nextLine();
String s= scan.nextLine();
//printing the inputs taken from the user.
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
另一种处理方法是始终使用nextLine();
进行扫描并按照您希望的方式进行解析。这样做可以更容易地检查用户输入的数据是否有效。