Here is my assignment.
Write a program that prompts the user for a positive integer n and prints “Hello World” n times. Of course, a value of n that is less than or equal to 0 is illegal. To ensure valid input, include a method
int getPos()
that prompts for a positive integer. If the value of that integer is less than or equal to 0, the method should print an appropriate message and request a positive number. When the user supplies a valid number, the method returns that number. (Hint: the break; statement is really handy in this program.)
Below is my code
/** * * CSC 225 - Online * Problem 6 * */ import java.util.*; public class Problem6 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int input; int a; System.out.println( " Hello user! " ); System.out.print( " Please enter the number of ireations you would like Hello World displayed. "); input = scan.nextInt(); getPos(input); System.out.println(input); for(a = 1; a <= input; a++) { System.out.println( " Hello World! "); } } public static int getPos(int input) { Scanner scan = new Scanner(System.in); while (input <= 0) { System.out.println( " Error: Please enter a valid integer greater than 0." ); System.out.print( " Please enter a valid number. " ); input = scan.nextInt(); } return input ; } }
Below is my output
Hello user!
Please enter the number of ireations you would like Hello World displayed. -5
Error: Please enter a valid integer greater than 0.
Please enter a valid number. -5
Error: Please enter a valid integer greater than 0.
Please enter a valid number. -6
Error: Please enter a valid integer greater than 0.
Please enter a valid number. 55
-5
As you can see instead of returning 55 it returns my -5. FYI I placed a System.out.println tp see what the computer is doing. And I'm seeing its just not returning my value. Even if I remove my break statement in my while loop the text application just pauses....nothing happens. It does not display my Hello World statements. Any suggestions???
Thanks Again!
--- Update ---
Never mind I figured it out. lol