-2

大家好,我正在学习java以便在Android中编码,我有一些PHP经验,所以我被分配了一个练习,但找不到合适的循环,我尝试了else/if,虽然,但仍然找不到它,这是练习:

1- 提示用户输入学生人数,必须是可以被 10 整除的数字(数字 / 10)= 0 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 ); 

    }
}
4

2 回答 2

0

使用 while 循环时,您需要在条件为真时执行一些代码。此代码需要进入doorwhile块。对于您的示例,do-while 循环似乎更合适,因为您希望代码至少执行一次。此外,您需要%在 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);
于 2013-11-05T00:39:01.067 回答
0

两件事情:

  • 我认为你的意思是使用%,而不是/
  • 您可能希望在 while 循环中输入数据

    while (num % 10 != 0) {
    // request user input, update num
    }
    // do something with your divisible by 10 variable
    
于 2013-11-05T00:31:47.657 回答