【发布时间】:2017-07-07 01:44:14
【问题描述】:
我对编码很陌生,希望你们能帮助我。 我遇到了 nextDouble 不等待 print.ln 收集数据的问题。 使用我的启动输入,我必须输入两个数字才能移动到下一行并要求我已经输入的第二个数字,因为它没有等待。 到那时,它还决定请求第三个数字并接受该数字的输入,但可以毫无问题地请求第三个和第四个数字。 当它重复时,它也会发生在循环内部。
我知道使用 nextDouble 并不意味着它会“等待”换行符,我知道 nextNumbertype 没有换行符标志,但通常的技巧 在获得双精度后添加“input.nextLine”似乎不起作用。
我知道我可以将所有输入作为字符串稍后再转换,但这是一项家庭作业,我的教授似乎想要一种非常具体的方式。
关于什么是错的或我可以尝试什么的任何想法?
这是输出:
Enter x1 or <crtl + z> to quit
1
4
Please input the x2 number:
Please input the y1 number:
1
Please input the y2 number:
5
Distance is 5.000000
Enter x1 or <crtl + z> to quit
下面是实际代码:
import java.util.Scanner;
public class distanceFinder {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double x1 = 0;
System.out.println("Enter x1 or <crtl + z> to quit");
x1 = input.nextDouble();
while(input.hasNext())
{
System.out.println("Please input the x2 number:");
double x2 = input.nextDouble();
System.out.println("Please input the y1 number:");
double y1 = input.nextDouble();
System.out.println("Please input the y2 number:");
double y2 = input.nextDouble();
double x3 = 0;
double y3 = 0;
double xy1 = 0;
x3 = Math.pow((x2 - x1), 2);
y3 = Math.pow((y2 - y1), 2);
xy1 = x3 + y3;
double distance = Math.sqrt(xy1);
System.out.printf("Distance is %.6f %n%n%n", distance);
System.out.println("Enter x1 or <crtl + z> to quit");
x1 = input.nextDouble();
}
input.close();
}
}
【问题讨论】:
-
问题在于
hasNext根据 javadcos 此方法可能会在等待输入扫描时阻塞。