gpt4 book ai didi

java - 使用扫描仪在java中自定义用户输入的输出

转载 作者:行者123 更新时间:2023-11-29 04:23:36 24 4
gpt4 key购买 nike

是否有任何方法可以使用扫描仪获取用户输入的自定义输出?

例如:

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

它退出...

我想要的是

Choose one of the fruits:
1)Mango
2)Apple
3)Melon
4)Papaya

1)Mango Selected

按 1 它应该打印 Mango Selected...好吧我可以为此添加 println 但我也不想显示 1 或 Mango(无论用户输入什么)而是我想显示我的自定义消息..

怎么做?

最佳答案

您可以将它们添加到 map 中,然后通过按键获取它们

 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));

关于java - 使用扫描仪在java中自定义用户输入的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47636029/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com