I was working on my assignment for my Java 1 class and I am getting an error that does not seem like it should be one. Can I get some help? It is saying that I have an else w/out if.
here is the if block
char placement = scan.next().toUpperCase().charAt(0);
if(placement == 'F')
{
System.out.print("Please Enter The Show To Be Added At The Beginning Of The List: ");
String show = scan.next();
TVShows.add(0, show);
}
else if(placement == 'R');
{
System.out.print("Please Enter The Show To Be Added At The End Of The List");
String show = scan.next();
TVShows.add(show);
}
else
{
System.out.println("Invalid Choice Please Try Again");
}
Remove the semi colon
else if (placement == 'R');
^
which is terminating the else if block statement
Related
Here is my code:
while (menuExit == true) {
System.out.println (SEPARATE_LINE);
System.out.println ("Which do you want to do ? ");
System.out.println (SEPARATE_LINE);
System.out.println ("1.Register");
System.out.println ("2.Sign in");
System.out.println ("3.Check shop status");
System.out.println ("0.Exit");
System.out.println (SEPARATE_LINE);
System.out.print("Please enter your choice as number:");
do{
try{
int selectMain = input.nextInt();
if(selectMain == 1){
register(currentNum , customers);
customers.clear();
customers = ReadData.readCustomerData();
}else if(selectMain == 2){
signIn(customers,historys,cusData,hisData);
}else if(selectMain == 3){
CheckData.checkShopStatus(shops,shopData);
}else if(selectMain == 0){
System.out.println ("Thank you");
menuExit = false;
}else {
System.out.println ("Your input are wrong , Please enter again.");
}
continueInput = false;
}catch(InputMismatchException ex){
System.out.println("Please enter again.");
input.nextLine();
}
}while (continueInput);
input.close();
This is the menu of my program , when I enter into one of these selection and come back to the menu , I got NoSuchElementException , the error point to the line int selectMain = input.nextInt();. Please someone help me , thank you for your attention.
You have continueInput = false in the try block in such a way that it means that it will run regardless of the user input. This means the dowhile loop exits on the next try, and the input is closed. however, because this is in another while loop, it tries to get another input, even though the input scanner is closed! This gets you the NoSuchElementException.
package javaapplication1;
import java.util.Scanner;
public class JavaApplication1 {
public static void main(String[] args) {
System.out.println("What is the password?");
Scanner new2 = new Scanner(System.in);
int input = 0;
while(input <= 5 )
{
String password = new2.nextLine();
if(!password.equals("bluesky123")){
System.out.println("Incorrect password");
input++;
}
else if("bluesky123".equals(password)) {
System.out.println("You got it right!");
break;
}
else if(input == 5) {
System.out.println("maximum number of attempts reached");
break;
}
}
}
}
basically, once I hit the 5 loops, it just says "incorrect password" and breaks. not the "maximum attempts" message.
Allow me to annotate:
This if statement will always be evaluated:
if(!password.equals("bluesky123")){
System.out.println("Incorrect password");
input++;
}
This if statement will only be evaluated if the password is "bluesky123". In this case, it will always evaluate to true.
else if("bluesky123".equals(password)) {
System.out.println("You got it right!");
break;
}
There is no case when this if statement will ever be evaluated. Once if-else finds a statement that is true, it will skip all others in that section.
else if(input == 5) {
System.out.println("maximum number of attempts reached");
break;
}
In your case, you should consider a nested if (i.e. an if inside another if).
while(input <= 5 )
{
String password = new2.nextLine();
if(!password.equals("bluesky123")){
System.out.println("Incorrect password");
input++;
}
else {
System.out.println("You got it right!");
break;
}
if((input == 5) && (!password.equals("bluesky123"))) {
System.out.println("maximum number of attempts reached");
break;
}
}
Your logic has some flaws. You have to pay attention to how JAVA processes if / else if
https://www.tutorialspoint.com/java/if_else_statement_in_java.htm
I tested your code it is working! The only thing that you need to do is to move the follow line to inside the while loop
System.out.println("What is the password?");
Doing this it will print "Incorrect password" and then it will print again
"What is the password?"
Because in the way that it is working now seems that the software is not waiting the password to be retyped when in fact it is.
`String termination;
do {
System.out.println("Begin Transaction!");
int coinNumber;
String deposit;
do{
System.out.print(">>");
coinNumber = input.nextInt();
deposit = input.nextLine();
int search = deposit.indexOf(" ", 0);
String denominations = deposit.substring(search +1);
if (coinNumber < 0){
System.out.println("Error! Please deposit positive number.");
}
else if (denominations.equalsIgnoreCase("quarter") || denominations.equalsIgnoreCase("quarters")){
Customer.insertQuarters(coinNumber);
}
else if (denominations.equalsIgnoreCase("dime") || denominations.equalsIgnoreCase("dimes")){
Customer.insertDimes(coinNumber);
}
else if (denominations.equalsIgnoreCase("nickels") || denominations.equalsIgnoreCase("nickels")){
Customer.insertNickles(coinNumber);
}
else if (denominations.equalsIgnoreCase("penny") || denominations.equalsIgnoreCase("pennies")){
Customer.insertPennies(coinNumber);
}
else if (denominations.equalsIgnoreCase("quarter") || !denominations.equalsIgnoreCase("quarters")
|| !denominations.equalsIgnoreCase("dime") || !denominations.equalsIgnoreCase("dimes")
|| !denominations.equalsIgnoreCase("nickel") || !denominations.equalsIgnoreCase("nickels")
|| !denominations.equalsIgnoreCase("penny") || !denominations.equalsIgnoreCase("pennies")
|| !deposit.equalsIgnoreCase("done")){
System.out.println("Error! Please deposit correct denominations.");
}
} while (!deposit.contains("done"));
System.out.println(Customer.getVoucher());
System.out.print("Would you like to start another transaction (y/n): ");
termination = input.nextLine();
}
while (termination.equalsIgnoreCase("y"));
System.out.println(Customer.getCollectedFees());
input.close();
}
}`
I need it to be were user inputs: (4 quarters) and as many deposits as they want. Then, types 'done' without having lines in between the deposits.
enter image description here
Thank you.
The carriage return character isn't absorbed when you make a call to nextInt(). Try placing a Scanner.nextLine() right after your initialize coinNumber:
coinNumber = input.nextInt();
input.nextLine();
deposit = input.nextLine();
I'm trying to write some code that makes the user input a valid username and they get three tries to do it. Every time I compile it I get an else without if error wherever I have a else if statement.
Scanner in = new Scanner(System.in);
String validName = "thomsondw";
System.out.print("Please enter a valid username: ");
String input1 = in.next();
if (input1.equals(validName))
{
System.out.println("Ok you made it through username check");
}
else
{
String input2 = in.next();
}
else if (input2.equals(validName))
{
System.out.println("Ok you made it through username check");
}
else
{
String input3 = in.next();
}
else if (input3.equals(validName))
{
System.out.println("Ok you made it through username check");
}
else
{
return;
}
You are misunderstanding the use of if-else
if(condition){
//condition is true here
}else{
//otherwise
}else if{
// error cause it could never be reach this condition
}
Read more The if-then and if-then-else Statements
You can have
if(condition){
}else if (anotherCondition){
}else{
//otherwise means 'condition' is false and 'anotherCondition' is false too
}
If you have an if followed by an else, that ends the block. You can have if followed by multiple else if statements, but only one else -- and the else must be last.
You need to either: change all your "else" except the last to "else if", or put plain "if" before the following "else if" statements:
(1)
else if (input2.equals(validName))
{
System.out.println("Ok you made it through username check");
}
(2)
else if (input3.equals(validName))
{
System.out.println("Ok you made it through username check");
}
Your code is not very maintainable. What would you do, if the user got 5 tries? Add some additional if blocks? And what if the user has 10 tries? :-) You see what I mean.
Try the following instead:
Scanner in = new Scanner(System.in);
int tries = 0;
int maxTries = 3;
String validName = "thomsondw";
while (tries < maxTries) {
tries++;
System.out.print("Please enter a valid username: ");
String input = in.next();
if (input.equals(validName)) {
System.out.println("Ok you made it through username check");
break; //leaves the while block
}
}
I'm writing a relatively simple Java program that calculates discounts for shoppers if they have certain vouchers or bonuses. It's working okay, but I have an issue when the program asks the user if they have any vouchers.
If they type "n", they still have to go through the loop as if they responded with "y" once before they can exit. I know it's probably a dumb mistake in there somewhere, but it's been driving me crazy and I'd appreciate a pair of fresh eyes to once it over.
do {
System.out.println("Please enter the total price of the goods");
price = keyboard.nextDouble();
if (price < limits[0] || price > limits[1]) {
System.out.println("Invalid price. Please try again");
validPrice = false;
} else {
validPrice = true;
}
} while (!validPrice);
keyboard.nextLine();
do {
System.out.println("Does the customer have any additional discounts? y/n");
choice = keyboard.nextLine();
if (!choice.matches(inputRegexMatchPattern)) {
System.out.println("Invalid input – please re-enter");
} else if (choice.toLowerCase().charAt(0) == 'y') ;
{
System.out.println(choice);
do {
System.out.println("What type of discount does the customer have? [L]oyalty Card/[D]iscount Voucher");
input = keyboard.nextLine();
if (!input.matches(discountRegexMatchPattern)) {
System.out.println("Invalid input – please re-enter");
}
} while (!input.matches(discountRegexMatchPattern));
if (input.charAt(0) == 'l' || input.charAt(0) == 'L') {
voucherDiscounts += voucherDiscountsArray[0];
System.out.println("Loyalty Card discount accepted");
} else if (input.charAt(0) == 'd' || input.charAt(0) == 'D') {
voucherDiscounts += voucherDiscountsArray[1];
System.out.println("Discount Voucher accepted");
}
}
} while (!(choice.toLowerCase().charAt(0) == 'n'));
You have a semicolon here:
else if (choice.toLowerCase().charAt(0) == 'y') ;
What that means is your loop will continue to execute in spite of the selection you make. Java interprets this if statement as not having any body.
Remove the semicolon and you should be good to go.
The do while construct always performs the content of the loop BEFORE it actually tests the condition.
I guess what you want here is a simple while loop.