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.
Related
I get an error from automated JUnit 4 unit testing software that my course instructor uses to automatically check assignments.
We upload our draft code to a cloud program tester which automatically checks and grades the assignments.
This is week 1 of first semester. I've never coded in Java before. And the lessons haven't taught if/else, while, loops, switch etc. so I don't think it's okay to use those (they appear next module.)
I followed a class video tutorial, which doesn't throw any exceptions in the tutorial — so I don't know what's going on.
The unit was on variables, input, printing out, Booleans, operators, and a few things like contains, replace, equals etc.
Note: I am allowed to ask questions on StackOverflow per instructor.
The error is: java.util.NoSuchElementException: No line found
No line number is specified in the testing software where the exception occurs. And since it's not happening in my IDE, I don't know where it is.
Other solutions I've found require while and other methods I'm not supposed to use.
My code (below) runs okay in the VSCODE IDE cloud the school provided.
import java.util.Scanner;
public class ContainsAnyCase {
public static void main(String[] args) {
System.out.println("Type a word:\n");
Scanner userInputWord = new Scanner(System.in);
String word = userInputWord.nextLine();
String wordlc = word.toLowerCase();
System.out.println("Type a sentence:\n");
Scanner userInputSentence = new Scanner(System.in);
String sentence = userInputSentence.nextLine();
String sentencelc = sentence.toLowerCase();
boolean isContains = sentencelc.contains(wordlc);
System.out.println(isContains);
}
}
I'm wondering if anyone can explain why there is an error and if there are ways to fix it or avoid the error without going into the territory of future modules? Also, I'm still learning how to use Stack Overflow appropriately. If I asked my question wrong, please advise how I can improve my question or post. Thank you.
I expected for the program to tell me true/false if the word was in the sentence. In my IDE, it worked. When I uploaded it to the JUnit4, it said java.util.NoSuchElementException: No line found
Here's an example of using just ONE SCANNER as suggested in the comments.
I've also eliminated the second set of variables for lower case; just convert the input directly to lower case and store it in the original variable:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Type a word:\n");
String word = sc.nextLine().toLowerCase();
System.out.println("Type a sentence:\n");
String sentence = sc.nextLine().toLowerCase();
boolean isContains = sentence.contains(word);
System.out.println(isContains);
}
If you need to preserve the exact user input for later, then you can convert to lower case only when you call contains() like this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Type a word:\n");
String word = sc.nextLine();
System.out.println("Type a sentence:\n");
String sentence = sc.nextLine();
boolean isContains = sentence.toLowerCase().contains(word.toLowerCase());
System.out.println(isContains);
}
I have to refer to the users input name in the second method an I don't know if it is possible . What i have right prompts me to enter the name agin. also sorry if this is a dumb question i just started to code.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
getName(keyboard);
getRounds(keyboard,getName());
public static String getName(Scanner keyboard ) {
System.out.print("Welcome to ROCK PAPER SCISSORS. I, Computer, will be your opponent.\n");
System.out.print("Please type in your name and press return: ");
String name = keyboard.next();
System.out.print("\nWelcome " + name + ".");
return name;
}
public static int getRounds(Scanner keyboard, Sting getName) {
System.out.println();
System.out.print("\nAll right"+getname+ "How many rounds would you like to play?\n");
System.out.print("Enter the number of rounds you want to play and press return: ");
int rounds = keyboard.nextInt();
return rounds;
You are returning a reference to a String object from your getName method. Good.
But then you neglected to capture that returned value. Bad.
String name = getName( keyboard );
This is just like what you did when you captured the returned reference from new Scanner(System.in) and stored that reference in a variable named keyboard. (By the way, “keyboard” is not the best name there, “scanner” or “console” is more appropriate.)
Then pass that reference to your getRounds method.
getRounds( keyboard , name );
This is just like what you did when you pass keyboard to the same method.
Before posting here, study The Java Tutorials provided free-of-cost by Oracle Corp.
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.
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 want to take input form user, i am sure my code is right but it don't work at all. Please help is there any thing that i am doing wrong?
`public void edit() throws IOException {
sll.insertAfter();
System.out.println("Enter text: ");
String sen;
sen = keyboard.next();
Object obj = sen;
sll.put(obj);
}
when i execute this an error appears at this line
sen = keyboard.next();
import java.util.*;
public class Example
{
public static void main(String[] args)
{
Edit();
}
public static void Edit()
{
Scanner scan = new Scanner(System.in);
String random;
System.out.print("Please input some text: ");
random = scan.nextLine();
System.out.println("You entered: " + random);
}
}
I don't know what your main method looks like so I can only assume it's empty That being said I can tell you why your current code doesn't work based off of the information you've given us.
Your edit method is not static, and in this situation assuming you've laid out your program simillar to this it must be static as it is in my example.
You've not setup a scanner, or maybe you did outside of your edit method but failed to make it static?
Scanner scan = new Scanner(System.in);
Why are you using Object, if you want to edit the string just use a for loop and substring.
Object
If you provide us with more information, your full code and the error you're getting we can better help you!