我被要求仅使用永无止境的循环来打印 2 的倍数。
尝试:
import java.util.Scanner;
public class Infiniteloop {
public static void main (String [] args)
{
Scanner input=new Scanner (System.in);
int number,x;
System.out.print("Enter a number");
number=input.nextInt();
if(number%2==0)
{
while(number>=0)
{
x= (++number);
System.out.println(x);
}
}
}
}
我只能使用while循环。所以我尝试将2的余数设置为零。我尝试使用计数器,但它不会增加它。不断打印出零。我需要一些帮助。谢谢。
最佳答案
假设您要提示用户输入起始数字,然后打印以下所有偶数:
number = input.nextInt(); //read the input
number += number % 2; //if input is odd, add 1
while (true)
{
System.out.println (number);
number += 2;
}
假设您想检查偶数:
while (true)
{
number = input.nextInt();
if (number % 2 == 0) System.out.println (number);
}
或者,如果您不关心空行:
while (true) System.out.println (input.nextInt () % 2 == 0 ? "even" : "");
编辑:二的幂也是如此:
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
int number;
while (true)
{
System.out.print ("Enter a number");
number = input.nextInt ();
while ( (number & 1) == 0) number >>= 1;
if (number == 1) System.out.println ("Perfect divisor.");
}
关于Java,无限循环 - 仅限 2 的倍数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6126155/