问题:(十进制到十六进制)编写一个程序,提示用户输入 0和15之间的整数,并显示其相应的十六进制数。下面是一些样品运行:Java十进制到十六进制程序
输入一个十进制值(0至15):11 的十六进制值是乙
输入一个十进制值(0至15):5 的十六进制值是5
输入十进制值(0到15):31 31是无效输入
以下是我的代码。 1.我并不真正了解charAt(0)
,也不知道我做错了什么。 1-9 = 1-9和10-15 = A-F。我只能使用代码中看到的内容。没有特别的toHexStrings
cases
或arrays
。这是基础知识的基础。我不明白为什么RULE1被忽略,或者是否有更多问题。
import java.util.Scanner;
public class NewClass1 {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a decimal value (0 to 15): ");
String decimal = input.nextLine();
// RULE1
char ch = decimal.charAt(0);
if (ch <= 15 && ch >= 10) {
System.out.println("The hex value is " + (char)ch);
}
// RULE2
else if (ch <= 10 && ch >= 0) {
System.out.println("Tsshe hex value is " + ch);
}
// RULE3
else {
System.out.println("Invalid input");
}
}
}
RULE1被忽略,我看不出为什么。现在是凌晨2点,我已经在这里呆了4个小时了。没有晦涩的评论,因为如果我知道如何解决这个问题,我就不会在这里。我需要一些帮助来理解错误。
UPDATE2: import java.util.Scanner;
public class NewClass1 {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a decimal value (0 to 15): ");
int decimal = input.nextInt();
if (decimal <= 15 && decimal >= 10) {
System.out.println("The hex value is " + (char)decimal);
}
else if (decimal < 10 && decimal >= 0) {
System.out.println("The hex value is " + decimal);
}
else {
System.out.println("Invalid input");
}
}
}
RULE1的作品,但不产生数字的字符/字母。我必须将其设置为变量吗?
UPDATE3:
import java.util.Scanner;
public class NewClass1 {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a decimal value (0 to 15): ");
int decimal = input.nextInt();
// RULE1
if (decimal <= 15 && decimal >= 10) {
int value = decimal - 10 + 10;
System.out.println("The hex value is " + (char)value);
}
// RULE2
else if (decimal < 10 && decimal >= 0) {
System.out.println("The hex value is " + decimal);
}
// RULE3
else {
System.out.println("Invalid input");
}
}
}
我觉得我接近,但结果仍然是无效的规则1
UPDATE4:工作版本。
import java.util.Scanner;
public class NewClass {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a decimal value (0 to 15): ");
int decimal = input.nextInt();
if (decimal <= 15 && decimal >= 10) {
int value = ('A' + decimal - 10);
System.out.println("The hex value is " + (char)value);
}
else if (decimal <= 10 && decimal >= 0) {
System.out.println("The hex value is " + decimal);
}
else {
System.out.println("Invalid input");
}
}
}
按照预期工作。谢谢你们!谢谢Pham Trung。
你现在如何看待'charAt'呢? – immibis 2015-02-10 07:43:22
我'想'是假设召唤一个与其数字对应的字符/符号。 – 2015-02-10 08:37:33
不,它会返回字符本身。所以“15”.charAt(0)='1',但'1'不是1. – immibis 2015-02-10 08:48:10