Noo*_*ick 8 java arrays string converter
我只是在一本Java夏季课的书中搞一些练习因为我有点领先,这意味着这不是功课.我收到一条错误消息,指出你无法转换String为int但是两者都是字符串,一个是变量,一个是数组.
就是这条线,我遇到了麻烦...... select = items[select];
public class CarpentryChoice {
public static void main(String[] args) {
String items [] = {"Table", "Desk", "Chair", "Couch", "Lazyboy"};
int price [] = {250, 175, 125, 345, 850};
String select;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter an item to view it's price: ");
select = scan.nextLine();
for(int i=0; i < items.length; i++) {
select = items[select];
}
}
}
Run Code Online (Sandbox Code Playgroud)
Ell*_*sch 10
因为它select是一个String变量,所以它不能用作数组中的索引.
select = items[select];
Run Code Online (Sandbox Code Playgroud)
我相信你的意思是使用索引值i在for环(其中i是0到items.length).就像是
select = items[i];
Run Code Online (Sandbox Code Playgroud)
但是,根据您的评论,我相信您真的很想要
int select = scan.nextInt();
System.out.println("You selected: " + items[select]);
Run Code Online (Sandbox Code Playgroud)
根据您的编辑,您可以使用两个数组和两个循环.就像是,
String items[] = { "Table", "Desk", "Chair", "Couch", "Lazyboy" };
int price[] = { 250, 175, 125, 345, 850 };
Scanner scan = new Scanner(System.in);
int pos = -1;
outer: while (pos == -1) {
System.out.println("Please enter an item to view it's price: ");
String select = scan.nextLine();
for (int i = 0; i < items.length; i++) {
if (items[i].equalsIgnoreCase(select.trim())) {
pos = i;
break outer;
}
}
}
if (pos != -1) {
System.out.printf("The price is %d%n", price[pos]);
}
Run Code Online (Sandbox Code Playgroud)
但是Map(在我看来)是一个更好的解决方案(它肯定更有效).喜欢,
String[] items = { "Table", "Desk", "Chair", "Couch", "Lazyboy" };
int[] price = { 250, 175, 125, 345, 850 };
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i < items.length; i++) {
map.put(items[i], price[i]);
}
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter an item to view it's price: ");
while (scanner.hasNextLine()) {
String item = scanner.nextLine().trim();
if (map.containsKey(item)) {
System.out.printf("The price is %d%n", map.get(item));
}
System.out.println("Please enter an item to view it's price: ");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
261 次 |
| 最近记录: |