您好我创建了一个二维数组,允许用户输入一个单词然后告诉他们价格。如何通过使用for循环来改进本程序?感谢将来的回复,抱歉编辑错误!
String[][] the ={
{"Best Health Basic","R450.00"},
{"Best Health Basic Plus","R575.00"},
{"Best Health Premium","700.00"},
{"Best Health Premium Plus","950.00"}};
String INPUT = JOptionPane.showInputDialog("Enter one of the following\nBest Health Basic\nBest Health Basic Plus\nBest Health Premium\nBest Health Premium Plus");
if (the[0][0].equalsIgnoreCase(INPUT)) {
System.out.println("found it " + the[0][1]);
return;
}
if (the[1][0].equalsIgnoreCase(INPUT)) {
System.out.println("found it " + the[1][1]);
return;
}
if (the[2][0].equalsIgnoreCase(INPUT)) {
System.out.println("found it " + the[2][1]);
return;
}
if (the[3][0].equalsIgnoreCase(INPUT)) {
System.out.println("found it " + the[3][1]);
return;
}
答案 0 :(得分:0)
使用for-loop
从0循环到数组的长度。好的做法是使用变量的长度(the.length = 4
)。
for (int i=0; i<the.length; i++) {
if (the[i][0].equalsIgnoreCase(INPUT)) {
System.out.println("found it " + the[i][1]);
return;
}
}
但更好的做法是使用HashMap
来存储一对value-key
:
Map<String, String> map = new HashMap<>();
map.put("Best Health Basic","R450.00");
map.put("Best Health Basic Plus","R575.00");
map.put("Best Health Premium","700.00");
map.put("Best Health Premium Plus","950.00");
System.out.println("found it " + map.get(INPUT));
答案 1 :(得分:0)
您可以执行以下操作:
for (int i = 0; i < theArrayWithPrices.length; i++) {
if (theArrayWithPrices[i][0].toLowerCase().contains(userInput.toLowerCase())) {
System.out.println("Product " + theArrayWithPrices[i][0] + " costs " + theArrayWithPrices[i][1]);
}
}
注意:
老实说,这是超级基本的东西。你真的想做更多的自学;例如,转向Oracle的优秀教程;并通过“基础”工作。