I am having issues calling the Severity.LOW variable from the Enum I created. I have tried importing it, wrapping it in a class, and importing the wrapper class. I cannot figure out what im doing wrong.
Here is the Main.java
package allergyProblem;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter First Name:");
String firstName = sc.nextLine();
System.out.println("Enter Last Name:");
String lastName = sc.nextLine();
System.out.println("Enter Phone Number:");
String phoneNumber = sc.nextLine();
System.out.println("Enter E-Mail Address:");
String emailAddress = sc.nextLine();
System.out.println("Enter Street Name:");
String streetName = sc.nextLine();
System.out.println("Enter City:");
String city = sc.nextLine();
System.out.println("Enter State:");
String state = sc.nextLine();
System.out.println("Enter Zipcode:");
int zipCode = sc.nextInt();
Address adr = new Address(streetName, city, state, zipCode);
Allergy allergy = new Allergy("coughing", "Arzoo", Severity.LOW, "Regular cough");
List<Allergy> allergies = new ArrayList<Allergy>();
allergies.add(allergy);
Patient patient = new Patient(firstName, lastName, phoneNumber, emailAddress, adr, allergies);
System.out.println(patient);
}
}
Here is the Enum im trying to access
package allergyProblem;
import java.util.*;
public enum Severity {HIGH, MEDIUM, LOW}
This is the error i get when trying to compile Main.java.
Severity.java which is the Enum, compiled properly without any errors.
Main.java:43: error: cannot find symbol
Allergy allergy = new Allergy("coughing", "Arzoo", Severity.LOW, "Regular cough");
^
symbol: variable LOW
location: class Severity
1 error
The error is telling you that Severity as a type is found (ignore that it says 'class Severity', it does that even if javac knows it is an enum, unfortunately), but that it does not contain the variable LOW.
There's only one explanation for that:
The Severity that javac is using here is NOT the result of compiling public enum Severity {HIGH, MEDIUM, LOW}. Check if there are other classes named Severity in your classpath in that package, or in the package that contains your Main.java file. Then, check that you properly (re)compiled Severity.java, because a stale class file can also mess with it. Then check that you don't have some old stale build result on the class path.
NB: Note that your code won't work even after fixing this, you're abusing Scanner. The right way to use scanner is to either only call .nextLine, or to never call it, with a strong preference for never calling it. If you want to read lines, after making the scanner, immediately run scanner.useDelimiter("\r?\n"); in order to tell the scanner that you want one token per enter, not one token per whitespace (this is a good idea in any case when taking command line input, the fact that scanner defaults to whitespace as delimiter is a dumb error that cannot be fixed due to backwards compatibility concerns. It's a good habit to get into: Making a scanner? Immediately set the delimiter). Then, you can just call next() instead of nextLine() for a lines worth of data, and then it will work - your take will not work due to well known issues mixing nextLine and nextAnythingElse.
Related
I'm trying to get a program together that reads integers that a user inputs. I've been reading about the scanner class which seems to be the most common way to do this in java. However when I copy+paste the examples given on sites like this one I get some kind of error that I have no idea how to fix. Which is frustrating because all the stuff posted is supposed to be completed code that shouldn't have problems!
An example of some code that's supposed to work:
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] arguments){
Scanner input = new Scanner(System.in);
String username;
double age;
String gender;
String marital_status;
int telephone_number;
// Allows a person to enter his/her name
Scanner one = new Scanner(System.in);
System.out.println("Enter Name:" );
username = one.next();
System.out.println("Name accepted " + username);
// Allows a person to enter his/her age
Scanner two = new Scanner(System.in);
System.out.println("Enter Age:" );
age = two.nextDouble();
System.out.println("Age accepted " + age);
// Allows a person to enter his/her gender
Scanner three = new Scanner(System.in);
System.out.println("Enter Gender:" );
gender = three.next();
System.out.println("Gender accepted " + gender);
// Allows a person to enter his/her marital status
Scanner four = new Scanner(System.in);
System.out.println("Enter Marital status:" );
marital_status = four.next();
System.out.println("Marital status accepted " + marital_status);
// Allows a person to enter his/her telephone number
Scanner five = new Scanner(System.in);
System.out.println("Enter Telephone number:" );
telephone_number = five.nextInt();
System.out.println("Telephone number accepted " + telephone_number);
}
}
Instead of the program running, it gives me two errors.
On the the line public class ScannerDemo { it gives me this error:
Illegal modifier for the local class ScannerDemo; only abstract or final is permitted
On the next line public static void main(String[] arguments){ I get this error:
The method main can not be declared static; static methods can only be declared in a static or top level type.
I have tried this with many different forms of scanners that are supposed to be all ready to go and get errors every time. What am I doing wrong? How can I fix it?
I am using Processing 3.
Please understand the difference between Java and Processing. Processing is its own language and editor with its own syntax rules, and you can't just copy-paste random Java code and expect it to work. You have to understand how Processing works, and then add code in a way that works in Processing.
Assuming you're using the Processing editor, then your main sketch file should not contain just a class, and it definitely shouldn't contain a main() method. It should contain a setup() and draw() function instead.
If you really want to use a class, then get rid of your main() method, encapsulate your logic in a function inside your class, and then add a setup() or draw() function that uses the class.
Or better yet, stop using a class and just use Scanner in your Processing code.
If you still can't get it working, please post a MCVE in a new question post, and we'll go from there. Good luck.
I believe as #Hovercraft has mentioned you just need this code in a file called ScannerDemo.java, Were guessing you have it in different file name.
Your class name and file name must be same. This is decision to first error.
public static void main(String[] arguments){
isn`t working because first error.
Trying to test my java "skills" and make a text based game--except i can't get the user input. i already importd the scanner class, and it works well w/ integers so idk what the problem is quite frankly. whenever i try to compile it, the lines containing "String name = scanner.next();" show up with a 'Scanner cannot be resolved' error.
import java.util.Scanner;
public class CH1 {
public static void main (String args[]) {
Scanner s= new Scanner( System.in);
int answer;
System.out.println ("You're in grave danger, but first, I must know your name. Will you tell me? ");
answer = s.nextInt();
if (answer == 1) {
System.out.println ("I respect your decision, but I'll need to know your name
if you turn up dead, unless you want to have a one man funeral.");
System.out.println ("What's your name?");
String name = scanner.next();
}
else if (answer == 2) {
System.out.println("Great, now what's your name?");
String name = scanner.next();
}
else {
System.out.println(" Huh? I didn't really get that. (1 for no, 2 for yes.)");
}
}
}
You named that scanner s first!
You can't just use a different name later on!
So simply change the scanner variable name to "scanner" and keep using that name.
Beyond that: Single character variable names are something you almost never do (except for index values in for loops). The point is: variable names should say something about the thing they denote. "s" says nothing!
I'm trying to create a videoStore with the basic CRUD operation. For creating each movie I need to read the title, the year and the gender as below:
System.out.print("name: ");
name = in.nextLine();
System.out.print("year: ");
year = in.nextInt();
in.nextLine();
System.out.print("gender: ");
gender = in.next();
When I enter the addMovie option, I get this print on the console
(name: year:)
Can someone explain to me why it happens as above?
Here is the rest of the method:
static ArrayList<Movie> movies = new ArrayList<Movie>();
static Scanner in = new Scanner(System.in);
public static void InserirFilme() {
String name;
int year;
String gender;
boolean existe = false;
System.out.print("name: ");
name = in.nextLine();
System.out.print("year: ");
year = in.nextInt();
in.nextLine();
System.out.print("gender: ");
gender = in.next();
Movie movie = new Movie(name, year, gender);
for(Movie m: movies)
{
if(movie == m)
{
existe = true;
}
}
if(!existe)
{
movies.add(movie);
}
else
{
System.out.println("the movie already exists in the videoStore");
}
}
Calling next does not remove the line break, which means the next time you call InserirFilme the call to read the name can complete immediately. Use nextLine.
System.out.print("gender: ");
gender = in.nextLine();
(You probably mean "genre" instead of "gender" though)
Also, as mentioned in the comments, this check will never succeed:
if(movie == f)
You run this method in loop (right?)
The first call reads input correctly, but it leaves the linebreak in System.in after the last in.next().
On next call the name: is printed, then scanner reads an empty string from System.in because the linebreak already exists here.
And after thet the year: is printed on the same line because no new linebreaks are entered.
So you just have to insert another in.nextLine() after reading gender (or genre :) )
Or use nextLine() for read genre instead of next(), because genre might have more than one word.
But there are some disadvantages with using fake nextLine() to 'eat' linebreak - there might be another text which you doesn't process. It's a bad practice - to loose the data user entered.
It is better to read all the data from line, then validate/parse it, check isn't there some extra data, and if the data is invalid show notification and let him try to enter the right value.
Here are some examples how to deal with user input manually - https://stackoverflow.com/a/3059367/1916536. This is helpful to teach yourself.
Try to generalize user input operations:
name = validatedReader.readPhrase("name: ");
year = validatedReader.readNumber("year: ");
genre = validatedReader.readWord("genre: ");
where ValidatedReader is a custom wrapper for Scanner which could use your own validation rules, and could gently re-ask user after a wrong input.
It could also validate dates, phone numbers, emails, url's or so
For production purposes, it is better to use validation frameworks with configurable validation rules. There are a lot of validation frameworks for different purposes - Web, UI, REST etc...
when i enter the addMovie option, i get this print on the console (name: year:) can someone explain me why it happens i already searched a lot and i cant understand why :S
The way i understood your question is that you are getting the output (name: year: ) in a line and want it in seperate lines? In that case you simply can use System.out.println(String); instead of System.out.print(String). On the other hand you can also use "\n" whenever you want a linebreak within a String. Hope i could help you :).
Edit: If this was not an answer to your question, feel free to tell me and clarify your question :)
For String name you are using in.nextLine(); i.e the data entered on the entire line will be added to name string.
After "name: " is displayed, enter some text and press enter key, so that the year and gender fields will get correct values.
The code written is correct but you are not giving appropriate input through the scanner.
I recommend to use
String name = in.next();//instead of String name = in.nextLine();
You may instantiate Scanner Class differently for String and Integer type input. It works for me :)
Example:
static Scanner in1 = new Scanner(System.in);
static Scanner in2 = new Scanner(System.in);
Please use nextLine() for 'name' and 'gender'. It may contain more than one word. Let me know if it works.
Example:
System.out.print("name: ");
name = in1.nextLine();
System.out.print("year: ");
year = in2.nextInt();
System.out.print("gender: ");
gender = in1.nextLine();
I need to use the following in my program and not sure how to get it to work.
Ask the user to enter their name(String variable) and age (int
variable).
Also I need to display their name, age and a welcome message using a printf statement.
This is what I have so far. Can anyone help me? Please
package myfirstprogram;
import java.util.Scanner;
public class MyFirstProgram {
public static void main(String[] args) {
String name;
int age;
Scanner sc = new Scanner(System.in);
System.out.printf("Please Type Your Name then press the Enter key.");
System.out.printf("Please Type Your Age then press the Enter Key.");
name = sc.next();
age = sc.next();
System.out.printf("Hello. My name is " + name + ", I am pleased to meet you.");
System.out.printf("Your Age is " + age);
System.out.printf("Hello and Welcome, " + name);
}
}
Did you even try to compile your code to see what errors are in it?
Are you using a GUI program (like Eclipse, et al.) to compile your code? Or javac on the command-line? Either way your code compiles with the error:
javac myfirstprogram/MyFirstProgram.java
myfirstprogram/MyFirstProgram.java:17: incompatible types
found : java.lang.String
required: int
age = sc.next();
^
1 error
This is saying that, as shmosel and others rightly pointed out in the comments, Scanner.next() returns a string, which is fine when you are getting the user's name input that is of type String, but this won't work for age input as you have defined age as an int.
So to "get it to work" you need to do as the compiler instructs which is to change the line 17 to:
age = sc.nextInt();
Then your program should "work" as you expect.
Hope this helps!
I would try something like this:
public static void main(String[] args) {
String name;
int age;
Scanner sc = new Scanner(System.in);
System.out.printf("Please enter your name");
name = sc.next();
System.out.printf("Please enter your age");
age = sc.nextInt();
System.out.printf("Hello " + name + "\nYour age is: " + age);
sc.close();
}
The reason this code works is because, like others have said, the age variable is an integer, not a String (what sc.next() returns). Also, it is much easier to separate both questions because that way the program will easily distinguish what is being inputted as the age and the name.
If you want it to be a bit more fail proof, you can throw an exception that will check to see that the user did not input a String as an integer.
A good place to see how libraries work in Java is both Stackoverflow and the Java API website (depending on your version of Java there are different sites)
Java™ Platform, Standard Edition 7
API Specification
Java™ Platform, Standard Edition 8
API Specification
If you need help with anything else in Java and the above is complicated, try these websites:
Tutorials Point - Java
Best of luck!
I'm using eclipse for this project. I've tried compiling in command prompt but the same problems happen. The scanner works until I get to "phone" and then it just seems to skip the user input and prints everything else on the same line.
I expect to store the users input into the assigned variables, and then print them out on separate lines.
I added sc.close; to see if that would help but it didn't. Some help would be greatly appreciated. Also my variable "address" isn't completely printed out.
I think I may be using Scanner incorrectly?
import java.util.Scanner;
public class ContactDisplay {
public static void main(String[] args) {
//Write a program that displays your name, address, and telephone number;
//create scanner
Scanner sc = new Scanner(System.in);
//Creates the variables;
String name;
String address;
String phone;
//Asks for name
System.out.print("What is your name? ");
//stores the name
name = sc.next();
//Asks and stores the address
System.out.print("What is your address? ");
address = sc.next();
//Asks and stores the phone number
//PROBLEM IS BELOW
System.out.print("What is your phone number? ");
phone = sc.next();
//Prints everything out
System.out.println(name);
System.out.println(address);
System.out.println(phone);
}
}
Here is a screenshot:
You should use 'sc.nextLine()' to scan string values, and you should use 'sc.nextInt' to scan integer values. If you press ctrl and space keys while typing a bunch of code it shows you the possible things you may want to write.