User44 User44 - 3 months ago 12
Java Question

Illegal start of expression in Java AFTER ATTEMPTED SOLUTIONS

I am aware that this questions has been asked before, but I still face the same issue after trying to resolve it. Here's the code and an image:

import java.util.Scanner;

class Testing {

public static void main(String[] args){
Greeting();
AgeVerification();
Calculator();
}


static void Greeting(){
System.out.println("Hey. I'm Java, you are...?");
Scanner getname = new Scanner(System.in);
String name = getname.next();
System.out.println("Nice to meet you "+name+".\n");
}


static void AgeVerification(){
System.out.println("How old are you?");
Scanner getage = new Scanner(System.in);
Int age = getage.next();
if(age => 18){
System.out.println("Access granted, go ahead.");
}
else {
System.out.println("Access denied, you're still a minor.");
}
}


static void Calculator(){
System.out.println("Now lets do some maths. Do you want to add, subtract, multiply, or divide?");
Scanner getoperation = new Scanner(System.in);
String operation = getoperation.next();
if(operation == "add" | operation == "Add"){
System.out.println("Which two numbers would you like to add? Enter them separately.");
}
}

}


https://ctrlv.cz/3JDJ

I originally had the three methods below the main listed as public, but removed the "public" attributes only to encounter the same issue. I am new to Java programming, and appreciate the help.

Answer

There's a couple of problems with your code.

First, on this line:

Int age = getage.next();

To declare an integer, use the int type. Also, you probably want to use nextInt() instead of next().

Next, this check is the wrong way around:

if(age => 18){

It should be if (age >= 18){.

And finally, in this line:

if(operation == "add" | operation == "Add"){

| is not doing what you think it is here, you should use ||. As pointed out in the comments, you should check string equality using the equals() method.

    if(operation.equals("add") || operation.equals("Add")){

Finally, and this is just nitpicky, but if you wanted to you could change this if-statement to just check:

if (operation.equalsIgnoreCase("add")) {

Hope this helped!