2017-12-04 11 views
1

スキャナを使用してユーザ入力をカスタム出力する方法はありますか?例についてはスキャナを使用してJavaでユーザ入力をカスタム出力する

:私が欲しいもの

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

1)Mango Selected 
です...私はそれを実行したとき

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やMango(ユーザーが入力したもの)を表示しないようにしたいのですが、私のカスタムメッセージを表示したいのです...

どのようにすればいいですか?

+1

を何もあなたの 'if'の体ではありません –

+0

「1」のキーを押してもらいたいのですか、それともそれが来る前に '1'を押してから' enter'を押しますか?あなたの質問から、あなたはそれがキープレスで起こりたいと思うように聞こえるからです。 –

+0

私が1を押してEnterを押すと、マンゴーが選択され、上に印刷された「1」が削除されます。 –

答えて

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

私は果物を配列に格納し、前記配列からのユーザーの入力に基づいてオプションを出力します。

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

Try it online!

関連する問題