2013-11-05 29 views
-2

嗨,大家好,我正在学习java以便在Android中进行编码,我在PHP中有一些经验,所以我分配了一个练习,但无法找到正确的循环,我试过其他/ if ,但仍然无法找到它,这是练习:这个练习在Java中的右循环

1-提示用户输入学生人数,它必须是一个可以除以10的数字(数字/ 10)= 0 012-2-检查的用户输入,如果用户输入不能被10整除,则要求用户输入,直到他输入正确的输入为止

我如何编码到目前为止,while循环没有工作任何想法如何改进或使其工作?

package whiledowhile; 

import java.util.Scanner; 

public class WhileDoWhile { 

    public static void main(String[] args) { 

     Scanner user_input = new Scanner(System.in); 
    /* int counter = 0; 
     int num; 
     while (counter <= 100) { 
      System.out.println("Enter number"); 
      num = user_input.nextInt(); 
      counter += num; // counter = counter + num 
      //counter ++ = counter =counter +1 
     } 

     System.out.println("Sum = "+ counter); 
*/ 

     int count = 0; 
     int num; 
     System.out.println("Please enter a number: "); 
     num = user_input.nextInt(); 
     String ex; 

     do { 
    System.out.print("Wrong Number please enter again: "); 
      num++; 


    } 
     while(num/10 != 0); 

    } 
} 
+0

'if/else'不是一个循环。任何可以通过'while'循环完成的事情都可以通过'for'循环完成,任何可以通过'for'循环完成的事情都可以通过'while'循环完成。你应该使用哪一个是可读性的问题。 – nhgrif

回答

0

两件事情:

  • 我想你的意思是使用%,不/
  • 你可能想有你的while循环的内部数据录入

    while (num % 10 != 0) { 
    // request user input, update num 
    } 
    // do something with your divisible by 10 variable 
    
0

当使用while循环时,你将要执行一些代码,而条件成立。此代码需要进入dowhile块。对于你的例子,一个do-while循环似乎更合适,因为你希望代码至少执行一次。此外,您希望在您的条件内使用模运算符%,而不是/。见下:

Scanner s = new Scanner(System.in); 
int userInput; 

do { 
    // Do something 
    System.out.print("Enter a number: "); 
    userInput = s.nextInt(); 

} while(userInput % 10 != 0);