gpt4 book ai didi

java - 为什么程序在读取下一行之前就运行了?

转载 作者:行者123 更新时间:2023-12-02 03:09:25 26 4
gpt4 key购买 nike

public class Solution {

public static void main(String[] args) {
int i = 4;
double d = 4.0;
String s = "HackerRank ";

Scanner scan = new Scanner(System.in);
/* Declare second integer, double, and String variables. */
/* Read and save an integer, double, and String to your variables.*/
int sec = scan.nextInt();
double db = scan.nextDouble();
String newWord = scan.nextLine();

/* Print the sum of both integer variables on a new line. */
System.out.println(i + sec);
/* Print the sum of the double variables on a new line. */
System.out.println(d + db);
/* Concatenate and print the String variables on a new line;
the 's' variable above should be printed first. */
System.out.println(s + newWord);
scan.close();
}
}

如果String newWord = scan.nextLine();位于 int sec = scan.nextInt(); 之前不过它工作得很好。

最佳答案

只需将 String newWord = scan.nextLine(); 替换为 String newWord = scan.next();

这里:

    double db = scan.nextDouble(); 
String newWord = scan.nextLine();

scan.nextDouble() 不会读取所有行,仅读取 double 行。
因此,scan.nextLine()将当前行的其余部分分配给newWord变量,即一个空的String:"".

If String newWord = scan.nextLine(); is placed before int sec = scan.nextInt(); it works fine though.

确实是因为 "" 是字符串的有效值。因此,当您执行此操作时,newWord 具有 "" 值。

<小时/>

编辑评论

尽量避免将 nextInt()nextDouble() 等与 nextLine() 方法混合使用。
您可以执行 nextLine() 来读取空字符串,然后再次执行另一个 nextLine() 来读取用户的输入。

或者,即使对于数字类型,您也只能使用 nextLine() 并从 String 输入创建数值。这是您的代码的示例:

public static void main(String[] args) {
int i = 4;
double d = 4.0;
String s = "HackerRank ";

Scanner scan = new Scanner(System.in);
/* Declare second integer, double, and String variables. */
/* Read and save an integer, double, and String to your variables.*/
int sec = Integer.valueOf(scan.nextLine());
double db = Double.valueOf(scan.nextLine());
String newWord = scan.nextLine();

/* Print the sum of both integer variables on a new line. */
System.out.println(i + sec);
/* Print the sum of the double variables on a new line. */
System.out.println(d + db);
/* Concatenate and print the String variables on a new line;
the 's' variable above should be printed first. */
System.out.println(s + newWord);
scan.close();
}

关于java - 为什么程序在读取下一行之前就运行了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41272389/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com