Java 使用字符串和tow语句问题执行while
那么应该是这样吗 但它不接受这一点。这表明nee需要初始化Java 使用字符串和tow语句问题执行while,java,Java,那么应该是这样吗 但它不接受这一点。这表明nee需要初始化 我该怎么办?你应该边用边做 因为do while必须至少有一个迭代,并且它在检查while之前进行 您的代码应该是: double urWallet, prOfItems; double sum=0; String nmOfItems; System.out.print("How much money do you have? "); urWallet = m105.nextDouble(); Sy
我该怎么办?你应该边用边做 因为do while必须至少有一个迭代,并且它在检查while之前进行 您的代码应该是:
double urWallet, prOfItems;
double sum=0;
String nmOfItems;
System.out.print("How much money do you have? ");
urWallet = m105.nextDouble();
System.out.println("Pleas, insert the name of the items in the invoice(in one word): ");
System.out.println("Enter word \"stop\"as the name of product to finish your input:");
while( !nmOfItems.equals("stop"));
{
nmOfItems = m105.next();
prOfItems = m105.nextDouble();
sum = (double)sum + prOfItems;
}
if (sum > urWallet)
{
System.out.println("You don't have much money");
}
else
System.out.println("You have much money");
System.out.printf("%s is the item with the minimum price (wich is %.3f SAR) \n ",nmOfItems , sum);
正如@yogidilip所建议的那样
nmOfItems = m105.next();
while( !nmOfItems.equals("stop"))
{
prOfItems = m105.nextDouble();
sum = (double)sum + prOfItems;
}
在操作后立即检查条件,并在从控制台读取后立即中断循环
do{
nmOfItems = m105.next();
if(nmOfItems.equals("stop")) {
break;
}
prOfItems = m105.nextDouble();
sum = (double)sum + prOfItems;
}
while(true);
或
do
{
nmOfItems = m105.next();
if(nmOfItems.equalsIgnoreCase("stop"))
{
break;
}
prOfItems = m105.nextDouble();
sum = (double)sum + prOfItems;
}
while(true);
您可以设置if条件,然后中断。
nmOfItems
除了停止之外还有什么意义?当用户输入stop the code停止循环时,打印价格并回答我的问题。顺便说一句,您上次的编辑使问题更难理解。请仔细阅读问题。很抱歉看到编辑。现在它是一个无限循环。为什么是无限循环?您从未将nmOfItems
的值设置为循环中的任何内容,因此,如果它进入内部,它将永远运行。它起作用了。谢谢你,你能解释一下这些步骤吗;我以前从未使用过它如果这个答案对你有帮助,那么你应该接受它while
或者do while
始终接受布尔表达式。循环将继续执行,直到条件变为false
,所以我在这里写了while(true)
表示此循环始终为真并继续执行,但当用户写入stop时,如果
条件为真,中断
将退出循环流,如果我想打印用户输入的最低价格
while (true)
{
nmOfItems = m105.next();
if(nmOfItems.equalsIgnoreCase("stop"))
{
// If user starts the program by error, or user wants to discontinue process
break;
}
prOfItems = m105.nextDouble();
sum = (double)sum + prOfItems;
}