簡體   English   中英

使用掃描程序在java中自定義輸出用戶輸入

[英]Custom output of user input in java using scanner

有沒有辦法使用掃描儀獲得用戶輸入的自定義輸出?

例如:

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它應該打印芒果選擇...好吧我可以為此添加println但我也想不顯示1或芒果(無論用戶輸入)而不是我想顯示我的自定義消息..

怎么做?

您可以將它們添加到地圖中,然后通過鍵獲取它們

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

我將你的水果存儲在一個數組中,並根據用戶從所述數組輸入的內容打印選項。

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

在線嘗試!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM