[英]How to use nextLine for scanner in java
我使用了正确的数据类型,但我找不到我的错误。 以下是我的代码;
Scanner input = new Scanner (System.in);
//Read
System.out.printf ("Enter the station: ");
String s = input.nextLine();
System.out.printf ("Enter quantity in liter: ");
double q = input.nextDouble();
System.out.printf ("Enter type of petrol: ");
String t = input.nextLine();
System.out.printf ("Enter price of petrol: ");
double p = input.nextDouble();
System.out.printf ("Enter discount: ");
int d = input.nextInt();
当我运行我的程序时,它不会 go 到下一行输入值。 对于汽油类型,我想输入“Super 99”之类的内容,所以我需要使用 input.nextLine() 但它不起作用。
试试下面的代码。
在 double q = input.nextDouble(); 之后使用另一个 input.nextLine() 线。
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
//Read
System.out.printf ("Enter the station: ");
String s = input.nextLine();
System.out.printf ("Enter quantity in liter: ");
double q = input.nextDouble();
input.nextLine();
System.out.printf ("Enter type of petrol: ");
String t = input.nextLine();
System.out.printf ("Enter price of petrol: ");
double p = input.nextDouble();
System.out.printf ("Enter discount: ");
int d = input.nextInt();
}
/* *****这对你有用,亲爱的 */
导入 java.util.*; class 测试仪 {
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
System.out.printf ("Enter the station: ");
String s = input.nextLine();
System.out.printf ("Enter quantity in liter: ");
double q = input.nextDouble();
input.nextLine();
System.out.printf ("Enter type of petrol: ");
String t = input.nextLine();
System.out.printf ("Enter price of petrol: ");
double p = input.nextDouble();
System.out.printf ("Enter discount: ");
int d = input.nextInt();
}
}
你只需要使用:
System.out.println("Enter the type of petrol");
它将像这样工作:
Enter the type of petrol
Super99 //its what you will enter as per your choice here the cursor will automatically take you to the next line
要打印包含换行符的行:
System.out.println("Enter price of petrol: ");
// -OR-
System.out.printf("Enter price of petrol: \n");
要获取单个令牌(单个单词、数字、integer 等):
scanner.nextInt(); // integer
scanner.next(); // word
获取整行:
scanner.useDelimiter("\r?\n");
// now the scanner is in 'entire line' mode
scanner.nextInt(); // still works
scanner.next(); // gets one line's worth
到 go 回到“每个空格一个令牌”模式,输入例如“abc”(回车)将导致 3 .next()
数据调用可用:
scanner.reset();
// -OR-
scanner.useDelimiter("\s+");
提示:不要混合nextLine()
和任何其他next
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.