我正在處理一個問題,其中有一個菜單選項1.要混洗單詞,2要洗牌單詞並嘗試通過更改數組索引號來修復它。在java中的單獨if語句中使用相同的值
我做了這部分if (input==1)
洗牌的話。
我現在必須在if (input==2)
部分採用相同的洗牌字,並嘗試修復它。任何人都可以指導我如何在這個塊if(input==1)
中使用相同的值?
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class Project2 {
public static void main(String[] args) {
while (true) {
System.out.println("Select an item from below: \n");
System.out.println("(1) Mix");
System.out.println("(2) Solve");
System.out.println("(3) Quit");
int input;
Scanner scan = new Scanner(System.in);
input = scan.nextInt();
String team;
String mix_word;
char orig_team[];
char mix_team[];
boolean Result;
// System.out.println(input);
if (input == 1) {
team = orig();
System.out.println(team);
mix_word = mix(team);
System.out.println(mix_word);
orig_team = team.toCharArray();
mix_team = mix_word.toCharArray();
int arg_length = mix_team.length;
}
if (input == 2) {
}
if (input == 3) {
break;
}
if (input > 3 || input <= 0) {
System.out.println("input accurate numbers 1 or 2 or 3");
}
}
}
static String mix(String Team) {
String word = shuffle(Team);
return word;
}
static String shuffle(String input) {
List<Character> characters = new ArrayList<Character>();
for (char c : input.toCharArray()) {
characters.add(c);
}
StringBuilder output = new StringBuilder(input.length());
while (characters.size() != 0) {
int randPicker = (int) (Math.random() * characters.size());
output.append(characters.remove(randPicker));
}
return output.toString();
}
static String orig()
{
String[] lines = new String[1000];// Enough lines.
int counter = 0;
try {
File file = new File("input.txt");// The path of the File
FileReader fileReader1 = new FileReader(file);
BufferedReader buffer = new BufferedReader(fileReader1);
boolean flag = true;
while (true) {
try {
lines[counter] = buffer.readLine();// Store a line in the
// array.
if (lines[counter] == null) {// If there isn't any more
// lines.
buffer.close();
fileReader1.close();
break;// Stop reading and close the readers.
}
counter++;
} catch (Exception ex) {
break;
}
}
} catch (FileNotFoundException ex) {
System.out.println("File not found.");
} catch (IOException ex) {
System.out.println("Exception ocurred.");
}
int pick;
Random rand = new Random();
pick = rand.nextInt(counter) + 0;
return (lines[pick]);
}
}
我建議你使用'switch'語句 – 2013-03-09 22:05:02
@Peter Lawrey,我正在使用switch語句,仍然有問題。我在兩個塊中獲得了相同變量的不同值。它需要是一樣的。 – user1471980 2013-03-09 22:49:52
我的猜測是你沒有在case語句之間放置'break'。如果你忘記這樣做,它將從一個案件運行到另一個案件。 – 2013-03-09 23:14:35