有人可以帮我吗?我需要的只是帮助。我尝试使用while循环,这似乎不起作用。基本上,为了更清楚,我需要让用户输入int 0 - 9的值.2 if语句查找负数和outofbound数。我想要的是重复代码,直到输入正确的输入。如果用户输入是char。enter code here
public static void doUserMove(Scanner console, char[][] board)
{
do
{
System.out.print("Which row from 0-9 do you want to place your character: ");
int row = console.nextInt();
if(row >= SIZE)
{
System.out.print("Your row is OUT-OF-BOUND! Please enter a number from 0 to 9: ");
System.out.println();
}
else if(row < 0)
{
System.out.print("Your row is NEGATIVE! Please enter NON-NEGATIVE number from 0 to 9: ");
System.out.println();
}
System.out.print("Which column from 0-9 do you want to place your character: ");
int column = console.nextInt();
if(column >= SIZE)
{
System.out.println("Your column is OUT-OF-BOUND! Please enter a number from 0 to 9");
System.out.println();
}
else if(column < 0)
{
System.out.println("Your column is NEGATIVE! Please enter NON-NEGATIVE number from 0 to 9!");
System.out.println();
}
else if(board[row][column] != ' ')
{
System.out.println("FCFS: First Come For Serve! Please enter another position.");
System.out.println();
}
else
{
board[row][column] = 'U';
return;
}
}
while(true);
}
答案 0 :(得分:-1)
使用while循环是正确的方法,只需尝试这样(每个变量一个循环):
int row;
do {
System.out.printline("please input number");
row = console.nextInt();
} while(row > size || row < 0)
这样,它一直询问直到行在允许的范围内。 或者,您可以首先询问不同的文本,然后运行while循环,说输入无效(这样用户就知道他做错了)
答案 1 :(得分:-1)
您可以尝试这样的事情:
public static void main(String[] args) {
do {
System.out.print("Which row from 0-9 do you want to place your character: ");
int row = getValue(new Condition(MIN, MAX));
System.out.print("Which column from 0-9 do you want to place your character: ");
int column = getValue(new Condition(MIN, MAX));
} while (true);
}
private static int getValue(Condition condition) {
Scanner scanner = new Scanner(System.in);
int value;
do {
value = scanner.nextInt();
if (value < condition.min || value > condition.max) {
System.out.println("Your enter is OUT-OF-RANGE! Please enter a number from "+condition.min+" to "+condition.max+": ");
}
} while (value < condition.min || value > condition.max);
return value;
}
class Condition {
int min;
int max;
public Condition(int min, int max) {
this.max = max;
this.min = min;
}
}
答案 2 :(得分:-2)
Try-catch也应该有用!
public static void doUserMove(Scanner console, char[][] board) {
System.out.print("Which row from 0-9 do you want to place your character: ");
int row = console.nextInt();
System.out.print("Which column from 0-9 do you want to place your character: ");
int column = console.nextInt();
try {
if(board[row][column] != ' ') {
System.out.println("FCFS: First Come For Serve! Please enter another position.");
} else {
board[row][column] = 'U';
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Sorry, your row and/or column is out of bounds! Please try again");
doUserMove(console, board);
}
}
如果此代码不起作用,请告诉我!