dimanche 12 février 2017

How to validate scanner input using a different method?

Vote count: 0

import java.util.Scanner

public class Editable {

/* Return true if amount is within MIN_AMOUNT and MAX_AMOUNT 
*/
public static boolean isValidAmount(double amount) {
    return amount > MIN_AMOUNT && amount < MAX_AMOUNT;
}

/* Asks user to input amount until isValidAmount is true.
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(system.in);

}

I'm new to Java and I've been struggling with this for quite a bit. I'm asking for user input in main and I need it to keep asking for user input until isValidAmount returns true. I have tried multiple different solutions but can't seem to get it to work.

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    double inputAmount = 0;
    try {
        while (!isValidAmount(inputAmount)) {
            System.out.println("Enter amount:");
            inputAmount = scanner.nextDouble();
            scanner.next();
        }
    } catch (Exception e) {
        System.out.println("Input error.");
        scanner.next();
    }

asked 49 secs ago

Let's block ads! (Why?)



How to validate scanner input using a different method?

Aucun commentaire:

Enregistrer un commentaire