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!
Related
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'm not the best programmer and am quite new to it. I've been trying for hours to get this program correct but I can't seem to come up with a way to make it work out the way I'd like to. Here's what I want to do:
Write a program that prompts a user for their name and then displays "Hello, [Name Here]!"
If the user does not enter anything but pressed Enter anyways, you should re-prompt for the user's name. This flow should look like the following:
Whats is your name?
Please Enter your name:
Please Enter your name: Programming Practice
Hello, Programming Practice!
Here's how I'm thinking of the program before I start writing anything in my IDE:
Ask the user for their name
Give them a chance to enter their name
If their entry is not in name format, give them output saying incorrect format
Give them a chance to enter in proper format
Repeat steps 4 and 5 as many times as it takes for them to enter proper format
Print "Hello, [Name Here]!"
END
Here's what I've got so far:
package lol;
import java.util.Scanner;
public class Whatever {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.printf("What is your name?\n");
String name = sc.nextLine();
if (name != "Programming Practice")
{
System.out.println("Please enter a valid name");
String name2 = sc.nextLine();
System.out.println("Hello, " + name2 );
}
else
{
System.out.println("Hello, " + name );
}
}
}
Right now the output I'm getting regardless of my entries are:
What is your name?
Please enter a valid name
Hello,
You can throw the sc.nextLine() into a while(true) loop and break out when you get a result you deem valid.
String name = "";
while(true) {
name = sc.nextLine();
if (name.equals("Programming Practice")) {
System.out.println("Hello, " + name);
break;
} else {
System.out.println("Please enter in the correct format");
continue;
}
}
A better way of approaching this problem would be by using do-while loop.
do {
// Your processing
} while (checkCondition());
The logic is based on the idea that the user will be prompted to enter details at least once.
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.
i am a beginner in java and i am doing practiceit questions off the internet.I tried attempting the question but i dont understand the error.
Write a method called processName that accepts a Scanner for the console as a parameter and that prompts the user to enter his or her full name, then prints the name in reverse order (i.e., last name, first name). You may assume that only a first and last name will be given. You should read the entire line of input at once with the Scanner and then break it apart as necessary. Here is a sample dialogue with the user:
Please enter your full name: Sammy Jankis
Your name in reverse order is Jankis, Sammy
public static void processName(Scanner console) {
System.out.print("Please enter your full name: ");
String full=console.nextLine();
String first=full.substring(0," ");
String second=full.substring(" ");
System.out.print("Your name in reverse order is: "+ second + "," + first);
}
Maybe i will go about explaining my code.So i try to break the two words apart.So i use substring to find the both words and then i hardcode to reverse them.I think the logic is right but i still get these errors.
Line 6
You are referring to an identifer (a name of a variable, class, method, etc.) that is not recognized. Perhaps you misspelled it, mis-capitalized it, or forgot to declare it?
cannot find symbol
symbol : method substring(int,java.lang.String)
location: class java.lang.String
String first=full.substring(0," ");
^
Line 7
You are referring to an identifer (a name of a variable, class, method, etc.) that is not recognized. Perhaps you misspelled it, mis-capitalized it, or forgot to declare it?
cannot find symbol
symbol : method substring(java.lang.String)
location: class java.lang.String
String second=full.substring(" ");
^
2 errors
33 warnings
public static void processName(Scanner console) {
System.out.print("Please enter your full name: ");
String[] name = console.nextLine().split("\\s");
System.out.print("Your name in reverse order is: "+ name[1] + "," + name[0]);
}
Of course it only works if the name has 2 words. For longer names you should write a method which would reverse an array
Take a look at the documentation for the substring() method. It does not take a string as its second parameter.
String first=full.substring(0," ");
String second=full.substring(" ");
What you may want instead is the indexOf() method. First find the index of the space character. Then find the substring up to that point.
int n = full.indexOf(" ");
String first=full.substring(o, n); //gives the first name
As per Java API, substring() accepts either one int argument like substring(int beginIndex) and two int arguments like substring(int startIndex, int endIndex) but you are calling with String arguments. So you're getting those errors. More info can be found here
String API.
go to here http://docs.oracle.com/javase/6/docs/api/java/lang/String.html and read to understand.
public class ex3_11_padString {
public static void main(String[] args) {
System.out.print("Please enter your full name: ");
String f_l_Name = console.nextLine();
String sss[] = f_l_Name.split(" ", 2);
System.out.print("Your name in reverse order is " + sss[1] + ", " + sss[0]);
}
}