Question

How would I code this method in Java using a scanner? Begin by asking how many...

How would I code this method in Java using a scanner?

Begin by asking how many spaces the row should be with a prompt using System.out.print like the following, with 40 as the maximally allowed number of spaces: (user input shown bold)

Please enter the number of spaces for the game (1-40): eight


To do this, use the promptNumberReadLine method that you will write, described on the back page. If the user does not type a number in the correct range, that method will prompt them in this way:

That was not a valid number! Please try again.

Please enter the number of spaces for the game (1-40): 8

public static int promptNumberReadLine(Scanner s, String prompt, int max)

Print the prompt using System.out.print(…). If the next piece of information in the Scanner represents an integer which is at least 1 and at most max, return the number, but make sure the Scanner also reads in the rest of the line before returning. Otherwise (if the next piece of information doesn’t represent the above requirements), read in the rest of the line, print the line
That was not a valid number! Please try again.
and repeat the process described in this box.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

" but make sure the Scanner also reads in the rest of the line before returning" Its not clear what this mean.Can you provide some examples for this. If its to just read the line, I have added a line for that, else provide example, I will implement. Also "eight" is a valid condition or invalid condition ? specify that too.

import java.util.Scanner;

public class ScannerTest
{ public static int promptNumberReadLine(Scanner s, String prompt, int max)
{
    int data = -1;
    String line;
    boolean isExit = false;
    do
    {
            System.out.print(prompt);
            String strData = s.next();
        try
        {
            // Read input from user
            data = Integer.parseInt(strData);
            // Validate input
            if (data > 0 && data <= max)
            {
                // Flag for exitig loop
                isExit = true;
                // read rest of the line
                line = s.nextLine();
            } else
            {
                // message to user
                System.out.println("That was not a valid number! Please try again.");
            }
        }
        catch (NumberFormatException e)
        {
            // message to user
            System.out.println("That was not a valid number! Please try again.");
        }
    } while (!isExit) ;
    // return value
    return data;
}
    public static void main(String [] args)
    {
        Scanner s = new Scanner(System.in);
        String prompt = "Please enter the number of spaces for the game (1-40): ";
        int data = promptNumberReadLine(s,prompt,40);
    }
}

import java.util.Scanner; 2 4 @ 5 public class ScannerTest { public static int promptNumberReadLine(Scanner s, String prompt,catch (NumberFormatException e) 31 // message to user System.out.println(That was not a valid number! Please try again.); 3Please enter the number of spaces for the game (1-40): 56 That was not a valid number! Please try again. Please enter the num

Add a comment
Know the answer?
Add Answer to:
How would I code this method in Java using a scanner? Begin by asking how many...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I have already finished most of this assignment. I just need some help with the canMove...

    I have already finished most of this assignment. I just need some help with the canMove and main methods; pseudocode is also acceptable. Also, the programming language is java. Crickets and Grasshoppers is a simple two player game played on a strip of n spaces. Each space can be empty or have a piece. The first player plays as the cricket pieces and the other plays as grasshoppers and the turns alternate. We’ll represent crickets as C and grasshoppers as...

  • I need to create a code for this prompt: In this project we will build a...

    I need to create a code for this prompt: In this project we will build a generic UserInput class for getting keyboard input from the user. Implementation: The class UserInput is a 'Methods only' class, and all the methods should be declared static. Look at the TestScanner.java program at the bottom of this page that inputs a string, int and double. It shows you how to use Scanner class to get input from the keyboard. Write FOUR simple methods, one...

  • public static void main(String[] args) {         System.out.println("Welcome to the Future Value Calculator\n");         Scanner sc...

    public static void main(String[] args) {         System.out.println("Welcome to the Future Value Calculator\n");         Scanner sc = new Scanner(System.in);         String choice = "y";         while (choice.equalsIgnoreCase("y")) {             // get the input from the user             System.out.println("DATA ENTRY");             double monthlyInvestment = getDoubleWithinRange(sc,                     "Enter monthly investment: ", 0, 1000);             double interestRate = getDoubleWithinRange(sc,                     "Enter yearly interest rate: ", 0, 30);             int years = getIntWithinRange(sc,                     "Enter number of years: ", 0, 100);             System.out.println();            ...

  • Project 7-3 Guessing Game import java.util.Scanner; public class GuessNumberApp {    public static void main(String[] args)...

    Project 7-3 Guessing Game import java.util.Scanner; public class GuessNumberApp {    public static void main(String[] args) { displayWelcomeMessage(); // create the Scanner object Scanner sc = new Scanner(System.in); String choice = "y"; while (choice.equalsIgnoreCase("y")) { // generate the random number and invite user to guess it int number = getRandomNumber(); displayPleaseGuessMessage(); // continue until the user guesses the number int guessNumber = 0; int counter = 1; while (guessNumber != number) { // get a valid int from user guessNumber...

  • How would I try/catch recovery from a format mismatch error? The scanner needs to continue prompting...

    How would I try/catch recovery from a format mismatch error? The scanner needs to continue prompting until the user enters a valid number. I know that I would need to try n = kbd.nextInt(); and catch a InputMismatchException and if n<1 or n>100 then I need to print Out of Range Exception. Must be in 1..100. However, I am unsure how to loop all of that. import java.io.*; import java.util.*; public class Lab5 { public static void main( String args[]...

  • Need code written for a java eclipse program that will follow the skeleton code. Exams and...

    Need code written for a java eclipse program that will follow the skeleton code. Exams and assignments are weighted You will design a Java grade calculator for this assignment. A user should be able to calculate her/his letter grade in COMS/MIS 207 by inputting their scores obtained on worksheets, assignments and exams into the program. A skeleton code named GradeCompute.java containing the main method and stubs for a few other methods, is provided to you. You must not modify/make changes...

  • Step 4: Add code that discards any extra entries at the propmt that asks if you...

    Step 4: Add code that discards any extra entries at the propmt that asks if you want to enter another score. Notes from professor: For Step 4, add a loop that will validate the response for the prompt question:       "Enter another test score? (y/n): " This loop must only accept the single letters of ‘y’ or ‘n’ (upper case is okay). I suggest that you put this loop inside the loop that already determines if the program should collect...

  • You will need to think about problem solving. There are several multi-step activities. Design, compile and...

    You will need to think about problem solving. There are several multi-step activities. Design, compile and run a single Java program, StringEx.java, to accomplish all of the following tasks. Add one part at a time and test before trying the next one. The program can just include a main method, or it is neater to split things into separate methods (all static void, with names like showLength, sentenceType, lastFirst1, lastFirst), and have main call all the ones you have written...

  • Would you please do Pseudocode for this progarm in Java?? Using scanner algorithm, The scanner takes...

    Would you please do Pseudocode for this progarm in Java?? Using scanner algorithm, The scanner takes the name of a text file from the command line and prints out the list of tokens. If there is non-valid token in the input file, print out “error”. please help me to write Pseudocode! thank you!! The scanner takes the name of a text file from the command line. It outputs to the console error if there is any non-valid token in the...

  • Hello Guys. I need help with this its in java In this project you will implement...

    Hello Guys. I need help with this its in java In this project you will implement a Java program that will print several shapes and patterns according to uses input. This program will allow the use to select the type (say, rectangle, triangle, or diamond), the size and the fill character for a shape. All operations will be performed based on the user input which will respond to a dynamic menu that will be presented. Specifically, the menu will guide...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT