gpt4 book ai didi

java - 很难找到该范围是否为空,以便我继续编写代码。 java

转载 作者:行者123 更新时间:2023-12-02 09:17:41 24 4
gpt4 key购买 nike

    int[] intRange1 = {};
intNum = getValidInt(sIn, "Please enter a whole number: ",
"Invalid response. Only whole numbers are acceptable.", intRange1);
System.out.println("The whole number your entered was: " + intNum);
System.out.println("Now we will test your whole number in a math equation...");
System.out.printf("Adding 10 to your whole number would be: 10 + %d = %d.\n\n", intNum, (intNum + 10));

// Get an integer within a range from the user
int[] intRange2 = { 10, 50 };
intNum = getValidInt(sIn, "Please enter a whole number between 10 and 50: ",
"Invalid response. Only whole numbers between 10 and 50 are acceptable.", intRange2);
System.out.println("The whole number your entered was: " + intNum);
System.out.println("Now we will test your whole number in a math equation...");
System.out.printf("Adding 10 to your whole number would be: 10 + %d = %d.\n\n", intNum, (intNum + 10));
}
/*
* making the method I can get it to validate the first part but I can not get
* it to do the part with the range
*/

public static int getValidInt(Scanner sIn, String question, String warning, int[] range) {
boolean valid = false;
int validNumber = 0;

do {
System.out.println("Please enter a whole number: ");
String number = sIn.nextLine();

try {
validNumber = Integer.parseInt(number);
valid = true;
} catch (NumberFormatException e) {

System.out.println("Invalid response. Only whole numbers are acceptable.");
valid = false;

} // end of try/catch block
} while (!valid);// end of do while
}

最佳答案

为什么不直接做

    int v = SIn.nextInt();

然后如果它不是整数则捕获异常。请尝试以下操作:

    Scanner sIn = new Scanner(System.in);


int r = getValue(sIn, 10, 40);

System.out.println("You entered " + r);

static int getValue(Scanner sIn, int low, int high) {
String msg = "Please enter a number between %d and %d%n";
while (true) {
System.out.printf(msg, low, high);
System.out.print("Enter: ");
try {
int v = sIn.nextInt();
if (v >= low && v <= high) {
sIn.nextLine();//clear input buffer
return v;
}
System.out.printf("Number out of range (%d).", v);
}
catch (InputMismatchException e) {
System.out.printf("Illegal input type (%s)%n", sIn.nextLine());
}
}
}



关于java - 很难找到该范围是否为空,以便我继续编写代码。 java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58884220/

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