做与字符串和拖曳声明的问题

时间:2017-04-21 22:03:54

标签: java

   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);  

所以应该这样吗?

但它不接受这一点。这表明需要初始化

我该怎么办?

3 个答案:

答案 0 :(得分:0)

正如@yogidilip所建议的

 do{  
 nmOfItems = m105.next();  
 if(nmOfItems.equals("stop")) {
    break;
 }         
 prOfItems = m105.nextDouble();     
 sum = (double)sum + prOfItems; 
 }   
 while(true);  

答案 1 :(得分:0)

在操作后立即检查条件,并在从控制台读取后立即退出循环。

do
{
    nmOfItems = m105.next();  
    if(nmOfItems.equalsIgnoreCase("stop")) 
    {
        break;
    }         
   prOfItems = m105.nextDouble();     
  sum = (double)sum + prOfItems; 
}   
while(true);

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; 
}

答案 2 :(得分:-2)

只是你应该在不做的时候使用

因为do while必须至少有一次迭代,并且在检查之前执行

您的代码应为:

 nmOfItems = m105.next();
 while( !nmOfItems.equals("stop"))
 {
      prOfItems = m105.nextDouble();     
      sum = (double)sum + prOfItems;  
 }