The error in this program is the while statement in the main method. It was working before in the sense that when I invalid input value it would stop and exit program and when I input proper value it would loop through the while statement once but suddenly after more work too my code it loops infinity for any input below 1025. Ignore the sloppiness of the output of the program as I am still editing that, the main problem is why it does not stop looping in the while statement.
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("");
}
}
Why do you need a while
loop if you are going to execute it only once ? Consider if
instead.
Never mind, how about breaking the while
loop ?
You can use break;
wherever applicable, to stop execution of a loop.
For example :
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("");
}
break;
}