简体   繁体   English

从用户输入 1-10 次 5 次并将它们存储在一个数组中,如果输入错误,则提示输入正确

[英]Take input from user between 1-10 five times and store them in an array, if wrong input given then prompt for correct input

I am looping five times and taking user inputs using util.Scanner, I am stuck with the part where I have to prompt user for correct input, and when the correct input is given and is to be stored in the array.我循环了五次并使用 util.Scanner 获取用户输入,我被困在必须提示用户正确输入的部分,以及何时给出正确的输入并将其存储在数组中。 Then the loop continues.然后循环继续。

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++;
    }

You can try:你可以试试:

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;
    }
}

First, ask the user for an input and based on that you loop and take input using scanner.首先,询问用户输入,并基于此循环并使用扫描仪获取输入。

Scanner input= new Scanner(System.in);
System.out.println("Enter Five Numbers");

The looping part:循环部分:

    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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM