ランダムな単語をテキストファイルから選択してスクランブルし、2つのインデックス位置をスワップして解読できるようにするプログラムを作成しようとしています。時間。テキストファイルからランダムに選択された単語をスクランブルする方法
私は、テキストファイルからランダムな単語を取得し、その上にあるインデックス番号を使って出力するプログラムを持っています。
私は考え出すトラブルを抱えていますどのように:
- それが画面上に出力し、そして前にスクランブル単語をゲットで2つのインデックスをスワッピングをループできるようにするには、ユーザーを取得するにはどのよう
- 単語が解読されるまでの時間。
これらの操作を実行する方法はありますか?
ここまでは私のコードです。
import java.io.*;
import java.util.*;
public class Midterm { // class header
public static void main(String[] args) { // Method header
int option = 0;
Scanner input = new Scanner(System.in);
int scrambled;
int counter = 0;
int index1;
int index2;
String[] words = readArray("words.txt");
/*
* Picks a random word from the array built from words.txt file. Prints
* index with word beneath it.
*/
int randWord = (int) (Math.random() * 11);
for (int j = 0; j < words[randWord].length(); j = j + 1) {
System.out.print(j);
}
System.out.print("\n");
char[] charArray = words[randWord].toCharArray();
for (char c : charArray) {
System.out.print(c);
}
/*
* Prompt the user for input to play game or quit.
*/
System.out.println("\n");
System.out.println("Enter 1 to swap a par of letters.");
System.out.println("Enter 2 to show the solution and quit.");
System.out.println("Enter 3 to quit.");
if (input.hasNextInt()) {
option = input.nextInt();
counter++;
}
else {
option = 3;
}
System.out.println("");
if (option == 1) {
System.out.println("Enter the two index locations to swap separated by a space. ");
index1 = 0;
index2 = 0;
if (input.hasNextInt()) {
index1 = input.nextInt();
}
else {
System.out.println("Please enter only numbers.");
}
if (input.hasNextInt()) {
index2 = input.nextInt();
}
else {
System.out.println("Please enter only numbers.");
}
}
}
// end main
public static String[] readArray(String file) {
// Step 1:
// Count how many lines are in the file
// Step 2:
// Create the array and copy the elements into it
// Step 1:
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine()) {
ctr = ctr + 1;
s1.nextLine();
}
String[] words = new String[ctr];
// Step 2:
Scanner s2 = new Scanner(new File(file));
for (int i = 0; i < ctr; i = i + 1) {
words[i] = s2.next();
}
return words;
} catch (FileNotFoundException e) {
}
return null;
}
}
ありがとうございました! – Ordee
実際、私が遭遇した小さな問題がありました。ユーザーが「2つのインデックスロケーションを入力...」の部分に無効なエントリを入力した場合、コードはエラーを適切に処理していないようです。プログラムは無限ループになるようで、手動で停止する必要があります。私は、Javaでtry/catchメソッドと例外処理プロシージャがあることを知っていますが、まだ読んでいます。 – Ordee
私はそれを得たと思う。 while(!validoption)行を削除し、if/elseループを各インデックスの2つの別々のループに分けました。 index1とindex2にはそれぞれ独自のif/elseループがあります。プログラムをきれいに終了させるようです。プログラムを終了するのではなく、インデックスの場所を尋ねることに戻る方法はありますか? – Ordee