我正在使用Java作为语言进行介绍性编程。我们正在执行的任务使我心烦意乱。我有一个when循环请求数值,当输入字符串值时终止,即
while (sc.hasNextDouble())
{...}
然后是另一个扫描器输入,它使用
if (sc.hasNextLine())
问题是,我使用一个字符串来终止top while循环,然后由扫描仪立即使用该循环。我试图在top循环中使用if/ not语句,并显式地中断;语句,但这不起作用。不管我做了什么,它还是会被传下去。我该怎么处理这个?任何指南针都会赏识。
编辑:根据请求,下面是一些实际的代码。请记住,这是一个任意的班级分配,所以它可能没有很多意义。
//Request user input
System.out.print("Please enter multiple double values. Enter q or any non double value to quit.");
double doubleValue = 0.00; //declare doubleValue variable (for each entered double value)
double sum = 0.00; //declare starting sum value variable at 0.00
double doubleAverage = 0.00; //declare average of doubles variable
//declare largest double value variable as MIN_VALUE to ensure any entered value is larger
double largestDouble = Double.MIN_VALUE;
//declare smallest double value variable as MAX_VALUE to ensure any entered value is smaller
double smallestDouble = Double.MAX_VALUE; //declare smallest double value variable
int count = 0; //set starting count
while (sc.hasNextDouble())
{
doubleValue = sc.nextDouble();
//System.out.print("Please enter another double value. Enter -1 to stop entering values.");
sum = sum + doubleValue;
count++;
}
/*
* This section prompts the user for their first name and printd it in reverse.
*/
System.out.print("Please enter your first name:");
String fName = ""; //declare fName variable before requesting input
if (sc.hasNext())
{
fName = sc.next();
…
在此之后,用于终止用于结束结束if语句的while循环的字符串值。
发布于 2018-10-03 18:25:02
不从sc
扫描仪传递数据的一种方法是创建一个新的scanner对象。让我们称其为scan
。这样,当您引用scan
时,它将不知道前面输入的sc
扫描器。
在if
语句中,您将引用scan
扫描器而不是sc
扫描器。
数据从while
循环传递到if
语句的原因是,它们都引用同一个对象,当您调用sc.hasNext()
时,它读取了输入到控制台的最后一个内容。
发布于 2018-10-03 18:14:40
尝试将输入读取为字符串,然后将其转换为字符串。
Scanner sc= new Scanner(System.in);
String in = sc.nextLine();
while (!in.equals("q")) {
try {
Double d = Double.valueOf(in);
// do whatever you like with d
} catch (NumberFormatException ex) {
System.out.println("oi, that is not a double");
}
in = sc.nextLine();
}
发布于 2018-10-05 04:38:07
我的指导员提供的另一个有效选项是使用一个虚拟变量来使用扫描仪输入,i.e.something如下所示:
String fName = sc.next(); // Consume the Q or q here
。
https://stackoverflow.com/questions/52637588
复制