Having trouble with implementing a system that detects if an input is a integer or not

spong120 :

I'm trying to make a system that asks the user how many times they want a phrase to be repeated and then it checks if the answer is an integer or a string. The program works well when I don't try to implement this system and leave it just at asking the phrase and how many times it should be repeated but it falls appart when I try to check if the amount of times is an integer or not.

import java.util.*;

public class Phrase {
    public static Scanner phraseScan = new Scanner (System.in);
    public static Scanner amountScan = new Scanner (System.in);
    public static void main (String[] args ) {

        System.out.println("What phrase do you want repeated?");
        String phrase = phraseScan.nextLine();
        int phraseLoops = 0;

        System.out.println("How many " + phrase + "s" + " do you want?");
        int desiredPhraseLoops = amountScan.nextInt();

        for (;;) {
            if (!amountScan.hasNextInt()) {
                System.out.println("Integers only please");
                amountScan.next();

            }
            desiredPhraseLoops = amountScan.nextInt();
            if (desiredPhraseLoops >= 0) {
                System.out.println("Valid amount!");
                continue;
            } else {
                break;

            }
        }



        System.out.println(desiredPhraseLoops + " " + phrase + "s coming your way!");

        do {
            System.out.println(phrase);
            phraseLoops++;

        } while (phraseLoops != desiredPhraseLoops);

        System.out.println("You printed " + phraseLoops + " " + phrase + "s" );
    }
}

What I've tried:

try {
          desiredPhraseLoops = amountScan.nextInt();

        } catch (InputMismatchException exception) {
            System.out.println("This is not an integer.");
        } 

          if (!amountScan.hasNextInt()) {
            System.out.println("Good.");
        } else {
            System.out.println("Enter an Integer please.");
        } 

Any time I tried anything, it would ask which phrase I wanted and how many times I wanted it repeated. And then the program just stopped afterward, no matter if I put in an integer or a string, it just didnt give me any other prompts.

The output is this:

What phrase do you want repeated? Test How many Tests do you want? 3

And that's it.

DevilsHnd :

To begin with, just use one Scanner object. You don't need more than that for keyboard input.

If you like, you can just stick with the Scanner#nextLine() method, for example:

Scanner userInput = new Scanner(System.in); 

String phrase = "";
while (phrase.equals("")) {
    System.out.println("What phrase do you want repeated?");
    phrase = userInput.nextLine();
    // VALIDATION: 
    // Was anything other than a empty string (spaces) 
    // or longer than 2 characters supplied?
    if (phrase.trim().equals("") || phrase.length() < 3) {
        // Nope!
        System.err.println("Invalid Input!. Enter a proper phrase!");
        phrase = "";
    }
    // Yes, allow the prompt loop to exit.
}

String phraseLoopsNumber = "";
while (phraseLoopsNumber.equals("")) {
    System.out.println("How many " + phrase + "s" + " do you want?");
    phraseLoopsNumber = userInput.nextLine();
    // VALIDATION: 
    // Did the User supply a string representation of an integer value? 
    if (!phraseLoopsNumber.matches("\\d+")) {
        // Nope!
        System.out.println("Invalid Input (" + phraseLoopsNumber + ")! An integer value is expected!");
        phraseLoopsNumber = "";
    }
    // Yes he/she/it did...Allow prompt loop to exit.
}

int numberOfLoops = Integer.parseInt(phraseLoopsNumber);

// Do what you have to do with the desired number of loops contained
// within the numberOfLoops integer variable.

In the above code, the String#matches() method was used along with a small Regular Expression (RegEx). The "\\d" expression passed to the matches() method checks to see if the string it is working against contains all (1 or more) digits.

If however you're hell bent on using the Scanner#nextInt() method then you can do it this way:

int numberOfLoops = -1;
while (numberOfLoops == -1) {
    System.out.println("How many " + phrase + "'s" + " do you want?");
    // Trap any input errors against the Scanner.nextInt() method... 
    // This would be a form of validation.
    try {
        numberOfLoops = userInput.nextInt();
        // Consume the newline from ENTER key in case a nextLine() prompt is next.
        userInput.nextLine(); 
    } catch (Exception ex) {
        System.out.println("Invalid Input! An integer value is expected!");
        // Consume the newline from ENTER key in case a nextLine() prompt is next.
        // The first one above would of been skipped past if nextInt() threw an exception.
        userInput.nextLine(); 
        numberOfLoops = -1;
        continue;  // continue loop so as to re-prompt
    }
    // Further Validation: 
    // Did the User supply a number greater than 0? 
    if (numberOfLoops < 1 ) {
        // Nope!
        System.out.println("Invalid Input (" + numberOfLoops + ")! A value 1 or greater is expected!");
        numberOfLoops = -1; 
    }
    // Yes he/she did...Allow prompt loop to exit.
}
// Do what you have to do with the desired number of loops contained
// within the numberOfLoops integer variable. 

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Having trouble implementing JsonObjectRequest

Having trouble implementing a readlink() function

Having trouble with implementing a timer in Kivy

Having Trouble Implementing Column Subquery

having trouble implementing the right word to a url link

Having trouble implementing my first Decorator pattern

Having trouble requesting input in python

Having trouble retrieving integer from .properties

Having trouble turning mbpfan into a system service

Having trouble creating an App Script email system

I'm having trouble changing the value in input

Having trouble converting user input into a graphic bar

having trouble with user-input addition

Having trouble using user input between functions

Having trouble implementing ACTION_OPEN_DOCUMENT to my project

Xamarin. Having trouble correctly implementing AudioManager AudioFocus activity and listeners

Having trouble implementing promises with setTimeout and running them in parallel

Having trouble implementing a copy constructor for a doubly linked list

c++ Having trouble implementing templated nested class

I am having trouble implementing a mouse action listener in my GUI

Having trouble implementing Braintree payment for Android using Firebase as backend

I am having trouble implementing a "while" loop in Java

Buffer to integer. Having trouble understanding this line of code

easyocr detects no integer values

Having Trouble building a distributed calculator system with C sharp

Having trouble mocking System.getenv calls in junit

Having trouble creating a Like system for comments in a Laravel Project

Having trouble with a Javascript adding system (simple but I'm slow)

Having trouble with jquery dynamic input and regex matching. Partially works