gpt4 book ai didi

java - 无法检查用户输入是否小于某个数字

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

当我输入小于 12 的数字时没有问题,但当我输入更大的数字时,我会得到“输入小于 13 的数字”,并且在后续输入中始终会出现该问题。我怎样才能让程序检查 int 和小于 13 的数字?

package com.company;

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Scanner z = new Scanner(System.in);
boolean cont;
boolean isNumber;

do {
System.out.println("Enter the number you want to see the factorial of (0-12)");
do{
if(s.hasNextInt()){
isNumber = true;
}else{
isNumber=false;
System.out.println("Enter a number");
s.next();
}
}while(!isNumber);
int input = s.nextInt();

boolean isSmall;
do{
if(input < 13){
isSmall= true;

}else{
isSmall=false;
System.out.println("Enter a number less than 13");
s.next();
}
}while(!isSmall);

int factorial = 1;
System.out.print(input + "!" + " = ");
for ( int i =1 ; i<=input ; i++) {
factorial *= i;
System.out.print(i);
if (input == i) {
break;
}

System.out.print(" * ");
}
System.out.println(" = " + factorial);

System.out.println("Do you want to continue?");
String line = z.nextLine();
if(line.matches("y|YES|Y|yes|Yes")){
cont=true;
}else{
cont= false;
System.out.println("Thanks for using the program!");
}
}while(cont);
}
}

最佳答案

您忘记将新值放入输入中,因此您总是比较较大的值 13

do{
if(input < 13){
isSmall= true;
}else{
isSmall=false;
System.out.println("Enter a number less than 13");
input = s.nextInt();
}
}while(!isSmall);

关于java - 无法检查用户输入是否小于某个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45152152/

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