- #1
notorious9000
- 11
- 0
Java help ! (how to not to use if statement)
My teacher asked the user for an integer and converted it into a number in base N, where N was a value between 2 and 9, inclusive. Expand this program to allow values of N between 2 and 36, inclusive, where digits representing the numbers 10, 11, 12, …, 36 are represented as A, B, C, …, Z, respectively. Do not use an if-statement with 20+ different cases to determine what character to append to the current string. Instead, use character arithmetic to determine which character should be output.
Red lines are those that I don't understand.
I don't know what he is talking about.
Sorry English is not my first language...
Is he saying that user's input should be in alphabets from 10[A] ~ 36[Z] ?
And This is what I have.
import java.util.Scanner;
public class MinsooLab5d{
public static void main(String[] args){
int n, b;
String r = "";
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : "); //insert a number
n = sc.nextInt();
int c = n;
System.out.print("Enter a base number [2~36] : ");
b = sc.nextInt();
if(b>=2 && b<=36){
while(c != 0){
int x = c % b;
r=x+r;
c=c/b;
}
System.out.println(n + "base" + b + " in binary is " + r); //print out result
}
else
{
System.out.println("Out of base number range !");
}
}
}
My teacher asked the user for an integer and converted it into a number in base N, where N was a value between 2 and 9, inclusive. Expand this program to allow values of N between 2 and 36, inclusive, where digits representing the numbers 10, 11, 12, …, 36 are represented as A, B, C, …, Z, respectively. Do not use an if-statement with 20+ different cases to determine what character to append to the current string. Instead, use character arithmetic to determine which character should be output.
Red lines are those that I don't understand.
I don't know what he is talking about.
Sorry English is not my first language...
Is he saying that user's input should be in alphabets from 10[A] ~ 36[Z] ?
And This is what I have.
import java.util.Scanner;
public class MinsooLab5d{
public static void main(String[] args){
int n, b;
String r = "";
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : "); //insert a number
n = sc.nextInt();
int c = n;
System.out.print("Enter a base number [2~36] : ");
b = sc.nextInt();
if(b>=2 && b<=36){
while(c != 0){
int x = c % b;
r=x+r;
c=c/b;
}
System.out.println(n + "base" + b + " in binary is " + r); //print out result
}
else
{
System.out.println("Out of base number range !");
}
}
}