I am writing a simple bank application. In my program I have used a while loop. In case a user enters wrong input it will re-prompt to enter again.
Now the problem is I am not able to write any system.out.print statement after the loop. It always shows error (says: unreachable statement), and eventually the line doesn't get printed out.
HOW CAN I FIX THIS?
[The reason I need to use system.out.print because I want to print all the info the user has input.]
The program I am working on:
package bankapplication;
import java.util.Scanner;
public class BankApplication {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("WELCOME TO OUR BANK!\n\nPlease give all the inofrmation correctly.");
System.out.println("Enter your name: ");
String name = input.nextLine();
System.out.println("");
System.out.println("Enter your SSN: ");
String ssn = input.next();
System.out.println("");
System.out.println("Enter your Address: ");
String address = input.next();
System.out.println("");
System.out.println("Enter your telephone nr: ");
String teleNum = input.next();
System.out.println("");
while (true) {
System.out.println("Choose an account number for you (Between 5 and 10 positive numbers): ");
int accNum = input.nextInt();
System.out.println("");
if (accNum < 0 && accNum > 10 && accNum < 6) {
System.out.println("Invalid choise!");
} else {
System.exit(0);
}
}
System.out.println("Congratulation! Your new account has been created!");
System.out.println("The following is your account info:\n");
System.out.println("name: " + name + "SSN: " + ssn + "Address: " + address + "Tele. Num: " + teleNum + "Acc num: " + accNum);
}
}
When you invoke System.exit the entire program exits and the process is terminated. Instead you could replace the else statement with:
else { break; }
That will break the current loop and the rest of the statements will be printed. The keyword break simply breaks the loop.
You have a while (true) loop - a loop which is infinite unless something in the loop breaks out of it. The only line you have that breaks out of the loop is System.exit(0), which will end your program entirely. Therefore it is impossible to reach the code after your loop.
If you mean to break out of the loop in your else clause, use a break statement instead of exiting the program.
Note however that your if condition will never be true.
if (accNum < 0 && accNum > 10 && accNum < 6) {
accNum can never be less than zero and greater than 10.
You need to figure out what condition you actually want to check.
the condition
(accNum < 0 && accNum > 10 && accNum < 6)
can never be acheived , there is no way a number can be negative and >10 at the same time...the System.exit(0) will always be called on first loop.
That and when u call System.exit(0) you are exiting the program not the loop, therefor you will never reach the statement you are talking about .
you should either use
break;
or if you would like more prestige, put the right condition in the while(condition) ... try not to get used to using break ;
Related
Hello I am stuck on a programming assignment for class. The assignment is to make a program that can count different loops. I have the prompt user input code correct I think I just can't figure out how to make it print my message the amount of times that I have entered.
I want the second while loop to print something like
Row 1 - Hello
Row 2 - Hello
Row 3 - Hello
Row 4 - Hello
For the number that I put as the input.
Thank you for the help in advance.
import java.util.Scanner;
public class CountingLoops
{
public static void main(String[] args)
{
String message; // First message prompt
String inputString; // For reading input.
double numRows; // Number to be asked.
double rowNumber = 1;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the message you want to print? ");
message = keyboard.nextLine();
System.out.print("Enter how many times you want your message to be printed. Enter the value from 1-20:" );
numRows = keyboard.nextDouble();
while (numRows > 20 || numRows < 1)
{
System.out.print("Number was not between 1-20. Try Again.");
System.out.print("Enter how many times you want your message to be printed. Enter the value from 1-20: ");
numRows = keyboard.nextDouble();
}
while (numRows <= 20)
{
System.out.println("Row " + rowNumber++ + " - " + message);
rowNumber = keyboard.nextDouble();
rowNumber++;
}
}
}
What do you mean by "a program that can count different loops". Currently the bottom while loop is an infinite loop since numRows isn't being updated. Here's what I believe can solve your issue:
while (numRows > 0)
{
System.out.println("Row " + rowNumber++ + " - " + message);
rowNumber++;
numRows--;
}
Since it is an assignment, I won't provide the code. But all the problem with your code is in the last while loop.
First, you don't even change the value of the variable numRows and of course, you cannot exit the while loop.
Second, you don't need to read another input during this while loop since all the input is done at the beginning.
Third, you added rowNumber twice in your code and obviously, it is incorrect and it should be changed to something else.
Your answer will involve comparing rowNumber and numRows to determine when you are done.
The instructions read:
Write a program that prompts the user to input a student first name followed by a space and an integer test grade, then the user will press enter and you will prompt them again for a name and a test grade; for a total of 10 students and 10 grades. (Ex: Dawn 100 ) ; You must check that the user enters a grade that is >= 0 and <= 100. If not, you must prompt the user with an error message and the user must input the grade again.
I can't figure out how to do this without getting a java.util.InputMismatchException error message.
Scanner input = new Scanner(System.in);
String[] students = new String[10];
int[] grades = new int[10];
for(int i = 0; i < students.length; )
{
System.out.println("Enter a student name and grade(between 0 and 100): ");
if(input.nextInt() > 0 && input.nextInt() <= 100)
{
students[i] = input.next();
grades[i] = input.nextInt();
i++;
}
else
{
System.out.println("*Error* Grade value must be between 0 and 100. Please Try again");
}
}
Let's take a closer look...
if(input.nextInt() > 0 && input.nextInt() <= 100)
You check the input for nextInt, twice, so you're no longer actually comparing the same value, but also, you've asked for a String and an int value, but you've not checked for the String first...
Assume I entered something like 500 -1, then you're if statement would pass successfully, because 500 is > 0 and -1 is <= 100
And if by some miracle, that worked, you're reading another String and another int from the stream...
students[i] = input.next();
grades[i] = input.nextInt();
So, for this to work, the input would have to be something like 1 2 John 50 ... which would just be completely weird and completely void what you're trying to do.
Instead, ask for one piece of information at a time and process it, for example...
Scanner input = new Scanner(System.in);
System.out.print("User name: ");
String name = input.nextLine();
System.out.print("Grade: ");
String gradeValue = input.nextLine();
Scanner parser = new Scanner(gradeValue);
if (parser.hasNextInt()) {
int grade = parser.nextInt();
if (grade >= 0 && grade <= 100) {
// Good grade
} else {
System.out.println("!! " + grade + " is not a valid grade");
}
} else {
System.out.println("!! " + gradeValue + " is not a valid integer value");
}
Don't keep reading from the Scanner when you're not expecting a value, extract the value you need and process it. Here I've used nextLine to get the grade and a second Scanner to parse it, it's safer and avoids the oddities where the new line is left in the buffer. It also gives you better control to process errors ;)
This is the main culprit:
if(input.nextInt() > 0 && input.nextInt() <= 100)
Your if condition contains two (2) calls to input.nextInt(), so at this point — before reading the name — your program will attempt to read two numbers from input and see if the first is greater than 0 and the second less than or equal to 100. And if it succeeded, it would not store the numbers read into any variables.
Instead you need to read the name into students[i] first. Then read the grade into grades[i]. Then check if the grade read is in the interval. I suggest you use a while loop so that as long as the grade is outside the interval, you print the error message and read the grade anew. If the first grade read was OK, you while loop won’t execute at all, so this is fine.
I can't figure out how to do this without getting a
java.util.InputMismatchException error message.
The first mistake you've made is reading user input incorrectly input.nextInt() > 0 && input.nextInt() this is requiring the user to enter an integer value twice whereas what you want is name (string) & grade (int).
the solution below takes that mistake into consideration, however personally I would use a while loop, but since you're using a for loop already I have decided to incorporate with that.
full solution:
Scanner input = new Scanner(System.in);
String[] students = new String[10];
int[] grades = new int[10];
for(int i = 0; i < students.length; i++)
{
System.out.println("Enter a student name and grade(between 0 and 100): ");
String getInput = input.nextLine();
if(Integer.parseInt(getInput.split(" ")[1]) < 0 || Integer.parseInt(getInput.split(" ")[1]) > 100)
{
System.out.println("*Error* Grade value must be between 0 and 100. Please Try again");
i--;
}
else {
students[i] = getInput.split(" ")[0];
grades[i] = Integer.parseInt(getInput.split(" ")[1]);
}
}
note - the solution given only takes into consideration what you've mentioned within your question i.e it is expecting input as such Ousmane 20, Brendon 23 , jack 30 etc, also you can make the program a bit more robust by adding more validations if needed maybe NumberFormatException, Scanner#hasNextInt() and so forth.
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter a digit: ");
int digit = in.nextInt();
boolean isAnInteger = false;
while (isAnInteger)
{
if (digit >= 10)
{
System.out.println("Please enter an integer: ");
}
else
{
System.out.println("Correct! " + digit + " is an integer!");
}
}
}
I'm currently taking AP Computer Science and I'm curious as to how to solve this (albeit basic) issue. I'm aware that "while" loops continue whatever is in their respective curly brackets when a condition in their parenthesis continues to be a met.
When I tried setting the while condition to while (digit >= 10), it resulted in an infinite loop (correct me, but it is due to the fact that if the user inputs a digit of 10 or greater, the condition will KEEP being met and continue infinitely). So, I tried setting the while condition to some boolean value, and an if nested inside with the prior condition. Now, when the user enters 10, nothing happens after, and the program ends.
How do I write the above code so that the System will continue printing "Please enter an integer:" if the condition (of inputting 10 or greater and the opposite) continues to be met?
There is a basic "poor design" issue that the variable isAnInteger has a scope wider than needed (it lives past the last line that needs it).
The "correct" approach is loop that contains the logic that determines "integerness" of the input and doesn't leave variables in scope when the loop ends, other than the captured input in digit of course.
Next, you want to separate the concerns of capturing input with checking it, so first create a method that gets a digit:
private static int readNumber(Scanner in) {
System.out.print("Please enter a digit: ");
int digit = in.nextInt();
in.nextLine(); // you must clear the newline char from the buffer
return digit;
}
Next, write a simple while() loop that keeps reading until it gets good input:
int digit = 10; // bad input
while (digit > 9) {
digit = readNumber(in);
}
Putting it all together with the final message:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int digit = 10; // initialize with "bad" input
while (digit > 9) {
digit = readNumber(in);
}
System.out.println("Correct! " + digit + " is an integer!");
}
private static int readNumber(Scanner in) {
System.out.print("Please enter a digit: ");
int digit = in.nextInt();
in.nextLine(); // you must clear the newline char from the buffer
return digit;
}
This approach makes the code much easier to read and understand.
Also notice how there is no repeated code (such as the line asking for a digit, or reading input).
The main conceptual piece here is that you don't update your value anywhere inside of your loop. Because it does not update, it will always remain the value it was when it entered the loop (that is, digit >= 10 will remain true until the program stops running).
You must update your values inside of your loop.
However, there's another concept you're missing: you're guaranteed to run the loop at least once, so you should take advantage of the do...while loop instead.
Note that I make use of nextLine() to avoid any wonky nextInt() issues.
(Oh, by the way: any number you're looking for is an integer. You should communicate that you're looking for an integer less than 10 instead.)
System.out.print("Please enter a digit: ");
int digit = Integer.parseInt(in.nextLine());
boolean isAnInteger;
do {
if (digit >= 10) {
System.out.println("Please enter an integer: ");
digit = Integer.parseInt(in.nextLine());
isAnInteger = false;
} else {
System.out.println("Correct! " + digit + " is an integer!");
isAnInteger = true;
}
} while (isAnInteger);
Yes, Makoto has it right.
You never update your values inside the while loop. In your original case, when you just wanted to keep printing out Please enter an integer: , you never ask for an input right after that line. Your original digit value will continue to be greater than or equal to 10, and will keep the loop going.
Even with your current code, you will still run into an infinite loop if your digit value is less than 10. Notice how the boolean isAnInteger is independent of whether your digit is less than 10.
The best way to fix this is by using something like this:
in = new Scanner(System.in);
System.out.print("Please enter a digit: ");
int digit = in.nextInt();
while (digit >= 10)
{
System.out.println("Please enter an integer: ");
digit = in.nextInt();
}
System.out.println("Correct! " + digit + " is an integer!");
What this does is it keeps checking to see if digit is greater than or equal to 10. If so, it will continue to ask the user for an input. If at any time during the iteration of the loop the user enters a value less than 10, it will not execute the next iteration, and leaves the loop. It will then execute the last println.
However, if the first input is less than 10, it will skip the while loop and execute the println at the bottom.
If you want to use a boolean like you did, you can do it in such a manner:
in = new Scanner(System.in);
System.out.print("Please enter a digit: ");
int digit = in.nextInt();
bool isAnInteger = true;
if (digit >= 10)
isAnInteger = false;
while (!isAnInteger) // checks if digit is not an integer
{
System.out.println("Please enter an integer: ");
digit = in.nextInt();
if !(digit >= 10)
isAnInteger = true;
}
System.out.println("Correct! " + digit + " is an integer!");
Makoto's way of using a do while loop is probably better, although this may be a better way of visualizing it (since you used a while loop).
My code here checks whether or not the word that the user inputs is a palindrome or not. It executes properly its just that if the user tries to loop it by pressing "1". The program ends. How do I fix this?
int answer =0;
String original, backwards = "";
Scanner input = new Scanner(System.in);
System.out.println("A palindrome is a word that is the same forwards as it is backwards. Enter a word to check if it is a palindrome or not.");
original = input.nextLine();
int length = original.length();
do {
for ( int i = length - 1; i >= 0; i-- )
backwards = backwards + original.charAt(i);
if (original.equals(backwards))
System.out.println("The entered phrase is a palindrome.");
else
System.out.println("The entered phrase is not a palindrome.");
}
while (answer ==1);
System.out.println("If you would like to check another word press 1. If you wish to exit, press 2.");
answer = input.nextInt();
if (answer ==1){
System.out.println("Enter another word");
}
else if (answer == 2){
System.out.println("Have a nice day");
}
}
}
Here is a sample output of the program:
A palindrome is a word that is the same forwards as it is backwards. Enter a word to check if it is a palindrome or not.
racecar
The entered phrase is a palindrome.
If you would like to check another word press 1. If you wish to exit, press 2.
1
Enter another word
Your loop finishes before the user gets to choose if he wants to enter 1 or 2. It is a do...while loop, so it ends at the while. So it executes only once - because as soon as a palindrome is checked, the next thing is to check whether the answer is 1. But the user has not entered either 1 or 2 at this point.
So you should move the } while ( answer == 1 ) part to the line after the closing of the if...else... that checks what the user answer was.
Also, if the answer was 1, you should ask for another input. The only place you ask for input is before the loop starts. If the user answered 1 you should run original = input.nextLine(); again. Be careful - you may need to run two input.nextLine(), as the scanner will think the rest of the line after the 1 or 2 is what you meant.
Your scanner is asking for nextLine, but you're asking for an int. nextLine means it will take what is typed in the nextLine as a string.
Simple fix is replace 1 and 2 with characters a and b.
Complicated way is to parse string into integer.
make the palindrome check as a method and then call the method if the user input is 1.
In your code , it does not do anything if the user inout is equal to 1.
i just used your scanner objects as it is. You can declare them in your class to use it in all the methods.
public void palindrome(String S){
int answer =0;
String original, backwards = "";
Scanner input = new Scanner(System.in);
System.out.println("A palindrome is a word that is the same forwards as it is backwards. Enter a word to check if it is a palindrome or not.");
original = input.nextLine();
int length = original.length();
do {
for ( int i = length - 1; i >= 0; i-- )
backwards = backwards + original.charAt(i);
if (original.equals(backwards))
System.out.println("The entered phrase is a palindrome.");
else
System.out.println("The entered phrase is not a palindrome.");
}
while (answer ==1);
System.out.println("If you would like to check another word press 1. If you wish to exit, press 2.");
int option= input.nextInt();
if (option==1){
System.out.println("Enter another word");
String word= input.readLine();
palindrome(word);
}
You need to put the check if user want to enter another work in the while loop. But in the mean time, be careful to reset all variables to their original value, so it might be best to set them in the while loop as well. Something like this:
import java.util.Scanner;
public class Palidrome {
public static void main(String[] args) {
int answer = 0;
Scanner input = new Scanner(System.in);
String original;
System.out
.println("A palindrome is a word that is the same forwards as it is backwards. Enter a word to check if it is a palindrome or not.");
while( true ) {
original = input.nextLine();
String backwards = "";
int length = original.length();
for (int i = length - 1; i >= 0; i--)
backwards = backwards + original.charAt(i);
if (original.equals(backwards))
System.out.println("The entered phrase " + original + " is a palindrome.");
else
System.out.println("The entered phrase " + original + " is not a palindrome.");
System.out.println("If you wish to exit, press 2");
answer = input.nextInt();
if(answer == 2) {
System.out.println("Have a nice day");
break;
}
input.nextLine();
System.out.println("Enter another word");
}
input.close();
}
}
A do while loop works the same way as a regular while loop, except the first conditional check is omitted. If the condition in your while was met, then execution of the code in the do block would be continued. However, the while condition is never met, can you see why? Even if this condition was met, that's not the code you wanted executed next. The code below while is not a part of the do-while loop. You need to move the while to come after both of your conditional blocks at the end. The Java docs on while loops should be a useful read.
public static void date1() {
int x = 0 ; //integer for looping
do // process to follow if length == 5
{
Scanner scanner = new Scanner(System.in);
try {
System.out.println("Please enter the first date ");
System.out.println("Please enter the year: ");
y1 = scanner.nextInt();
System.out.println("Please enter the month: ");
m1 = scanner.nextInt();
System.out.println("Please enter the day: ");
d1 = scanner.nextInt();
} catch (InputMismatchException inputMismatchException) {
scanner.nextLine();
System.err.println("You must enter intergers. Please try again. ");
}
x = x + 1 ; // set loop to three attempts
} while (x < 3) ; //do process occurs while attempts are under < 4
}
i want to break the loop if the all the inputs are proper (integers entered). I am not too sure what command to use to break the loop i created.
thanks in advance everybody!
Put a break command before you close your try{} block. If no exception is thrown, the break command will be executed and exit the loop.
A better way to do it, though, is to make a separate method that accepts a single input from the user, then call it three times. This way, you don't have to make the user input the first two numbers again if only the third one wasn't valid:
private static int getIntInput(){
while(true){
try{
return scanner.nextInt();
} catch(InputMismatchException e){
System.out.println("You must enter integers. Please try again.");
}
}
}
public static void date1(){
int x=0;
System.out.println("Please enter the first date ");
System.out.println("Please enter the year: ");
y1 = getIntInput();
System.out.println("Please enter the month: ");
m1 = getIntInput();
System.out.println("Please enter the day: ");
d1 = getIntInput();
}
You could, of course, make things more fancy... we could add a String input to the getIntInput() method, and then print that string every time we are accepting an input, so the user doesn't forget what he's trying to enter. Or you could clean up the syntax so it works (I think the compiler will complain that getIntInput needs to return an int, the way I typed it up right now...)
You could add a variable boolean stop = false and then modify your while to be while( x < 3 || stop == true). Then add some code to set stop = true once you are satisfied with your inputs.
Here's a hint: "break" out of the loop when all the inputs are proper.