3 回答

TA貢獻1828條經驗 獲得超3個贊
請看一下 和 的這個簡單用法示例。MapList
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(0, "");
map.put(1, "0");
map.put(3, "f");
map.put(5, "-1");
map.put(7, "V");
map.put(9, "-/");
map.put(11, "()");
map.put(13, "()");
map.put(15, "^");
map.put(17, "E");
map.put(19, "=");
map.put(21, "x");
map.put(23, "y");
List<Integer> listOfInputIntegers = new ArrayList<>();
Scanner input = new Scanner(System.in);
int integer;
do {
System.out.print("Input your next number:");
integer = input.nextInt();
listOfInputIntegers.add(integer);
} while (integer != 0);
for (int i : listOfInputIntegers) {
System.out.print(map.get(i));
}
System.out.println();
}
https://docs.oracle.com/javase/8/docs/api/java/util/Map.html
https://docs.oracle.com/javase/8/docs/api/java/util/List.html

TA貢獻1802條經驗 獲得超5個贊
將整數到字符串映射保留在 java.util.Map 中,以便在用戶鍵入 int 后輕松獲取相應的字符串。如果鍵入的字符串具有相應的字符串,請將其添加到要打印的字符串列表中。如果鍵入的字符串沒有相應的字符串,請打印它并要求下一個intintint
在用戶鍵入 0 停止循環后,通過聯接列表中的所有字符串,從累積的字符串列表中創建一個字符串,直到用戶鍵入 0
public class Test {
private static Map<Integer, String> integerToStringMappings = new HashMap<>();
static {
integerToStringMappings.put(1, "0");
integerToStringMappings.put(3, "f");
integerToStringMappings.put(5, "-l");
.... // and so on for all the integers mapped to strings
}
public static void main(String[] args) {
List<String> strings = new ArrayList<>();
Integer number = input.nextInt();
while(number != 0) {
System.out.println("Enter your integer: ");
number = input.nextInt();
String correspondingString = integerToStringMappings.get(number);
if ( correspondingString == null ) {
System.out.println("int: " + number);
} else {
strings.add(correspondingString);
}
}
System.out.println(String.join("", strings));
}
}

TA貢獻1829條經驗 獲得超7個贊
這可以通過使用 ArrayList 輕松實現,因為您不知道數組的大小(除非您專門詢問用戶將輸入的項目數)。
收集用戶的數字后,只需遍歷 ArrayList 中的每個數字,即可使用 if-else 語句生成相應的輸出。在這種情況下,我強烈建議使用 switch 語句。
ArrayList<Integer> values = new ArrayList<Integer>();
int number = input.nextInt();
while(number != 0) {
values.add(number);
number = input.nextInt();
}
for(int i=0; i<values.size(); i++) {
int numberCheck = values.get(i);
//Run through the if-else statements using numberCheck
System.out.println("int: " + numberCheck);
}
添加回答
舉報