我循环了五次,并使用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++;
}
答案 0 :(得分:1)
首先,向用户询问输入内容,然后您循环并使用扫描仪进行输入。
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();
}
}
答案 1 :(得分:0)
您可以尝试:
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;
}
}