I keep getting a syntax error on my last else statement in a string of if, else if , else , and I can't figure out why nor can I find anywhere that tells me what's really confusing is I have done this type of if else statement setup before and never had this problem. I have tried using 2 coding programs (JCreator and Eclipse) but they both give me an error Eclipse gives me a syntax error on the word else and JCreator on the entire statement saying it has no if statement to pair with it, but I have done one like this and didn't need an if statement as is was the final one.
import java.util.Scanner;
public class Hotel
{
public static void main(String[] args)
{
String answer = "";
Scanner keyboard = new Scanner(System.in);
GuestInterface go = new GuestInterface();
PassswordField hotel = new PassswordField();
System.out.println("do you wish do acces the guest interface or the hotel staff interface? ");
System.out.println("Hint: hotel staff -or- guest");
answer = keyboard.nextLine();
if(answer.equalsIgnoreCase("hotel Staff"))
{
System.out.println("Enter username");
answer = keyboard.nextLine();
hotel.readPassword("Enter Passsword \n ");
System.out.print("\n" + "incorect Password");
System.out.println("System will now shut down");
System.exit(0);
}
else
if(answer.equalsIgnoreCase("Guest"))
{
go.run();
}
else //error throws on this statment
{
System.out.println("uncompatible responce");
System.out.println("System ato shut down activated");
System.exit(0);
}
}
}
You wrote a ; at the end of this line:
if(answer.equalsIgnoreCase("Guest"));
So that is a seperate if-statement. Right after that, you start with this:
{
go.run();
}
else //error throws on this statment
{
// (...)
}
Which makes no sense to the compiler, because it didn't start with an if-statement.
Remove the ; to solve the error.
Related
I was trying to build a simple UI where a user enters a username and if the username is xyz then the user will be shown "enter your password". If the password is xyz1234 then the user will be shown "please wait loading..." and the scanner exits. If the username was incorrect, I tried to code it in a way so that it keeps asking for the username until the correct username is entered.
Apparently, the first part of the code works, if the username is xyz, then the code works correctly and displays what i want it to. However if the username is wrong in the first attempt and right in the second attempt, it still continues to show "incorrect username" instead of showing "enter the password".
The code is shown below:
import java.util.Scanner;
class User_Authentication
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter your Username");
String username=in.nextLine();
if(username.equals("xyz"))
{
System.out.println("Enter the Password");
String password=in.nextLine();
if(password.equals("xyz1234"))
{
System.exit(0);
System.out.println("Welcome");
System.out.println("Please wait while the system is loading....");
}
else
{
System.out.println("Your system has been locked for security reasons.");
System.out.println("Please contact an administrator to reset the password");
System.out.println("Any attempt to break in the computer will result in self destruction.");
System.exit(0);
}
}
else
{
do
{
if(username.equals("xyz"))
{
break;
}
System.out.println("Incorrect username");
System.out.println("Please try again");
in.nextLine();
}
while((username.equals("xyz"))==false);
}
}
} ```
Your saying in.nextLine() in your do-while loop, rather than username = in.nextLine()
Replace that and it should work, but overall you're do-while loop needs some work, it's relatively messy. Here's how I would approach it.
do {
System.out.println("Incorrect username");
System.out.println("Please try again");
username = in.nextLine();
} while(username.equals("xyz") == false);
Hi I'm currently working on an assignment where I have to check if the Resident Password matches with the Door password or not, I have to give the user three tries and after that use assert to show to tell the user to try again. this is my code but the assert is not showing any message.
public static void main(String[] args) throws Exception {
// write your code here
Scanner s = new Scanner(System.in);
String P, pas;
int i = 0;
while (i <= 2) {
System.out.println("Enter Resident Password: ");
pas = s.next();
System.out.println("Enter Door Password: ");
P = s.next();
Resident r = new Resident("XYZ", pas);
Door d = new Door(P);
Dorm D = new Dorm();
D.Check();
if (Resident.getPassword().equals(Door.getPassword())) {
System.exit(0);
} else {
i++;
}
}
assert i>2 : "Serious Error – Program has been terminated Try again later";
}
what should I do to get the message using assert.
From https://docs.oracle.com/javase/8/docs/technotes/guides/language/assert.html#enable-disable
By default, assertions are disabled at runtime. Two command-line switches allow you to selectively enable or disable assertions. To enable assertions at various granularities, use the -enableassertions, or -ea, switch
The way assert works with sending an error message is via using ensuring the condition fails in the case you want. For example:
assert <condition> : <message-if-condition-is-false>;
So if you change your assert to use:
assert i<=2 : "Serious Error – Program has been terminated Try again later";
You throw if i is still <=2. If the condition fails, then the message gets thrown as AssertionError.
So with the above, if I execute it as:
javac Example.java
java -ea Example
and give the desired wrong inputs, you would get:
Exception in thread "main" java.lang.AssertionError: Serious Error, Program has been terminated Try again later
Anyhow, you could choose to use System.err and output the error message:
public static void main(String[] args) throws Exception {
// Write your code here
Scanner s = new Scanner(System.in);
String P, pas;
int i = 0;
while (i <= 2) {
System.out.println("Enter Resident Password: ");
pas = s.next();
System.out.println("Enter Door Password: ");
P = s.next();
Resident r = new Resident("XYZ", pas);
Door d = new Door(P);
Dorm D = new Dorm();
D.Check();
if (Resident.getPassword().equals(Door.getPassword())) {
System.exit(0);
} else {
i++;
}
}
// This need not be verified with if (i>2) because the System.exit(0); will exit if the condition satisfies
System.err.println("Serious Error – Program has been terminated Try again later");
}
I am currently going through the Helsinki MOOC for Java OOP and I have hit a snag on one of the questions. I am working on Week 7 Exercise 8 and when I run my code manually I am getting everything to work out okay. However when I run their automated tests I am getting the "NoSuchElementException" error.
It is my understanding from the JavaDoc on this particular error that it is most likely caused by .nextLine() not finding a line to read. What confuses me though is based on the error message, and the location of the exceptions, my use of .nextLine() is working in some places and not others while I am using it in the same manner. I included my class that I am using below. Thanks for the help everyone, and if I overlooked a previous post similar to this I apologize.
import java.util.Scanner;
import java.util.ArrayList;
public class AirportPanel {
private Scanner reader;
private ArrayList<Airplane> airplanes;
private ArrayList<Flight> flights;
public AirportPanel(Scanner reader){
this.reader = reader;
this.airplanes = new ArrayList<Airplane>();
this.flights = new ArrayList<Flight>();
}
public void start(){
System.out.println("Airport panel");
System.out.println("--------------------\n");
while(true){
printMenu();
String input = readString();
if(input.toLowerCase().equals("x")){
break;
}else{
chooseOperation(input);
}
}
}
private void printMenu(){
System.out.println("Choose operation:");
System.out.println("[1] Add airplane" + "\n[2] Add flight" + "\n[x] Exit");
System.out.print("> ");
}
private void chooseOperation(String input){
if(input.equals("1")){
addPlane();
}else{
addFlight();
}
}
private void addPlane(){
System.out.print("Give plane ID: ");
String planeID = readString();
System.out.print("Give plane capacity: ");
String planeCap = readString();
this.airplanes.add(new Airplane(planeID, planeCap));
}
private void addFlight(){
System.out.print("Give plane ID: ");
String planeID = readString();
System.out.print("Give departure airport code: ");
String airport1 = readString();
System.out.print("Give destination airport code: ");
String airport2 = readString();
String airports = airport1 + "-" + airport2;
for(Airplane ap : this.airplanes){
if(ap.getID().equals(planeID)){
this.flights.add(new Flight(ap, airports));
}
}
}
private String readString(){
return this.reader.nextLine();
}
EDIT: Here is a screenshot of the stack trace. I also made a github repo with all of my files in the event that would help more. I am pretty new to coding so excuse the mess I surely made of these files.
EDIT 2: I went to my readString() method and changed my call of .nextLine() to .next() and it fixed my issue. I'm not entirely sure how or why but it is now submitting correctly.
I have an assignment to create an ArrayList of employees, to provide a menu to add, find, and delete employee records. I successfully managed to implement all the functions on my own, but there is a small problem. When I use the find or delete option, the correct record is found or deleted properly but the code goes through the array list of elements and prints out employee not found till the correct record is found, this is unnecessary as it should only print the found record. I have limited experience with coding and I am writing my own code from scratch, please help me with this.
enter image description here
I'VE ATTACHED MY CODE AND THE OUTPUT!
else if (choice.equals("4")) {
System.out.println("Enter Name: ");
String fName = myScanner.nextLine();
System.out.println("Enter Job Name: ");
String fJob = myScanner.nextLine();
for (int i = 0; i < myEList.size(); i++) {
if (myEList.get(i).getName().equals(fName) && myEList.get(i).getJob().equals(fJob)) {
System.out.println("Employee found!");
System.out.println(myEList.get(i).toString());
} else {
System.out.print("Employee not found!");
}
}
} else if (choice.equals("5")) {
System.out.println("Enter Name: ");
String dName = myScanner.nextLine();
System.out.println("Enter Job Name: ");
String dJob = myScanner.nextLine();
for (int i = 0; i < myEList.size(); i++) {
if (myEList.get(i).getName().equals(dName) && myEList.get(i).getJob().equals(dJob)) {
System.out.println("Employee record removed succesfully!");
myEList.remove(i);
} else {
System.out.print("Employee not found!");
}
}
}
This is the Output
Enter Option: 4
Enter Name: arjun
Enter Job Name: tester
Searching...
Employee not found!
Employee not found!
Employee found!
Name: arjun Job Name: tester Weekly Pay: 1200.0
else
{
System.out.print("Employee not found!");
}
This has to be AFTER the for loops are over. You need a found flag. If after the loop is false then print the message
Create a variable to track if employee not found before the loops
In the if statements sent it to false if found.
At the end of the loop check if it is true. Then print the message "Employee not found"
See the sample below
boolean notFound = true;
for(int i=0;i<myEList.size();i++)
{
if(myEList.get(i).getName().equals(fName)&&myEList.get(i).getJob().equals(fJob))
{
System.out.println("Employee found!");
System.out.println(myEList.get(i).toString());
notFound = false;
break;
}
}
if(notFound)
System.out.print("Employee not found!");
Remove this block of code
else
{
System.out.print("Employee not found!");
}
It should work fine after that.
EDIT
This is off topic but when you ask question next time remember to post image of output rather than typing it or posting a link.
And also avoid writing about your coding experience. Just be straight to the point. It just increases the size of question unnecessarily. :)
I am building a parser that recognizes simple commands such as "DOWN.", "UP." and "REP 3.". It must be able to parse the commands rather freely. It should be legal to write
"DOWN % asdf asdf asdf
."
Where % represents a comment and the fullstop signifying end-of-command. This fullstop can be on the next line.
This is all good and well so far, however I'm struggling with the Rep part (represents Repeat.)
I should be able to issue a command as follows:
DOWN .DOWN. REP 3 " DOWN. DOWN.
DOWN . % hello this is a comment
REP 2 " DOWN. ""
This should give me 17 DOWNS. The semantics is as follows for repeat: REP x " commands " where x is the amount of times it shall repeat the commands listed inside the quotation marks. Note that REP can be nested inside of REP. The following code is for handling the DOWN command. The incoming text is read from System.in or a text file.
public void repeat(String workingString) {
if (workingString.matches(tokens)) {
if (workingString.matches("REP")) {
repada();
} else
if (workingString.matches("(DOWN).*")) {
String job = workingString.substring(4);
job = job.trim();
if (job.equals("")) {
String temp= sc.next();
temp= temp.trim();
// Word after DOWN.
if (temp.matches("\\.")) {
leo.down()
// If word after DOWN is a comment %
} else if (temp.matches("%.*")) {
boolean t = comment();
} else {
throw SyntaxError();
}
} else if (job.matches("\\..*")) {
workingString += job;
System.out.println("Confirm DOWN with .");
}
} else if (workingString.matches("\\.")) {
instructions += workingString;
System.out.println("Fullstop");
} else if (workingString.matches("%.*")) {
comment();
} else {
// work = sc.next();
work = work.trim().toUpperCase();
System.out.println(work);
}
} else {
System.out.println("No such token: " + workingString);
}
}
I got a working start on the repeat function:
public String repada(){
String times = sc.next();
times.trim();
if (times.matches("%.*")) {
comment();
times = sc.next();
}
String quote = sc.next();
quote.trim();
if(quote.matches("%.*")){
comment();
quote = sc.next();
}
String repeater = "";
System.out.println("REP " + times + " "+quote);}
However I'm thinking my whole system of doing things might need a rework. Any advice on how I could more easily solve this issue would be greatly appreciated!