Java- Syntax error on token "!=", Name expected after this token - java

I'm trying to make a simple calculator and keep on getting the error in the title when I try to make it show "error" if the user doesn't enter one of the given types of operation.
import java.util.Scanner;
public class experiments {
public static void main(String args[]) {
Scanner userInput = new Scanner(System.in);
String operation;
double fNum, sNum, ans;
//select type of operation
System.out.println("Type addition, subtraction, multiplication, or division, then press enter");
operation = userInput.nextLine();
if (operation!=("addition","subtraction","multiplication","division")) {
System.out.println("error");
}
//enter numbers
System.out.println("Enter first number");
fNum = userInput.nextDouble();
System.out.println("Enter second number");
sNum = userInput.nextDouble();
//calculate
if (operation.equals("addition")) {
ans=fNum + sNum;
}
else if (operation.equals("subtraction")) {
ans=fNum - sNum;
}
else if (operation.equals("multiplication")){
ans=fNum * sNum;
}
else if (operation.equals("division")) {
ans=fNum/sNum;
}
//print answer
System.out.println("The answer is ");
System.out.println(ans);
}
}

You can't compare things to a group of objects like this:
operation!=("addition","subtraction","multiplication","division")
Presumably what you want is "if operation is not one of these four things". You've got a few options. The one most like what you have now is to make a new ArrayList (say legalOperations) containing your four legal operations, and then use legalOperations.contains(operation).
However, a cleaner way, which is "better Java", would be to make an enum and use that to do your comparisons.
public enum LegalOperations {
ADDITION,
SUBTRACTION,
MULTIPLICATION,
DIVISION
}
Then you could do your comparisons to your enum (perhaps you'd give the enum a constructor to allow it to have a clear String value for each enum constant, and an isLegalOperation method, for instance).

You should create ArrayList and put value there.
Then you can check if the value exists in the ArrayList.
Like that:
How Arrays.asList(...).contains(...) works?

Java is not capable of understand this command...
if (operation!=("addition","subtraction","multiplication","division")) {
Instead, you need to check each one individually...
if (!"addition".equals(operation) &&
!"subtraction".equals(operation) &&
!"multiplication".equals(operation) &&
!"division".equals(operation)) {
// Handle error...
}

if (operation!=("addition","subtraction","multiplication","division")) is incorrect comparison in Java. Use switch statement if you are using Java 7 or string.equals method with multiple if statements.

You can use the contains method like this:
String[] operations = {"addition","subtraction","multiplication","division"};
if(!operations.contains(operation)) {
...

I think you can rewrite the same as
if (!( operation.equals("addition") || operation.equals("subtraction") ||
operation.equals("multiplication") || operation.equals("division"))) {
System.out.println("error");
}

There is one more Easy way of doing it which involves writing less
as you have an array of Strings, Declare it as an array
String [] operations = {"addition", "subtraction", "multiplication", "division"};
then use this to check
if(!Arrays.asList(operations).contains(operation)) {
System.out.println("error");
}

Related

What's a better or more standard way to perform this function?

I am a java beginner, and in this particular problem I practiced making a program that converts any given string to lowercase string. Is there a a better way to achieve this goal in java (in terms of design)?
Also, how does the "else" (after "else if") catches or waits for me to make an input. Somehow that part does not make sense to me, even though I achieved what I wanted. How is the value of "ans" from input transferred to the entire loop and used until the loop is closed?
After many attempts and failures, I used a separate method for the conversion part. My second question is a bit too complicated to be researched.
import static java.lang.System.out;
import java.util.Scanner;
public class MyClass {
public static Scanner s = new Scanner(System.in);
public static String ans;
public static void main(String args[]) {
Conversion();
do {
ans = new String(s.nextLine());
if (ans.equalsIgnoreCase("Y")) {
Conversion();
} else if (ans.equalsIgnoreCase("N")) {
out.println("Thank you for using this program!");
break;
} else {
out.println("Invalid entry!");
out.println("Would you like to convert another string?\n(Please type 'Y' for yes, or 'N' for no.)");
}
} while (ans != "N");
}//END MAIN
public static void Conversion() {
out.println("Please enter string to be converted to lowercase: ");
String str = new String(s.nextLine());
out.println("Your new string is: " + str.toLowerCase());
out.println("Would you like to convert another string? (Y/N)");
}
}
I notice a few issues; Conversion looks like a class-name (Java naming convention would be conversion) and ans != "N" is using == instead of .equals - and wouldn't ignore case (!ans.equalsIgnoreCase("N")). Globals (e.g. static) are bad (pass the Scanner to the methods that need it), and the static import just makes the code more difficult to reason about (in my opinion). Your current loop doesn't really follow a conventional form, I would extract the prompt and loop for "another" conversion to a new method and if you must print a thank you I'd do so after the "main loop". Something like,
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
do {
conversion(sc);
} while (another(sc));
System.out.println("Thank you for using this program!");
}
public static void conversion(Scanner s) {
System.out.println("Please enter string to be converted to lowercase: ");
System.out.printf("Your new string is: %s%n", s.nextLine().toLowerCase());
}
public static boolean another(Scanner s) {
while (true) {
System.out.println("Would you like to convert another string? (Y/N)");
String ans = s.nextLine();
if (ans.equalsIgnoreCase("Y")) {
return true;
} else if (ans.equalsIgnoreCase("N")) {
return false;
}
System.out.println("Invalid entry!");
System.out.println("(Please type 'Y' for yes, or 'N' for no.)");
}
}
Answering your first question:
There are many design patterns and practices so many people can argue what I would recommend you to do. It's basically the same for all programming languages. Let's take your function "Conversion". The name itself says that you use it to convert stuff. Not to display, not to prompt - to convert. In this case, the only actual thing it should do is to convert upperCase to lowercase. In fact, you might want to specify what type of conversion it has in the name of the function (convertToLowerCase?). In fact, in Java, we use lowerCamelCase for all function names and UpperCamelCase for classes.
If you accept my previous suggestion, you could break the Conversion function into multiple ones like promptUserForInput, WrongInputHandler and so forth.
If I understood your second question correctly, you wonder about the way the code executed and how the variable ans is transferred further into the loop. Let's take a look at your code and what variables do:
You initialize your variable in the class MyClass by making it accessible to all methods in the class;
You prompt the user for the input to assign to this variable inside the do..while loop with this line ans = new String(s.nextLine()); which saves the value of the variable and, again, which can be accessed inside the whole class so its value is changed.
It goes into the if..else if...else statement. The way it works, it goes line by line - if the first if-statement fails, it goes on until it finds a truthy statement and it doesn't go any further. In your case, if the ans is not equal to either y/Y/ it will go to else if statement and if it's not n/N, it will go to else (so basically whatever except y/Y/n/N) and will be executed. After that, it jumps into the while (ans!= "N"); line where it compares your class-member variable ans and if it's not equal to "N" it starts over the loop right after the do{ part until you type in the "N".
I hope that makes sense. Whenever the program is asking you for input, it does not execute code further but is stuck until you provide any input. The value from input itself isn't passed throughout the loop and the program. The reason why you can use it because you created a higher-scope variable ans where you saved the result of your input.
IMPORTANT: if you've declared the ans inside the do..while loop, you would've not been able to have accessed it in the while (ans...) because it will 'die' right before the curly brace between do { ...here} while(). If you want to learn more about the scope and variables in general, you can read this article.
Here is my code example:
public static void main(String args[]) {
//declare before entering the loop to have higher scope
String ans = "y";
do {
//we get the given string to convert from the user
String str = promptForString();
//we convert the string
str = converseStringToLowerCase(str);
//display the string (could use another function for that: easier to debug and locate problems and in bigger projects)
out.println("Your new string is: " + str);
//prompt user for respond to continue or not
ans = promptForContinue();
handleResponse(ans);
} while (!ans.equals("n"));
}//END MAIN
//prompts user for an input string
public static String promptForString() {
out.println("Please enter string to be converted to lowercase: ");
String str = new String(s.nextLine());
return str;
}
//converts any given string to lower case
public static String converseStringToLowerCase(String str) {
return str.toLowerCase();
}
//is used to prompt user for reply
public static String promptForContinue() {
out.println("Would you like to convert another string? (Y/N)");
String str = new String(s.nextLine());
//is good to make if...else statements easier - it will always be lower case (or upper if you prefer)
return str.toLowerCase();
}
//easier to locate other response scenarios
public static void handleResponse(String response) {
if (response.equals("n")) {
out.println("Thank you for using this program!");
//it's not a very good practice to innaturally break loops. Use input for that in while(..) statement
// break;
} else if (!response.equals("y")) {
out.println("Invalid entry!");
out.println("Would you like to convert another string?\n(Please type 'Y' for yes, or 'N' for no.)");
}
}

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.
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!
In AgeVerification(), change
Int age = getage.next();
to
int age = getage.nextInt();
Next there is no => opertor in java. So to compare the age change
if(age => 18){
System.out.println("Access granted, go ahead.");
}
to
if(age >= 18){
System.out.println("Access granted, go ahead.");
}
Also, you can " | " refers to bitwise OR. Whereas you want to check if the string equals add or Add. So change it to
if(operation.equalsIgnoreCase("add")){
System.out.println("Which two numbers would you like to add? Enter them separately.");
}
You should change this:
Int age = getage.next();
to:
int age = getage.nextInt();
Case is important in Java, and while int is a built-in primitive type, Int has no meaning unless you define your own class called Int (which it seems you have not done). That will get rid of the "Illegal start of expression error". However, it will give you a different error because Scanner#next() returns a String and you want an integer value. Thus, you should be calling nextInt() instead of next().
Also, as others have pointed out, the integer comparison operator you want to use in the next line is >= (think "greater than or equal"); there is no => operator in Java.

Can someone explain this if statement that I have going and tell me what is wrong?

I am a beginner to programming (literally two days new), and I am having an issue. I am trying to make a VERY basic calculator, where the user inputs the first number, the operation (only +, -, *, and /), and then the second number. I'm having trouble getting the input of the operation to determine what the answer will be with the if statements, so can someone please explain it using very simple terminology?
package learn;
import java.util.Scanner;
class calculator{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
double termOne, operation, termTwo, answer;
System.out.println("Enter first term: ");
termOne = input.nextDouble();
System.out.println("Enter operation (Valid operations are : ");
operation = input.nextDouble();
System.out.println("Etner second term: ");
termTwo = input.nextDouble();
if (operation == add) {
answer = termOne + termTwo;
System.out.println(answer);
} else if (operation == subtract) {
answer = termOne - termTwo;
System.out.println(answer);
} else if (operation == divide) {
answer = termOne / termTwo;
System.out.println(answer);
} else (operation == multiply) {
answer = termOne * termTwo;
System.out.println(answer);
}
}
}
Okay so both Tunaki and Pshemo are right but I will try to point out your problems on a more simplified level.
Your first mistake is the way you declare your variable "operation". You use the datatype double (which is for floating point numbers, kinda) but later want it to hold a string.
Secondly, I'm assuming you are checking if the user typed in "add" to then add the two numbers. However there are several problems here:
You are not using quotes for your string so Java is looking for a variable called add rather than the actual "add".
String comparison in java does (mostly) not work this way. A better way to compare two strings is to use String.equals("otherString"). In your example that would be if(operation.equals("add"))
I hope this helps... Oh and I welcome anyone to format my post, I'm on a mobile and it's a pain in the a**

Checking Multiple strings with if, else if statement

I am creating a simple lift programme in java. I want to to have four users that are allowed to use the lift i have already got it working for 1 but i cant figure out how to check multiple strings using the one if statement.
import java.util.Scanner;
public class Username
{
public static void main (String[]args)
{
Scanner kb = new Scanner (System.in);
String name;
System.out.println("Enter your name");
name = kb.nextLine();
if (name.equals("barry "))
System.out.println("you are verified you may use the lift");
Scanner f = new Scanner(System.in);
int floor;
System.out.println("What floor do you want to go to ");
floor = f.nextInt();
if (floor >7)
System.out.println("Invalid entry");
else if (floor <= 7)
System.out.println("Entry valid");
}
}
Check out this related question:
Test if a string contains any of the strings from an array
Basically, put the names into an Array of strings, and compare the name entered with each name in the Array.
Use the OR symbol "||" or "|".
Such as if (name.equals("barry ") || name.equals("sara"))
For future reference the difference between the two is "||" short circuits. In this situtation, if barry is the name then the second statement for checking against sara will never be executed.
basically, you need an "Or" gate, this would work:
if(name.equals("name1")||name.equals("name2")||name.equals("name3"))
etc...

How do I set the statement if to read letters instead of numbers?

"if" statement only allows to put numbers in it.
Is there a way to make it read letters?
I'm only in my fifth lesson of Java (I study in a uni and the teacher is very slow but I want to learn things fast)
for example.
import java.util.Scanner;
public class Java {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
int answer1;
System.out.println("Do you like Java?");
answer1 = scan.nextInt();
if (answer1 == yes)
System.out.println("Cool ~");
else
System.out.println("Ehh...");
}
}
I want to put "yes" instead of the number 5.
So if the user types "yes" it will print "correct".
P.S. I didn't find a clear answer to that in the search engine.
It's not a duplicated thread as I'm trying to find a clear answer to that.
I need a detailed explanation about it.
I'm still a beginner, using those "high tech java words" won't help me.
You need to modify your program so that your scanner to reads a String instead of an int. You can do that as:
import java.util.Scanner;
public class Java {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
String answer1;
System.out.println("Do you like Java?");
answer1 = scan.next();
if (answer1.equals("yes"))
System.out.println("Cool ~");
else
System.out.println("Ehh...");
}
}
I used next() for this since we only want one word (token), but be aware that there are other options for reading Strings.
Notice also that I've changed the test in the condition because it's now a String. See this answer for more on comparing Strings.
You need to modify your program so that your scanner to reads a String instead of an int. You can do that as:
import java.util.Scanner; public class Java {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
String answer1;
System.out.println("Do you like Java?");
answer1 = scan.next();
if (answer1.equals("yes"))
System.out.println("Cool ~");
else
System.out.println("Ehh...");
} }
I used next() for this since we only want one word (token), but be aware that there are other options for reading Strings.
Notice also that I've changed the test in the condition because it's
now a String. See this answer for more on comparing Strings.
Ok, what if you want the program to read both words and numbers:
Here's my program (more in depth, when you see the full thing), but this is one of 5 parts (that look a like) where I'm having the program...
public static void Gdr1() {
try {
System.out.print("[Code: Gdr1] Grade 1: %");
Scanner gdr1 = new Scanner(System.in);
Z = gdr1.next();
Z = Double.toString(Grd1);
Grd1 = Double.parseDouble(Z);
if ((Grd1<100)&&(Grd1>=5)) {
Gdr2();
} else if ((Grd1>=100)&&(Grd1<125)) {
System.out.println(" System> Great Job "+Stu+"!");
Gdr2();
} else if (Grd1<5) {
System.out.println("I'm sorry, the lowest grade I am allowed to compute is 5...");
Gdr1();
} else if (Z.equalsIgnoreCase("restart")) {
restart01();
} else {
System.out.println("("+Z+") cannot be resolved in my system...");
Gdr1();
}
} catch (Exception e) {}
}
Now everything works in the program, besides for when the End-User's input = "restart", I know some of the code in the program seems complicated, but it does work (most of it), can anyone help me try to figure this out, its for my portfolio at my school due latest by 1/25/2017 # 11:59 pm.
The things like Z (constant String), ""+Stu+"" (variable input), and [Code: Gdr1] are there for a purpose...

Categories

Resources