代码执行得很好,但是警告仍然困扰着我。我已经使用了指示仅用于循环的变量decNumber
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int decNumber,rem=0;
System.out.print("Enter a decimal number: ");
decNumber = in.nextInt();
for(int i=0;decNumber>0;i++) {
rem = (decNumber%2);
decNumber = (decNumber/2);
System.out.println(rem);
}
最佳答案
这会更加洁净:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a decimal number: ");
int decNumber = in.nextInt();
for (int i = decNumber; i > 0; i = i / 2) {
int rem = (i % 2);
System.out.println(rem);
}
in.close();
}
}
这里的优点是
您无需销毁
decNumber
变量,因此以后仍可以使用它for
循环可防止内部行为(即rem
)流失for
循环实际上像for一样使用,而不是while