Illegal start of expression in Java AFTER ATTEMPTED SOLUTIONS - java

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.

Related

How can I take a user's input and use it as an integer?

I am a very new Java user who just installed Eclipse two days ago. I am getting my feet wet by writing a program that ask's the user what grade they got on a test in percentage form and returning back what their grade is in letter form. I was also wondering how I can set this integer in an if-else statement so taht if the test grade is greater than or equal to 90, the program will return A for a grade. So on and so forth until 50 or below which would return an F. So far, all I have is this:
import java.util.Scanner;
public class gradechecker {
public static void main(String[]args) {
Scanner user_input = new Scanner(System.in);
String test_grade;
System.out.println("Enter the grade percentage you received without the percent sign.");
test_grade = user_input.next();
if(test_grade <= 90) {
}
}
}
To grab a integer value from the user, you use .nextInt().
In this case,
test_grade = user_input.nextInt();
test_grade gets the value entered from the user. However, test_grade is declared as a String variable. You'll need to change that to a int.
What August and azurefrog said are correct in terms of one part of your question, you want to use user_input.nextInt() instead of user_input.next() to get an int input from the user.
For the second part of your question, consider the best order to check the input and how to check the input.
I would consider using >= instead. Check for an A first, then B, etc. If something is >= 80 but you've already determined that it's not >= 90, you know it'll be a B. And remember to check if the user entered an invalid number as well. Remember to use if...else if...else to logically join the comparisons, otherwise you could end up with the wrong result.
Edit: As was pointed out, test_grade needs to be an int instead of a String.
public static void main(String[]args) {
Scanner user_input = new Scanner(System.in);
You must use int to get the percentage in integer form
int test_grade;
System.out.println("Enter the grade percentage you received without the percent sign.");
to get an input use input.nextInt... check the http://www.java-made-easy.com/java-scanner.html
test_grade = user_input.nextInt();
//Check for the conditions similar to this
if(test_grade >= 90) {
// assign the grade here
String grade = A;
// print the grade
System.out.println("your grade is"+grade)
}

While not (or equivalent) java

I'm making a program with Java that needs to involve some error checking. I can stop users from entering bad numerical inputs like this (assume the input scanner has already been created):
while (n == 0){
System.out.println("Can't use 0 as a denominator! Please enter a real, nonzero number");
n = input.nextInt();
}
But how do I stop users from entering an invalid string? I can't use !=, because strings can only be compared with the string.equals() method, right? So, is there a while not loop? ie:
while !(string.equals("y") || string.equals("n")){
//here have code
}
Or something of that nature?
While there is no such thing as a while-not loop, you can always invert the condition:
while (!(string.equals("y") || string.equals("n"))){
This is read, "while the string is not equal to "y" or "n"".
You could also apply DeMorgan's identity to rewrite this as:
while (!(string.equals("y")) && !(string.equals("n"))){
which is a bit clearer as "While the string isn't equal to "y" and isn't equal to "n"".
There isn't a while-not instruction, but you can simply negate the condition in a normal while loop. Try this:
while (!string.equals("y") && !string.equals("n"))
Or even better, to guard against the case where the string is null and/or it's in a different case:
while (!"y".equalsIgnoreCase(string) && !"n".equalsIgnoreCase(string))
You almost get it, just change where you position your !
like this:
while (!(string.equals("y") || string.equals("n")))
Why not try regex?
Scanner sc = new Scanner(System.in);
String string = sc.nextLine();
while (!string.matches("(?i)^(?:y|n|yes|no)$"))
{
System.out.println("Invalid input...");
string = sc.nextLine();
}
boolean answer = string.matches("(?i)^(?:y|yes)$");

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...

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

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");
}

Java - appending & passing values

I'm having trouble with passing a string and double to another class because it keeps on crashing at double cost = input.nextDouble();. Also, i was wondering if i am correct with the appending method used in public boolean addPARTDETAILS(String partDESCRIPTION, double partCOST).
For example. If the user enters the parts and cost, i want it to store that in a list and print it out with the cost appended.
Parts used:
brake pads ($50.00)
brake fluids ($25.00)
Note. Assuming that i have declared all variables and the array.
System.out.print("Enter registration number of vehicle");
String inputREGO = input.next();
boolean flag = false;
for(int i=0; i<6; i++){
if(inputREGO.equalsIgnoreCase(services[i].getregoNUMBER())){
System.out.print("Enter Part Description: ");
String parts = input.nextLine();
double cost = input.nextDouble();
services[i].addPARTDETAILS(parts, cost);
//System.out.println(services[i].getregoNUMBER());
flag = true;
}
}if(flag==false);
System.out.println("No registration number were found in the system.");
public boolean addPARTDETAILS(String partDESCRIPTION, double partCOST){
if(partDESCRIPTION == "" || partCOST <= 0){
System.out.println("Invalid input, please try again!");
return false;
}
else{
partCOST=0;
StringBuffer sb = new StringBuffer(40);
String[] parts = new String[50];
for (int i=0;i<parts.length;i++){
partDESCRIPTION = sb.append(partCOST).toString();
}
System.out.println(partDESCRIPTION);
totalPART+=partCOST;
return true;
}
}
it keeps on crashing at double cost = input.nextDouble();.
It is highly unlikely that your JVM is crashing. It is far more likely that you are getting an Exception which you are not reading carefully enough and have forgotten to include in your question.
It is far more likely your code is incorrect as you may have mis-understood how scanner works. And so when you attempt to read a double, there is not a double in the input. I suspect you want to call nextLine() after readDouble() to consume the rest of the the line.
I suggest you step through the code in your debugger to get a better understanding of what it is really doing.
Just to expand a bit on Joop Eggen's and Peter Lawrey's answers because I feel some may not understand.
nextLine doesn't play well with others:
nextDouble is likely throwing a NumberFormatException because:
next, nextInt, nextDouble, etc. won't read the following end-of-line character, so nextLine will read the rest of the line and nextDouble will read the wrong thing.
Example: (| indicates current position)
Start:
|abc
123
def
456
After nextLine:
abc
|123
def
456
After nextDouble:
abc
123|
def
456
After nextLine (which reads the rest of the line, which contains nothing):
abc
123
|def
456
Now nextDouble tries to read "def", which won't work.
If-statement issues:
if(flag==false);
or, rewritten:
if(flag==false)
;
is an if statement with an empty body. Thus the statement following will always execute. And no need to do == false, !flag means the same. What you want:
if (!flag)
System.out.println("No registration number were found in the system.");
String comparison with ==:
partDESCRIPTION == ""
should be:
partDESCRIPTION.equals("")
or better:
partDESCRIPTION.isEmpty()
because == check whether the strings actually point to the exact same object (which won't happen unless you assign the one to the other with = at some point, either directly or indirectly), not just whether the have the same text (which is what equals is for).
Data dependent error.
if(flag==false);
System.out.println("No registration number were found in the system.");
should be (because of the ;):
if (!flag) {
System.out.println("No registration number was found in the system.");
}
And
partDESCRIPTION == ""
should be:
partDESCRIPTION.isEmpty()

Categories

Resources