这个程序的错误是 main 方法中的 while 语句。从某种意义上说,当我输入无效的输入值时,它会停止并退出程序,当我输入正确的值时,它会循环一次 while 语句,但在完成更多工作后,我的代码突然循环无穷大,任何输入低于 1025。忽略程序输出的草率,因为我仍在编辑它,主要问题是为什么它不会停止在 while 语句中循环。
import java.util.Scanner;
public class DNS
{
public static void main(String[] args)
{
int y;
Scanner input = new Scanner( System.in);
System.out.println("java DisplayNumberSystems");
System.out.println("Enter a decimal value to display to: ");
y = input.nextInt();
while(y !=1025)
{
for(int x=0; x <=y; x++)
{
System.out.println("Decimal");
System.out.println(x);
}
for(int i=0; i <=y; i++)
{
System.out.println("");
System.out.println("Binary");
convertToBinary(i);
}
System.out.println("");
for(int z=0; z <=y; z++)
{
System.out.println("Hex");
convertToHex(z);
}
System.out.println("");
for(int d=0; d <=y; d++)
{
System.out.println("Octal");
convertToOctal(d);
System.out.println("");
}
}
}
public static void convertToBinary(int x)
{
if(x >0)
{
convertToBinary(x/2);
System.out.printf(x%2 + "");
}
}
public static void convertToOctal(int x)
{
int rem;
while(x >0)
{
rem = x%8;
System.out.printf("%d", rem);
x=x/8;
}
}
public static void convertToHex(int x)
{
int rem;
while(x >0)
{
rem = x%16;
switch(rem)
{
case 1:
System.out.printf("1");
break;
case 2:
System.out.printf("2");
break;
case 3:
System.out.printf("3");
break;
case 4:
System.out.printf("4");
break;
case 5:
System.out.printf("5");
break;
case 6:
System.out.printf("6");
break;
case 7:
System.out.printf("7");
break;
case 8:
System.out.printf("8");
break;
case 9:
System.out.printf("9");
break;
case 10:
System.out.printf("A");
break;
case 11:
System.out.printf("B");
break;
case 12:
System.out.printf("C");
break;
case 13:
System.out.printf("D");
break;
case 14:
System.out.printf("E");
break;
case 15:
System.out.printf("F");
break;
}
x=x/16;
}
System.out.println("");
}
}