有没有办法使用扫描仪获得用户输入的自定义输出?
例如:
"files.associations": {
"*": "shellscript"
},
所以当我执行它时,这是输出
import java.util.Scanner;
public class test {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Choose one of the fruits:\n"+
"1)Mango\n"+
"2)Apple\n"+
"3)Melon\n"+
"4)Papaya\n");
String fruit = input.next();
if (fruit.equals("1") || fruit.equals("Mango")) {
}
}
}
然后退出......
我想要的是
Choose one of the fruits:
1)Mango
2)Apple
3)Melon
4)Papaya
1
按下1它应该打印芒果选择...好吧我可以为此添加println但我也想不显示1或芒果(无论用户输入什么)而不是我想显示我的自定义消息..
怎么做?
答案 0 :(得分:2)
您可以将它们添加到地图中,然后通过键
获取它们 import java.util.Scanner;
public class test {
public static void main(String args[]){
Map<Integer, String> selection = Maps.newHashMap();
selection.put(1, "Mango");
selection.put(2, "Apple");
selection.put(3, "Melon");
selection.put(4, "Papaya");
Scanner input = new Scanner(System.in);
System.out.println("Choose one of the fruits:\n"+
"1)Mango\n"+
"2)Apple\n"+
"3)Melon\n"+
"4)Papaya\n");
int fruit = input.nextInt();
System.out.println("you selected " + selection.get(fruit));
}
}
如果您不想通过控制台输入选择,那么您可以使用对话框
Map<Integer, String> selection = Maps.newHashMap();
selection.put(1, "Mango");
selection.put(2, "Apple");
selection.put(3, "Melon");
selection.put(4, "Papaya");
System.out.println("Choose one of the fruits:\n"+
"1)Mango\n"+
"2)Apple\n"+
"3)Melon\n"+
"4)Papaya\n");
int mySelection = Integer.valueOf(JOptionPane.showInputDialog("Enter
your selection here"));
System.out.println("you selected " + selection.get(mySelection));
答案 1 :(得分:1)
我将你的水果存储在一个数组中,并根据用户从所述数组输入的内容打印该选项。
String[] list = new String[]{"Mango", "Apple", "Melon", "Papaya"};
首先将它们打印到控制台:
System.out.println(Arrays.toString(list));
然后只需打印用户选项:
System.out.println("Choose a fruit:");
int fruit = input.nextInt();
System.out.println(list[fruit - 1] + " selected.");