我正在参加以 Java 作为语言的入门编程类(class)。我们正在做的任务困扰着我。我有一个 while 循环,要求输入数值,当输入字符串值时终止,即
while (sc.hasNextDouble())
{...}
接下来是另一个扫描仪输入,它正在使用
if (sc.hasNextLine())
问题是我使用一个字符串来终止顶部 while 循环,然后立即被扫描器消耗。我尝试将 if/else 语句与显式 break; 语句一起用于顶部循环,但这不起作用。无论我做什么,它仍然被传承。我应该如何处理这个问题?任何指示表示赞赏。
编辑:根据要求,这里是一些实际代码。请记住,这是针对任意类作业的,因此它可能没有多大意义。
//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 循环。
最佳答案
不传递来自 sc
扫描仪的数据的一种方法是创建一个新的扫描仪对象。我们称此为扫描
。这样,当您引用 scan
时,它就不会知道之前输入的 sc
扫描仪。
在您的 if
语句中,您将引用 scan
扫描器而不是 sc
扫描器。
数据从 while
循环传递到 if
语句的原因是它们都引用同一个对象,并且当您调用 sc.hasNext()
时,它会读取您在控制台中输入的最后一个内容。
关于Java:使用字符串来停止 while 循环,并由以下扫描仪输入消耗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52637588/