Jump to content

Having a problem with a Java program

cubercaleb
Go to solution Solved by fizzlesticks,

At the top of the for loop set again to true.

I was writing a program fro my CS class when I ran into a problem. The requirements don't ask me to do all this extra stuff since it's an early lab in Java, however I always like to go above and beyond so I decided to add some extras which we haven't discussed in class, but I have done research on as I needed. I got a program that works, except after the program passes the else statement and loops back it skips over the while statement which prompts the user for a value, this causes the program to go into an infinite loop which I do not want. A similar thing happened with my while statement but I was able to fix that, not sure about this one.

/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */package revtimeconverter;import java.util.*;/** * * @author me */public class RevTimeConverter {    /**     * @param args the command line arguments     */    public static void main(String[] args) {        // TODO code application logic here                int totalseconds, secondsrmdr1, secondsrmdr2, hours, minutes;        String hourstring, minstring, secstring;        Boolean again = true;        Scanner scan = new Scanner(System.in);        totalseconds = 0;                for ( ; ; ) {            while(again) {                try {                    System.out.print("Type the amount of seconds (0 to exit): ");                    totalseconds = scan.nextInt();                    again = false;                }                catch (InputMismatchException e) {                    System.out.println("Invalid input, please type an int.");                    scan.next();                }            }            if (totalseconds == 0) {                System.exit(0);            }            else {                hours = totalseconds / 3600;                secondsrmdr1 = totalseconds - (hours * 360);                minutes = secondsrmdr1 / 60;                secondsrmdr2 = secondsrmdr1 - (minutes * 60);                if (hours == 1)                     hourstring = " hour, ";                else                     hourstring = " hours, ";                if (minutes == 1)                    minstring = " minute, ";                else                    minstring = " minutes, ";                if (secondsrmdr2 == 1)                    secstring = " second.";                else                    secstring = " seconds.";                System.out.println("The total amount of time is: " +                hours + hourstring +                minutes + minstring +                secondsrmdr2 + secstring);                System.out.println("");            }        }    }    }
Link to comment
Share on other sites

Link to post
Share on other sites

Yeah, what fizzle said.

 

Basically, the for loop can't see the assigment of true (not in scope) for your boolean variable, so declare it at the start of the for loop.

 

Also, is there a reason why you wrapped the boolean variable? Normally it's declared as boolean, and not Boolean (notice the capital 'B').

"The only person you are destined to become is the person you decide to be."


CPU: Intel i5 4690K - Motherboard: Asus Maximus VII Ranger - RAM: Corsair Vengeance LP - 2x4GB @ 1866Mhz - GPU: MSI Twin Frozr GTX 770 4GB - CPU Cooler: Be Quiet! Dark Rock Pro 3 CPU Cooler - PSU: EVGA SuperNova G2 750W - Storage: Seagate Barracuda 2TB HDD- Case: Fractal Design Define R4 Windowed (with Red AKASA Led Strips) - Display: Benq GL2460HM 24" Monitor

Link to comment
Share on other sites

Link to post
Share on other sites


import java.util.*;

 

 

/**

 *

 * @author me

 */

public class RevTimeConverter {

    private static Scanner scanner = new Scanner(System.in);

 

    /**

     * @param args the command line arguments

     */

    public static void main(String[] args) {

        while (true) {

            int totalSeconds = promptUserInt("Type the amount of seconds (0 to exit): ");

 

            if (totalSeconds == 0) {

                break;

            } else {

                int hours = totalSeconds / 3600;

                totalSeconds = totalSeconds % 3600;                

                int minutes = totalSeconds / 60;

                int seconds = totalSeconds % 60;

                

                String hourDelimiter = hours == 1 ? " hour, " : " hours, ";

                String minuteDelimiter = minutes == 1 ? " minute, " : " minutes, ";

                String secondDelimiter = seconds == 1 ? " second." : " seconds.";

 

                System.out.println("The total amount of time is: " +

                        hours + hourDelimiter +

                        minutes + minuteDelimiter +

                        seconds + secondDelimiter + "\n");

            }

        }

    }

 

    private static int promptUserInt(String prompt) {

        while (true) {

            try {

                System.out.print(prompt);

                return scanner.nextInt();

            } catch (InputMismatchException e) {

                System.out.println("Invalid input, please type an integer.");

            }

        }

    }

}

Link to comment
Share on other sites

Link to post
Share on other sites

Yeah, what fizzle said.

 

Basically, the for loop can't see the assigment of true (not in scope) for your boolean variable, so declare it at the start of the for loop.

 

Also, is there a reason why you wrapped the boolean variable? Normally it's declared as boolean, and not Boolean (notice the capital 'B').

 

Didn't notice that, I changed it to boolean.

Link to comment
Share on other sites

Link to post
Share on other sites

import java.util.*;  /** * * @author me */public class RevTimeConverter {    private static Scanner scanner = new Scanner(System.in);     /**     * @param args the command line arguments     */    public static void main(String[] args) {        while (true) {            int totalSeconds = promptUserInt("Type the amount of seconds (0 to exit): ");             if (totalSeconds == 0) {                break;            } else {                int hours = totalSeconds / 3600;                totalSeconds = totalSeconds % 3600;                                int minutes = totalSeconds / 60;                int seconds = totalSeconds % 60;                                String hourDelimiter = hours == 1 ? " hour, " : " hours, ";                String minuteDelimiter = minutes == 1 ? " minute, " : " minutes, ";                String secondDelimiter = seconds == 1 ? " second." : " seconds.";                 System.out.println("The total amount of time is: " +                        hours + hourDelimiter +                        minutes + minuteDelimiter +                        seconds + secondDelimiter + "\n");            }        }    }     private static int promptUserInt(String prompt) {        while (true) {            try {                System.out.print(prompt);                return scanner.nextInt();            } catch (InputMismatchException e) {                System.out.println("Invalid input, please type an integer.");            }        }    }}

Well that's a bit more efficient, haha. I haven't used delimiters yet, also why separate the user prompt?

Link to comment
Share on other sites

Link to post
Share on other sites

Well that's a bit more efficient, haha. I haven't used delimiters yet, also why separate the user prompt?

 

separate idea, separate method 

Link to comment
Share on other sites

Link to post
Share on other sites

separate idea, separate method 

I see, does the break part of the code set the boolean value to false?

Link to comment
Share on other sites

Link to post
Share on other sites

I see, does the break part of the code set the boolean value to false?

 

break while break out of the while loop so you no longer need the boolean

 

also the return breaks the while loop in the prompt so the boolean is not needed

Link to comment
Share on other sites

Link to post
Share on other sites

break while break out of the while loop so you no longer need the boolean

 

also the return breaks the while loop in the prompt so the boolean is not needed

 

Ok, also with the prompt userint method how do you prevent a infinite loop?

Link to comment
Share on other sites

Link to post
Share on other sites

Ok, also with the prompt userint method how do you prevent a infinite loop?

 

if the user input is an integer then the integer is returned from the method which will cause the flow to leave the loop.  If it is not an integer then an exception is throw and caught so the error message shows and it goes back to the prompt

Link to comment
Share on other sites

Link to post
Share on other sites

if the user input is an integer then the integer is returned from the method which will cause the flow to leave the loop.  If it is not an integer then an exception is throw and caught so the error message shows and it goes back to the prompt

Like you would expect, but it just loops on the "Invalid input, please type an integer" when that happnes without the scan.next(); afterwards

Link to comment
Share on other sites

Link to post
Share on other sites

    private static int promptUserInt(String prompt) {

        while (true) {

            try {

                System.out.print(prompt);

                return scanner.nextInt();

            } catch (InputMismatchException e) {

                System.out.println("Invalid input, please type an integer.");

            } finally {

                scanner.nextLine();

            }

        }

    }

sorry it probably just needs to clear the buffer
Link to comment
Share on other sites

Link to post
Share on other sites

   -snip-
sorry it probably just needs to clear the buffer

 

Thanks, If I wanted to prompt the user with a question which they would type yes or no how could I do that? It would need to detect Yes or No (any other combo or upper and lower case) as valid answers, and throw and error with anything else, then use those answer to do separate functions

    private static String userprompt2(String prompt) {        while(true) {            try {                System.out.print(prompt);                return scan.next();            }            catch (InputMismatchException e) {                System.out.println("Invalid input, please type a string");            }            finally {                    scan.next();             }        }    }
Link to comment
Share on other sites

Link to post
Share on other sites

Thanks, If I wanted to prompt the user with a question which they would type yes or no how could I do that? It would need to detect Yes or No (any other combo or upper and lower case) as valid answers, and throw and error with anything else, then use those answer to do separate functions

    private static String userprompt2(String prompt) {        while(true) {            try {                System.out.print(prompt);                return scan.next();            }            catch (InputMismatchException e) {                System.out.println("Invalid input, please type a string");            }            finally {                    scan.next();             }        }    }

    private static String promptUserYesNo(String prompt) {        while (true) {            System.out.print(prompt);            String line = scanner.nextLine();            if ("Yes".equalsIgnoreCase(line) || "No".equalsIgnoreCase(line)) {                return line;            }            System.out.println("Invalid input, valid inputs are Yes or No.");        }    }
Link to comment
Share on other sites

Link to post
Share on other sites

    private static String promptUserYesNo(String prompt) {        while (true) {            System.out.print(prompt);            String line = scanner.nextLine();            if ("Yes".equalsIgnoreCase(line) || "No".equalsIgnoreCase(line)) {                return line;            }            System.out.println("Invalid input, valid inputs are Yes or No.");        }    }

Why don't you need try and catch blocks to do this?

Link to comment
Share on other sites

Link to post
Share on other sites

Why don't you need try and catch blocks to do this?

Since we are reading a string now there really isn't any input mismatch problems (numbers can easily be represented as strings). Also Scanner.nextLine doesn't throw that exception

Link to comment
Share on other sites

Link to post
Share on other sites

Since we are reading a string now there really isn't any input mismatch problems (numbers can easily be represented as strings). Also Scanner.nextLine doesn't throw that exception

Funny, when I try something like

if (line == "no")     System.exit(0);

if will say it can't find the symbol for line.

Link to comment
Share on other sites

Link to post
Share on other sites

Funny, when I try something like

if (line == "no")     System.exit(0);
if will say it can't find the symbol for line.

you can only refer to line within the while loop in the prompt method. That's where its in scope

Link to comment
Share on other sites

Link to post
Share on other sites

you can only refer to line within the while loop in the prompt method. That's where its in scope

Ok, but then how do I use the value of line to determine an outcome?

Shouldn't a return statement return the value of line so that its usable elsewhere?

Also, when I try running that code it prints the following

Would you like to make another calculation?(Yes/No) Invalid input, valid inputs are yes or noWould you like to make another calculation?(Yes/No)
Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×