gpt4 book ai didi

java接受用户输入5个整数

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:32:05 25 4
gpt4 key购买 nike

嗨,我们如何在 java 中限制特定用户输入的整数数量?下面是我接受用户输入的代码,我如何确保只接受用户输入的 5 个整数?谢谢

public static void main(String args[]) 
{
int a;
Scanner in = new Scanner(System.in);

System.out.println("Enter a string");
a = in.nextInt();
System.out.println("You entered integer "+a);

}

最佳答案

public static void main(String args[]) 
{
int a[] = new int[5];
int i = 0;
Scanner in = new Scanner(System.in);
while(i<5)
{
System.out.println("Enter an integer");
a[i] = in.nextInt();
i++;
System.out.println("You entered integer "+a[i-1]);
}

}

a[i] 介于 1 和 100 之间

public static void main(String args[]) 
{
int a[] = new int[5];
int i = 0;
Scanner in = new Scanner(System.in);
while(i<5)
{
System.out.println("Enter an integer between 1 and 100");
a[i] = in.nextInt();
if(a[i]>=1 && a[i]<=100)
{
i++;
System.out.println("You entered integer "+a[i-1]);
}
}

}

关于java接受用户输入5个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13283913/

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