简体   繁体   中英

Java - how to reprompt user if two conditions are met

Can anyone help me fix my below code? I'm supposed to create an array/list of 10 doubles and allow the user to type '99999' to quit. I'm also supposed to give the user an error if no doubles are entered, ie if the user types '99999' before any double values.

I know I could just put an "if (doubleList.isEmpty()) at the end of the while loop and just end the program that way, but I want to try and figure out how to keep prompting the user for values if they enter 99999 first.

I tried entering a "if(doubleList.isEmpty())" in the while(true) loop but couldn't get it to work.

The solution I have below somewhat works, but doesn't quite. It

Any suggestions? Thanks!

    import java.util.*;
    public class DistanceTesting
{
public static void main(String[] args)
{
    //Almost works, but not quite. I can't figure out how to reprompt the user if the list is empty
    List<Double> doubleList = new ArrayList<>();
    int count = 0;
    double sum;
    double average;
    double number;
    Scanner input = new Scanner(System.in);
    System.out.println("Enter up to 10 doubles: ");
    number = input.nextDouble();
    if (number == 99999)
    {
        System.out.println("Error: you must enter at least one double.");
    }
    while (true)
    {
        count++;
        System.out.println("Enter a double(or press 99999 to quit): ");
        number = input.nextDouble();
        if (number == 99999)
        {
            break;
        }
        if (count == 10)
        {
            break;
        }
        else
        {
            doubleList.add(number);
        }
    }
    
}
  }

If I understand your question correctly, you will want to put if(doubleList.isEmpty()) inside the if (number == 99999) block, and delete the lines before the while loop and just handle it inside the loop.

    if (number == 99999)
    {
        if(doubleList.isEmpty())
        {
            System.out.println("Error: you must enter at least one double.");
            count--;
            continue;
        }
        else
        {
            break;
        }
    }

What this does is when the user inputs 99999, it then checks if the list is empty. If it is, print the error, subtract count (since they didn't input a double you wanted), and continue starts again from the beginning of the loop, prompting them again

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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