one problem I noticed is that the program crashes if you enter non digits even though there is a catch statement. can someone help me out? I can't seem to find the problem.
Can you also explain what I'm doing wrong and why it's wrong? Thank you in advance.
//previous code had an issue while I was creating a new scanner. it's correct now.
import java.util.*;
public class HighLow {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int numberOfAttempts = 0;
System.out.println("WIN THE THREE ROUNDS TO WIN THE GAME!.");
int theNumber = (int) (Math.random() * 10 + 1);
System.out.println("Round 1: I am thinking of a number between" + "\n" + "1 and 10, can you guess the number in " + "\n" + "less than 3 attempts?");
System.out.println("Type a number below and press enter.");
int guess = 0;
do {
try {
guess = scan.nextInt();
if (guess != theNumber) {
if (guess < theNumber) {
System.out.println("Sorry " + guess + " is too low, please try again");
}else if (guess > theNumber) {
System.out.println("Sorry " + guess + " is too high, please try again." );
}
numberOfAttempts = numberOfAttempts + 1;
}else {
System.out.println(guess + " is the correct answer. You got it on" + "\n" + "attempt number " + (numberOfAttempts + 1) + ". Proceeding to round 2.");
theNumber = (int) (Math.random() * 100 + 1);
System.out.println("\n" + "Round 2: I am thinking of a number between " + "\n" + "1 and 100, can you guess the number in " + "\n" + "less than 6 attempts?");
numberOfAttempts = 0;
int secondRoundGuess = 0;
do {
try {
secondRoundGuess = scan.nextInt();
if (secondRoundGuess != theNumber) {
if (secondRoundGuess < theNumber) {
System.out.println("Sorry " + secondRoundGuess + " is too low, please try again");
}else{
System.out.println("Sorry " + secondRoundGuess + " is too high, please try again");
}
numberOfAttempts = numberOfAttempts + 1;
}
else {
System.out.println(secondRoundGuess + " is the correct answer. You got it on " + "\n" + "attempt number " + (numberOfAttempts + 1) + "." + "\n" + "Proceeding to round 3.");
System.out.println("\n" + "Round 3: I am thinking of a number between " + "\n" + "1 and 1000, can you guess the number in " + "\n" + "less than 10 attempts?");
theNumber = (int)(Math.random() * 1000 + 1);
numberOfAttempts = 0;
int thirdRoundGuess = 0;
do {
try {
thirdRoundGuess = scan.nextInt();
if (thirdRoundGuess != theNumber) {
if (thirdRoundGuess < theNumber) {
System.out.println("Sorry " + thirdRoundGuess + " is too low, please try again");
}else {
System.out.println("Sorry " + thirdRoundGuess + " is too high, please try again");
}
numberOfAttempts = numberOfAttempts + 1;
}else{
System.out.println(thirdRoundGuess + " is the correct answer.");
System.out.println("You won the game, you are a badass." + "\n" + "I made this game and I cant even beat " + "\n" + "level 3.");
System.out.println("I am a newbie at programming and it's my " + "\n" + "fourth month on this java journey ." + "\n" + "I am looking for fellow newbies who are willing " + "\n" + "to learn and grow together (or advanced programmers " + "\n" + "who will not get annoyed by teaching newbies)." + "\n" + "If you get to this point in the game " + "\n" + "and see this message, hit me up via direct " + "\n" + "messaging, lets create a group where we can learn " + "\n" + "and grow together.");
}
}catch(Exception e) {
System.out.println("Please enter a number.");
thirdRoundGuess = scan.nextInt();
}
}while(numberOfAttempts != 10);
System.out.println("Game over, you were so close. Try again");
}
}catch(Exception e) {
System.out.println("Please enter a number.");
secondRoundGuess = scan.nextInt();
}
}while(numberOfAttempts != 6);
System.out.println("Game Over. Try again?");
}
}catch(Exception e) {
System.out.println("Please enter a number.");
guess = scan.nextInt();
}
}while (numberOfAttempts != 3);
System.out.println("Game Over. Try again?");
scan.close();
}
}
The root cause of the problem is using scan.nextInt() inside the catch block. What is happening is guess = scan.nextInt(); just below the try is throwing an exception for non-integer input and the control enters the catch block where it encounters guess = scan.nextInt(); again which tries to consume the Enter from the last input causing the program to crash as Enter is not an int.
How to get rid of it?
You need to make two changes to get rid of the problem:
A. Use guess = Integer.parseInt(scan.nextLine()); in which scan.nextLine() will also consume Enter.
B. Comment out the line, guess = scan.nextInt(); as shown below:
} catch (Exception e) {
System.out.println("Please enter a number.");
//guess = scan.nextInt();
}
This is the exception stack trace you get when you run the code:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at HighLow.main(HighLow.java:137)
When you handle the exception first time the user types in a non-numeric value, the exception gets handled below:
catch(Exception e) {
System.out.println("Please enter a number.");
guess = scan.nextInt();
}
When it reaches guess = scan.nextInt();, the previous non-numeric value is still present in the scanner. And when it tries to get an integer out of the scanner when it has a non-numeric value, it throws another InputMismatchException inside catch that is not handled.
Related
My code is supposed to ask the user to input a number between 1 and 10. If they input a number between 1 and 10, then it will say thank you and end there. If not, it should loop and say, Please input a number between 1 and 10, and Please try again. It will then make the user input again. My problem is that after the second input, it automatically ends the loop even if they make an incorrect input the second time. By the way, I am very new to coding so please go easy on me in the comments XD. Someone, please help, thanks.
Here is my code:
import javax.swing.*;
public class LoopLecture {
public static void main(String[] args) {
int MIN = 1;
int MAX = 10;
String rating;
rating = JOptionPane.showInputDialog(null, "Please enter your rating of Krabbypatties on a scale of"
+ MIN + "to" + MAX + ".With" + MIN + "meaning youhated it and" + MAX + "meaning you loved it.");
int rating2 = Integer.parseInt(rating);
while (rating2 < MIN || rating2 > MAX) {
JOptionPane.showMessageDialog(null, "You must enter a value between " + MIN + "and" + MAX + ".");
JOptionPane.showMessageDialog(null, "Please try again.");
rating = JOptionPane.showInputDialog(null, "Please enter your rating of Krabbypatties on a scale of"
+ MIN + "to" + MAX + ".With" + MIN + "meaning youhated it and" + MAX + "meaning you loved it.");
if (rating2 >= MIN && rating2 <= MAX)
break;
}
JOptionPane.showMessageDialog(null, "Thank you!");
}
}
Within for loop try assigning the new value to the rating2
rating = JOptionPane.showInputDialog(null, "Please enter your rating of Krabby
rating2 = JOptionPane.showInputDialog(null, "Please enter your rating of Krabby
while (true) { // creates infinite while loop
break; // ends an infinite loop
}
You have a break; expression in your if statement, so I'm sure you understand how it works, but try just making the loop infinite, like shown above.
more better may to solve it:
parse rating to rating2 in loop
break if number between 1 and 10
catch NumberFormatException, no need do anything, just ignore it
public static void main(String[] args) {
int MIN = 1;
int MAX = 10;
String rating = JOptionPane.showInputDialog(null, "Please enter your rating of Krabbypatties on a scale of"
+ MIN + "to" + MAX + ".With" + MIN + "meaning youhated it and" + MAX + "meaning you loved it.");
while (true) {
try {
int rating2 = Integer.parseInt(rating);
if (rating2 >= MIN && rating2 <= MAX) {
break;
}
} catch (NumberFormatException ignored) {
}
JOptionPane.showMessageDialog(null, "You must enter a value between " + MIN + "and" + MAX + ".");
JOptionPane.showMessageDialog(null, "Please try again.");
rating = JOptionPane.showInputDialog(null, "Please enter your rating of Krabbypatties on a scale of"
+ MIN + "to" + MAX + ".With" + MIN + "meaning youhated it and" + MAX + "meaning you loved it.");
}
JOptionPane.showMessageDialog(null, "Thank you!");
}
I wrote a program that asks for user input (numbers), then tells the user which of the two numbers they put in are bigger after making sure both values are numbers. This is looped. The problem is, when the user enters something that isn't valid, the program shuts down instead of referring to my else statements. I think this is because text values in strings cannot be processed using parseInt() so instead of the program realizing that a text value isn't a valid number, it just fails. I am using BlueJ to make this program if that helps anyone solve the problem. I am also open to people telling me how to make my program more efficient/easier to code (I am a beginner).
import java.util.Scanner;
public class TemperatureDriver {
public static void main(String[] args) {
while (true) {
Scanner keyInput = new Scanner(System.in);
System.out.print("Enter a number"+ "\n");
String number_one = keyInput.next();
if (Integer.parseInt(number_one) <=0 || Integer.parseInt(number_one) > 0) {
System.out.print("Enter another number" + "\n");
String number_two = keyInput.next();
if(Integer.parseInt(number_two) <=0 || Integer.parseInt(number_two) > 0){
if (Integer.parseInt(number_one) > Integer.parseInt(number_two)) {
System.out.print(number_one + " is greater than " + number_two + "\n" + "\n");
} else if(Integer.parseInt(number_one) < Integer.parseInt(number_two)){
System.out.print(number_one + " is less than " + number_two + "\n" + "\n");
} else if(Integer.parseInt(number_one) == Integer.parseInt(number_two)){
System.out.print(number_one + " is equal to " + number_two + "\n" + "\n");
}
} else {
System.out.println("Invalid number!"+ "\n");
}
} else {
System.out.println("Invalid number!"+ "\n");
}
}
}
}
Your code where you call parseInt should be embedded in a try block, which should be followed by a catch block to catch the NumberFormatException.
try {
if (Integer.parseInt(number_one) <= 0 || Integer.parseInt(number_one) > 0) {
System.out.print("Enter another number" + "\n");
String number_two = keyInput.next();
if (Integer.parseInt(number_two) <= 0 || Integer.parseInt(number_two) > 0) {
if (Integer.parseInt(number_one) > Integer.parseInt(number_two)) {
System.out.print(number_one + " is greater than " + number_two + "\n" + "\n");
} else if (Integer.parseInt(number_one) < Integer.parseInt(number_two)) {
System.out.print(number_one + " is less than " + number_two + "\n" + "\n");
} else if (Integer.parseInt(number_one) == Integer.parseInt(number_two)) {
System.out.print(number_one + " is equal to " + number_two + "\n" + "\n");
}
} else {
System.out.println("Invalid number!" + "\n");
}
} else {
System.out.println("Invalid number!" + "\n");
}
} catch (NumberFormatException e) {
System.out.println("Not a valid number");
}
I want to have the userScore and computerScore updated every time the user inputs 'y' to play again, but instead, the scores get initialized from 0.
I have made an ArrayList to show the results every time user plays. Does Anyone have any suggestion on a better implementation for this?
Please ignore violation of the DRY principal :)
import java.util.*;
import java.io.*;
class OddsAndEvens{
static int UserScore = 0;
static int computerScore = 0;
static ArrayList<Integer> UserScoreArray = new ArrayList<Integer>();
static ArrayList<Integer> computerScoreArray = new ArrayList<Integer>();
public static void main(String args[]){
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
String name = "", choice="";
System.out.println("______________________________________________________________________________");
System.out.println();
System.out.println("Let's play a game called Odds and Evens");
System.out.print("What is your name? ");
try{
name = console.readLine();
} catch(Exception e){
System.out.println("Error while name input: " + e);
}
System.out.print("Hi " + name + ", which do you choose? (O)dds or (E)vens? ");
try{
choice = console.readLine().toLowerCase();
} catch(Exception e){
System.out.println("Error while Choosing Odd or Even: " + e);
}
if(choice.startsWith("o")){
System.out.println(name + " chose ODDS, the Computer will be EVENS");
} else if(choice.startsWith("e")){
System.out.println(name + " chose EVENS, the Computer will be ODDS");
} else{
System.out.println("Enter a valid choice "+ name + "..Either O(o) or E(e)");
}
System.out.println("______________________________________________________________________________");
System.out.println();
while(play(console, name, choice, UserScore, computerScore).startsWith("y")){
play(console, name, choice, UserScore, computerScore);
}
}
public static String play(BufferedReader console, String name, String choice, int UserScore, int computerScore){
int numberOfFingers = 0;
UserScoreArray.add(0);
computerScoreArray.add(0);
System.out.println("How many 'fingers' do you put out?(You can only put out 5 fingers)");
try{
numberOfFingers = Integer.parseInt(console.readLine());
} catch(Exception e1){
System.out.println("Error while, taking number of fingers: " + e1);
}
if(numberOfFingers > 5){
System.out.println("You cannot put out more than 5 fingers " + name);
System.out.println("Let's try again!");
play(console, name, choice, UserScore, computerScore);
}
Random rand = new Random();
int computerFingers = rand.nextInt(6);
System.out.println("The computer played: " + computerFingers);
int sum = numberOfFingers + computerFingers;
System.out.println("sum = " + numberOfFingers + "+" + computerFingers);
if(sum%2 == 0){
System.out.println(sum + " is. . . . Even");
if(choice.startsWith("e")){
System.out.println("The Winner is " + name);
UserScore++;
UserScoreArray.add(UserScore);
System.out.println(name + "'s score: " + UserScoreArray.get(UserScoreArray.size() - 1));
System.out.println("Computer's score: " + computerScoreArray.get(computerScoreArray.size() - 1));
} else{
System.out.println("The Winner is Computer");
computerScore++;
computerScoreArray.add(computerScore);
System.out.println(name + "'s score: " + UserScoreArray.get(UserScoreArray.size() - 1));
System.out.println("Computer's score: " + computerScoreArray.get(computerScoreArray.size() - 1));
}
} else{
System.out.println(sum + " is. . . . Odd");
if(choice.startsWith("o")){
System.out.println("The Winner is " + name);
UserScore++;
UserScoreArray.add(UserScore);
System.out.println(name + "'s score: " + UserScoreArray.get(UserScoreArray.size() - 1));
System.out.println("Computer's score: " + computerScoreArray.get(computerScoreArray.size() - 1));
} else{
System.out.println("The Winner is Computer");
computerScore++;
computerScoreArray.add(computerScore);
System.out.println(name + "'s score: " + UserScoreArray.get(UserScoreArray.size() - 1));
System.out.println("Computer's score: " + computerScoreArray.get(computerScoreArray.size() - 1));
}
}
System.out.println("______________________________________________________________________________");
System.out.println(name + "'s Array List contents: " + "\n" + UserScoreArray);
System.out.println("______________________________________________________________________________");
System.out.println("Computer's Array List contents: " + "\n" + computerScoreArray);
System.out.println("______________________________________________________________________________");
System.out.println();
System.out.println("How does the Score look like " + name + ", Want to Play again?(y or n)");
String playAgain = "";
try{
playAgain = console.readLine().toLowerCase();
} catch(Exception e3){
System.out.println("Error in function for playAgain: " + e3);
}
if(playAgain.startsWith("y")){
System.out.println("Starting another game-");
return playAgain;
}
else{
System.out.println("Thank you for playing, see you soon..");
System.exit(0);
}
return "p";
}
}
Please note that static variable is seen in all instances of a class. You don't need to pass it as a parameter to a method.
If you pass it as a parameter, please note the parameter name. If your variable is called "score" and your parameter is called "score" as well, what you are changing (with "score++" or other "score" manipulation) is no longer the "score" class variable, but a method parameter, and changes done to it will no longer be visible when you exit the method. This is called shadowing.
I suggest (for similar questions) a sister-site to SO - one that deals with code reviews. https://codereview.stackexchange.com/ You may learn more there, since here we tend to focus on specific problems.
Try this code , it will works, you need to intialies index 0 of 2 arrays in the beginining of main method
Here is the code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Random;
class OddsAndEvens{
static int UserScore = 0;
static int computerScore = 0;
static ArrayList<Integer> UserScoreArray = new ArrayList<Integer>();
static ArrayList<Integer> computerScoreArray = new ArrayList<Integer>();
public static void main(String args[]){
UserScoreArray.add(0);
computerScoreArray.add(0);
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
String name = "", choice="";
System.out.println("______________________________________________________________________________");
System.out.println();
System.out.println("Let's play a game called Odds and Evens");
System.out.print("What is your name? ");
try{
name = console.readLine();
} catch(Exception e){
System.out.println("Error while name input: " + e);
}
System.out.print("Hi " + name + ", which do you choose? (O)dds or (E)vens? ");
try{
choice = console.readLine().toLowerCase();
} catch(Exception e){
System.out.println("Error while Choosing Odd or Even: " + e);
}
if(choice.startsWith("o")){
System.out.println(name + " chose ODDS, the Computer will be EVENS");
} else if(choice.startsWith("e")){
System.out.println(name + " chose EVENS, the Computer will be ODDS");
} else{
System.out.println("Enter a valid choice "+ name + "..Either O(o) or E(e)");
}
System.out.println("______________________________________________________________________________");
System.out.println();
while(play(console, name, choice, UserScore, computerScore).startsWith("y")){
play(console, name, choice, UserScore, computerScore);
}
}
public static String play(BufferedReader console, String name, String choice, int UserScore, int computerScore){
int numberOfFingers = 0;
System.out.println("How many 'fingers' do you put out?(You can only put out 5 fingers)");
try{
numberOfFingers = Integer.parseInt(console.readLine());
} catch(Exception e1){
System.out.println("Error while, taking number of fingers: " + e1);
}
if(numberOfFingers > 5){
System.out.println("You cannot put out more than 5 fingers " + name);
System.out.println("Let's try again!");
play(console, name, choice, UserScore, computerScore);
}
Random rand = new Random();
int computerFingers = rand.nextInt(6);
System.out.println("The computer played: " + computerFingers);
int sum = numberOfFingers + computerFingers;
System.out.println("sum = " + numberOfFingers + "+" + computerFingers);
if(sum%2 == 0){
System.out.println(sum + " is. . . . Even");
if(choice.startsWith("e")){
System.out.println("The Winner is " + name);
UserScore++;
UserScoreArray.add(UserScore + UserScoreArray.get(UserScoreArray.size() - 1));
System.out.println(name + "'s score: " + UserScoreArray.get(UserScoreArray.size() - 1));
System.out.println("Computer's score: " + computerScoreArray.get(computerScoreArray.size() - 1));
} else{
System.out.println("The Winner is Computer");
computerScore++;
computerScoreArray.add(computerScore + computerScoreArray.get(computerScoreArray.size() - 1));
System.out.println(name + "'s score: " + UserScoreArray.get(UserScoreArray.size() - 1));
System.out.println("Computer's score: " + computerScoreArray.get(computerScoreArray.size() - 1));
}
} else{
System.out.println(sum + " is. . . . Odd");
if(choice.startsWith("o")){
System.out.println("The Winner is " + name);
UserScore++;
UserScoreArray.add(UserScore + UserScoreArray.get(UserScoreArray.size() - 1));
System.out.println(name + "'s score: " + UserScoreArray.get(UserScoreArray.size() - 1));
System.out.println("Computer's score: " + computerScoreArray.get(computerScoreArray.size() - 1));
} else{
System.out.println("The Winner is Computer");
computerScore++;
computerScoreArray.add(computerScore + computerScoreArray.get(computerScoreArray.size() - 1));
System.out.println(name + "'s score: " + UserScoreArray.get(UserScoreArray.size() - 1));
System.out.println("Computer's score: " + computerScoreArray.get(computerScoreArray.size() - 1));
}
}
System.out.println("______________________________________________________________________________");
System.out.println(name + "'s Array List contents: " + "\n" + UserScoreArray);
System.out.println("______________________________________________________________________________");
System.out.println("Computer's Array List contents: " + "\n" + computerScoreArray);
System.out.println("______________________________________________________________________________");
System.out.println();
System.out.println("How does the Score look like " + name + ", Want to Play again?(y or n)");
String playAgain = "";
try{
playAgain = console.readLine().toLowerCase();
} catch(Exception e3){
System.out.println("Error in function for playAgain: " + e3);
}
if(playAgain.startsWith("y")){
System.out.println("Starting another game-");
return playAgain;
}
else{
System.out.println("Thank you for playing, see you soon..");
System.exit(0);
}
return "p";
}
}
This happens because of your method parameters.You have two unwanted
method parameters in your play method.just remove UserScore &
computerScore parameters from your play method and your code should work well.
In your class, UserScore & computerScore fields are static. so no
need to pass those field values to another static method within the
same class.In your code those parameters just hide the actual static
fields.when you print the value of UserScore or computerScore in play
method, java just print the value of the local method parameters
instead of static fields.
Having issues with trying to get this to run and ask the user for their guess, then if it's too low, it states too low, or too high, or correct. Then states what the number was. This is the code I have so far.
import javax.swing.JOptionPane;
public class RandomGuess2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int random;
final int MIN = 1;
final int MAX = 10;
int userNum;
String userInput;
userInput = JOptionPane.showInputDialog(null, "Please guess a number between 1 and 10");
random = 1 + (int)(Math.random() * MAX);
userNum = Integer.valueOf(userInput);
int userDiff = (random - userNum);
if (userDiff < 0) {
JOptionPane.showMessageDialog(null, "Your guess of " + userNum + " is TOO HIGH");
if (userDiff > 0)
JOptionPane.showMessageDialog(null, "Your guess of " + userNum + " is TOO LOW");
if (userNum == random)
JOptionPane.showMessageDialog(null, "Your guess of " + userNum + " is correct! Congratulations!");
else
JOptionPane.showMessageDialog(null, "The number was " + random + "\nTry again Next time!");
}
}
}
Any help would be very much appreciated!
The Reason it wasn't working was because your checking was wrong it needs to be like this
if (userNum == random){
JOptionPane.showMessageDialog(null, "Your guess of " + userNum + " is correct! Congratulations!");
}
else{
if (userDiff < 0) {
JOptionPane.showMessageDialog(null, "Your guess of " + userNum + " is TOO HIGH");
}
if (userDiff > 0)
{
JOptionPane.showMessageDialog(null, "Your guess of " + userNum + " is TOO LOW");
}
JOptionPane.showMessageDialog(null, "The number was " + random + "\nTry again Next time!");
}
yours was checking first to see if the usernum was too high and if it was then it would check to see if the usernum was correct or to too low but that code only ran if the num was too high.
Your if-else-structure is not right. I guess this is what you want:
if (userDiff < 0) {
JOptionPane.showMessageDialog(null, "Your guess of " + userNum + " is TOO HIGH");
} else if (userDiff > 0) {
JOptionPane.showMessageDialog(null, "Your guess of " + userNum + " is TOO LOW");
}
if (userNum == random) {
JOptionPane.showMessageDialog(null, "Your guess of " + userNum + " is correct! Congratulations!");
} else {
JOptionPane.showMessageDialog(null, "The number was " + random + "\nTry again Next time!");
}
So, I'm having an issue getting my program to print out You must enter either C or F or Y or N depending on the response that is inputted. I have tried putting other if-else statements inside the program, but it does not function correctly and breaks the for loop.
public static void main(String[] args) {
for (int i = 0; i < 4; i++) {
System.out.println("Programmed by .");
double standardCompact = 30.50;
double couponCompact = ((30.50)-(30.50 * 0.07));
double standardFullSize = 40.50;
double couponFullSize = ((40.50)-(40.50 * 0.07));
// Scanner Input
Scanner input = new Scanner(System.in);
System.out.print("Rent a Car? [Y or N]: ");
// Response String
String response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("You entered no. Bye.");
}
else if (response.equals("Y")) {
System.out.print("Compact or Full-Size? [C or F]: ");
response = input.next().toUpperCase();
if (response.equals("C")) {
System.out.println("You selected Compact.");
//case1
System.out.print("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is " + standardCompact + " per day.");
}
else if (response.equals("Y")) {
System.out.println("Price is " + couponCompact + " per day.");
}
}
else if (response.equals("F")) {
System.out.println("You have selected Full-Size. ");
//case 2
System.out.print("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is " + standardFullSize + " per day.");
}
else if (response.equals("Y")) {
System.out.println("Price is " + couponFullSize + " per day.");
}
}
}
}
}
When constructing an if statement, else can be used to handle all other conditions not caught by previous if or else if statements.
int x = 0;
if(x ==1){
System.out.println("1");
}else if(x ==2){
System.out.println("2");
}else{
//execute if none of the other conditionals are true
System.out.println("Other Conditions not met");
}
//Outputs: Other Conditions not met
Consider using a combination of a boolean flag, and 'else' statements. Therefore, if the user does not enter N or Y, set this flag to true. Similarly, if the user does not enter C or F, set this flag to true.
Later, at the end of the for-loop, check this flag. If it is true, print your message. This could be worth a try...
public static void main(String[] args) {
boolean notValidCharacter;
for(int i = 0; i < 4; i++) {
notValidCharacter = false;
System.out.println("Programmed by .");
double standardCompact = 30.50;
double couponCompact = ((30.50)-(30.50 * 0.07));
double standardFullSize = 40.50;
double couponFullSize = ((40.50)-(40.50 * 0.07));
//Scanner Input
Scanner input = new Scanner(System.in);
System.out.print("Rent a Car? [Y or N]: ");
//Response String
String response = input.next().toUpperCase();
if (response.equals("N")){
System.out.println("You entered no. Bye. ");
}
else if (response.equals("Y")) {
System.out.print("Compact or Full-Size? [C or F]: ");
response = input.next().toUpperCase();
if (response.equals("C")) {
System.out.println("You selected Compact. ");
//case1
System.out.print("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is" + " " + standardCompact + " " + "per day.");
}
else if (response.equals("Y")) {
System.out.println("Price is" + " " + couponCompact + " " + "per day.");
}
}
else if(response.equals("F")) {
System.out.println("You have selected Full-Size. ");
//case 2
System.out.print("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is" + " " + standardFullSize + " " + "per day.");
}
else if (response.equals("Y")) {
System.out.println("Price is" + " " + couponFullSize + " " + "per day.");
}
}
else {
notValidCharacter = true;
}
}
else {
notValidCharacter = true;
}
if (notValidCharacter) {
System.out.println("You must enter either C or F or Y or N");
}
}
}