2016-10-21 9 views
0

クロスワードのような単語にマッチする単語を作って、単語や他のパズルゲームとJava Netbeansで一致させたいと思います。私は自分のint =私の配列に格納している言葉を作るのに問題があった。Javaで一致する単語

String word; int numword=0; 
    // Words that will be stores in my arry 
    String [] myNames = {"Pie","Soccer","Chelsea","Gaming","Steam"}; 
    // User inputs the number 
    numword = new Scanner(System.in).nextInt(); 
    // Print the word for testing purposes 
    System.out.println(myNames[numword]); 
    // Type the word 
    word = new Scanner(System.in).nextLine(); 
    // Check if the word is right 
    if (word.equals(n)){ 
     System.out.println("You got it"); 

    }else{ 
     System.out.println("You got it wrong"); 
    } 
+2

は、なぜあなたは、新しいスキャナオブジェクトを毎回作成するのですか? 1つのオブジェクトを作成し、それを使用します。ここで 'n 'とは何ですか?これは 'myNames [numword]'でなければなりません。 – Li357

+1

配列の長さよりも大きな数値を入力するとどうなりますか? –

答えて

0

あなたのコードを少し変更しました。これは、あなたの望むことですか?

String word; 
int numword = 0; 
Scanner scanner = new Scanner(System.in); 
// Words that will be stores in my arry 
String[] myNames = {"Pie", "Soccer", "Chelsea", "Gaming", "Steam"}; 
// User inputs the number 
numword = scanner.nextInt(); 
while (numword >= myNames.length || numword < 0) { 
    System.out.println("Not a valid number, enter value between 0 and " + (myNames.length - 1)); 
    numword = scanner.nextInt(); 
} 
// Print the word for testing purposes 
System.out.println(myNames[numword]); 
// Type the word 
word = scanner.next(); 
// Check if the word is right 
if (word.equals(myNames[numword])) { 
    System.out.println("You got it"); 
} else { 
    System.out.println("You got it wrong"); 
} 
+0

'numword'が-1の場合はどうなりますか? – Li357

+0

@AndrewLiありがとう、私は答えを更新しました。 –

+0

@LahiruAshanありがとう、それは私が欲しかったものです。 –

0

あなたは、ユーザー入力を取得するBufferedReaderのを使用することができます。

import java.util.BufferedReader; 

public class Main { 
    public static void main (String[] args) { 
     BufferedReader br = new BufferedReader (new InputStreamReader (System.in))); 
     String input = br.readLine(); 
    } 
} 
関連する問題