[英]How to take user input multiple times and store it in the same array list?
[英]Take input from user between 1-10 five times and store them in an array, if wrong input given then prompt for correct input
我循環了五次並使用 util.Scanner 獲取用戶輸入,我被困在必須提示用戶正確輸入的部分,以及何時給出正確的輸入並將其存儲在數組中。 然后循環繼續。
while(a<5){
Scanner input = new Scanner(System.in);
System.out.println("Please enter the value: ");
int x = input.nextInt();
//what code should be added here to prompt user if input is not in 1-10
//and after checking only, the value should be stored in the array
userInputs[a] = x;
a++;
}
你可以試試:
import java.util.Arrays;
import java.util.Scanner;
public class TakeInput {
public static void main(String[] args)
{
Scanner input= new Scanner(System.in);
System.out.println("Enter Five Numbers Between 1 and 10");
double number;
//set length of array which stores the user input
double [] arr= new double[5];
for(int i=0; i<5; i++)
{
System.out.println("Enter Input "+i);
//accept input from users
number=input.nextDouble();
TakeInput ti= new TakeInput();
//prompts to renter value if value is not valid
if(ti.validate_input(number)==true)
{
arr[i]=number;
}
else
{
System.out.println("Enter Number "+i+" Again");
number=input.nextDouble();
}
}
System.out.println("Array List: "+Arrays.toString(arr));
}
//validate user input, ensure that input is not out of range
public boolean validate_input(double input)
{
boolean response;
if(input<=1 || input >=10)
{
response=false;
}
else
{
response=true;
}
return response;
}
}
首先,詢問用戶輸入,並基於此循環並使用掃描儀獲取輸入。
Scanner input= new Scanner(System.in);
System.out.println("Enter Five Numbers");
循環部分:
int num;
int [] arr= new int[5];
for(int i=0; i<arr.length(); i++)
{
System.out.println("Enter Input "+i);
number=input.nextInt();
TakeInput ti= new TakeInput();
if(ti.validate_input(number)==true) arr[i]=number;
else{
System.out.println("Enter Number "+i+" Again");
number=input.nextInt();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.