問題:(十進制到十六進制)編寫一個程序,提示用戶輸入 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