gpt4 book ai didi

java - 用户输入的数字不重复

转载 作者:行者123 更新时间:2023-12-02 08:54:22 25 4
gpt4 key购买 nike

通过这个彩票程序,我试图确保数字在 1-59 的范围内,相同的数字不能输入两次,并且只能输入数字。我唯一需要帮助的代码是唯一可以输入数字的部分。


public void choose() {
System.out.println("\n");
int temp;
boolean valid;

for (int i = 0; i < 6; i++) {
do {
valid = true;
System.out.print("Enter in an integer from 1 to 59: ");
temp = keyboard.nextInt();
if (temp < 1 || temp > 59) {
System.out.println("Error, please enter a valid integer !!");
valid = false;
}
for (int j = 0; j < i; j++) {
if (numbers[j] == temp) {
System.out.println("Please enter a different number as you have already entered this !!");
valid = false;
break;
}
}
numbers[i] = temp;
} while (!valid);
}
}

最佳答案

按如下方式进行:

import java.util.Arrays;
import java.util.Scanner;

public class Main {
static int[] numbers = new int[6];
static Scanner keyboard = new Scanner(System.in);

public static void main(String args[]) {
// Test
choose();
System.out.println(Arrays.toString(numbers));
}

static void choose() {
int temp = 0;
boolean valid;
for (int i = 0; i < 6; i++) {
// Check if the integer is in the range of 1 to 59
do {
valid = true;
System.out.print("Enter in an integer (from 1 to 59): ");
try {
temp = Integer.parseInt(keyboard.nextLine());
if (temp < 1 || temp > 59) {
System.out.println("Error: Invalid integer.");
valid = false;
}
} catch (NumberFormatException e) {
System.out.println("Error: The input is not an integer.");
valid = false;
}
for (int j = 0; j < i; j++) {
if (numbers[j] == temp) {
System.out.println("Please enter a different number as you have already entered this");
valid = false;
break;
}
}
numbers[i] = temp;
} while (!valid); // Loop back if the integer is not in the range of 1 to 100
}
}
}

示例运行:

Enter in an integer (from 1 to 59): a
Error: The input is not an integer.
Enter in an integer (from 1 to 59): 12.23
Error: The input is not an integer.
Enter in an integer (from 1 to 59): 10
Enter in an integer (from 1 to 59): 200
Error: Invalid integer.
Enter in an integer (from 1 to 59): 20
Enter in an integer (from 1 to 59): 5
Enter in an integer (from 1 to 59): 10
Please enter a different number as you have already entered this
Enter in an integer (from 1 to 59): 20
Please enter a different number as you have already entered this
Enter in an integer (from 1 to 59): 6
Enter in an integer (from 1 to 59): 7
Enter in an integer (from 1 to 59): 12
[10, 20, 5, 6, 7, 12]

关于java - 用户输入的数字不重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60578282/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com