Why scanner is not taking input of another string and skepping it? I cant understand, here is my code:
import java.util.Scanner;
public class demo {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String name;
String address;
int age;
System.out.println("Enter your name");
name = s.nextLine();
System.out.println("My name is :" + name);
System.out.println("Enter your age");
age = s.nextInt();
System.out.println("My age is :" + age);
System.out.println("Enter your address");
address = s.nextLine();
System.out.println("My address is :" + address);
}
}
Output :
Enter your namedkMy name is :dkEnter your age22My age is :22Enter your addressMy address is :
It is simple. You can use s.nextLine(); after the age = s.nextInt();
Scanner provides a method nextInt() to request user input and does not consume the last newline character (\n).
System.out.println("Enter your age");
age = s.nextInt();
s.nextLine(); // consumes the \n character
System.out.println("My age is :" + age);
You should close the scanner after the last system out
Place below statement after Statement.out.println("My age is",age);
s.nextLine();
Above statement will do flush, which will clear the cache location in order to accept new input.
Related
I am writing a small program to create a password based off what the user inputs their first middle last name and the birthday and create a password off that and i don't know what i am doing but believe i need multiple scanners but when i do i get this error "variable scan is already defined in method main(string[]) Scanner scan = new Scanner(System.in);"
here is my code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.print("Please Enter your first name: ");
Scanner scan = new Scanner(System.in);
String name = scan.nextLine();
System.out.print("Please Enter your last name: ");
Scanner scan = new Scanner(System.in);
String name = scan.nextLine();
scan.close();
}
}
anythoughs on what could work?
You do not need multiple Scanner objects to accept multiple inputs. You should create one Scanner object and use it to collect as many inputs as you want.
Here is an example:
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your first name: ");
String fname = input.nextLine();
System.out.println("Enter your last name: ");
String lname = input.nextLine();
System.out.println("Enter your age: ");
int age = Integer.parseInt(input.nextLine());
System.out.println("Your details as entered:");
System.out.println("First Name: " + fname);
System.out.println("Last Name: " + lname);
System.out.println("Age: " + age);
}
}
Also some extra resources for you (for Scanner class): https://www.w3schools.com/java/java_user_input.asp
Edit:
replaced next() with nextLine()
replaced nextInt() with Integer.parseInt(input.nextLine());
Thank you very much for the information #Arvind Kumar Avinash. Reference thread: Scanner is skipping nextLine() after using next() or nextFoo()?.
That is because you cannot have two variables with the same name within the same scope.
You should rename one of them ..
Note that you did the same with the String variable name ;)
If you want to keep the same name for both use, then you should not re-declare the variable(s):
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan;
String name;
System.out.print("Please Enter your first name: ");
scan = new Scanner(System.in);
name = scan.nextLine();
scan.close();
System.out.print("Please Enter your last name: ");
scan = new Scanner(System.in);
name = scan.nextLine();
scan.close();
}
}
Notes:
in this example, you will loosen the first value entered by the user. You might want to use an other variable name to store the last name.
there is obviously no reason to instantiate two different Scanner objects with the same InputStream.
This is my code, the while loop does not have an input and the rep variable does not accept an input:
import java.util.Scanner;
public class MixedData {
public static void main(String[] args) {
String rep = "";
do {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your full name");
String name = keyboard.nextLine();
System.out.print("Enter your GPA: ");
double gpa = keyboard.nextDouble();
System.out.println("Name: " + name + ", GPA: " + gpa);
System.out.println("Do you want to enter the data for another student?(y/n)");
rep = keyboard.nextLine();
} // This does not accept input
while (rep.equals("y"));
}
}
Either just add one more keyboard.nextLine() before rep = keyboard.nextLine(); (in order to clear the newline character), or read your double gpa value with:
double gpa = Double.parseDouble(keyboard.nextLine());
Important point to understand here (especially if you're a novice Java developer), about why your code doesn't work, is, that you invoke nextDouble() as a last method on your Scanner instance, and it doesn't move the cursor to the next line.
A bit more details:
All the methods patterned nextX() (like nextDouble(), nextInt(), etc.), except nextLine(), read next token you enter, but if the token isn't a new line character, then the cursor isn't moved to the next line. When you enter double value and hit Enter, you actually give to the input stream two tokens: a double value, and a new line character, the double value is initialized into the variable, and the new line character stays into input stream. The next time you invoke nextLine(), that very new line character is read, and that's what gives you an empty string.
Here's the same code using a while loop instead of do-while. It works the way you want it to.
import java.util.Scanner;
public class MixedData {
public static void main(String[] args) {
String rep = "y";
while (!rep.equals("n")) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your full name: ");
String name = keyboard.nextLine();
System.out.print("Enter your GPA: ");
double gpa = keyboard.nextDouble();
System.out.println("Name: " + name + ",GPA: " + gpa);
System.out.println("Do you want to enter the data for another student?(y/n)");
rep = keyboard.next();
}
}
}
You need to skip blank lines.
public static void main(String[] args) {
String rep;
Scanner keyboard = new Scanner(System.in);
do {
System.out.print("Enter your full name");
String name = keyboard.nextLine();
System.out.print("Enter your GPA: ");
double gpa = keyboard.nextDouble();
System.out.println("Name: " + name + ", GPA: " + gpa);
System.out.println("Do you want to enter the data for another student?(y/n)");
rep = keyboard.next();
keyboard.skip("\r\n"); // to skip blank lines
}
while (rep.equalsIgnoreCase("y"));
keyboard.close();
}
Use nextLine instead of nextDouble:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String rep = "";
do {
System.out.println("Enter your full name:");
String name = keyboard.nextLine();
System.out.println("Enter your GPA:");
// double gpa = keyboard.nextDouble();
double gpa = Double.parseDouble(keyboard.nextLine());
System.out.println("Name: " + name + ", GPA: " + gpa);
System.out.println("Do you want to enter the data for another student?(y/n)");
rep = keyboard.nextLine();
} while (rep.equals("y"));
keyboard.close();
}
I have an assignment to do a CV that users will input on and display it. However, I don't know how I can call a variable to another to function to print/display.
Here is the code:
import java.util.Scanner;
public class curriculumVitae1{
public static String firstName;
public static String middleName, lastName, birthDate, maritalStatus, homeAddress, provincialAddress, mobileNumber, anotherMobile, landlineNumber, anotherLandline, primaryYears;
private static void main (String args[]){
Scanner input = new Scanner(System.in);
System.out.print("\nCurriculum Vitae");
System.out.print("\nInput your last name: ");
String lastName;
lastName = input.nextLine();
System.out.print("\nInput your first name: ");
String firstName;
firstName = input.nextLine();
System.out.print("\nInput your middle name: ");
String middleName;
middleName = input.nextLine();
System.out.print("\nInput your birthdate: ");
String birthDate;
birthDate = input.nextLine();
System.out.print("\nInput your marital status (Married, Widowed, Separated, Divorced, Single) : ");
String maritalStatus;
maritalStatus = input.nextLine();
System.out.print("\nInput your home address: ");
String homeAddress;
homeAddress = input.nextLine();
curriculumVitae1.cv();
}
private static void provincial(String args[]){
Scanner input = new Scanner(System.in);
System.out.print("\nDo you have a provincial address? Enter Y if yes, and N if no: ");
char provincialQuestion;
provincialQuestion = input.nextLine().charAt(0);
if (provincialQuestion=='Y'){
System.out.print("\nInput your provincial address: ");
String provincialAddress;
provincialAddress = input.nextLine();
}
else if(provincialQuestion=='N'){
}
}
private static void mobile(String args[]){
Scanner input = new Scanner(System.in);
System.out.print("\nContact Details ");
System.out.print("\nInput your mobile number: ");
String mobileNumber;
mobileNumber = input.nextLine();
System.out.print("\nDo you have another mobile number? Enter Y if yes, and N if no: ");
char mobileQuestion;
mobileQuestion = input.nextLine().charAt(0);
if (mobileQuestion=='Y'){
System.out.print("\nInput another mobile number: ");
String anotherMobile;
anotherMobile = input.nextLine();
}
else if(mobileQuestion=='N'){
}
}
private static void landline(String args[]){
Scanner input = new Scanner(System.in);
System.out.print("\nInput your landline number: ");
String landlineNumber;
landlineNumber = input.nextLine();
System.out.print("\nDo you have another landline number? Enter Y if yes, and N if no: ");
char landlineQuestion;
landlineQuestion = input.nextLine().charAt(0);
if (landlineQuestion=='Y'){
System.out.print("\nInput another mobile number: ");
String anotherLandline;
anotherLandline = input.nextLine();
}
else if (landlineQuestion=='N'){
}
}
private static String email(){
Scanner input = new Scanner(System.in);
System.out.print("\nInput your email address: ");
String emailAddress;
emailAddress = input.nextLine();
return emailAddress;
}
private static String tertiary(){
Scanner input = new Scanner(System.in);
System.out.print("\nEducation History ");
System.out.print("\nTertiary Education ");
System.out.print("\nInput your tertiary education course: ");
String tertiaryCourse;
tertiaryCourse = input.nextLine();
System.out.print("\nInput your tertiary education school: ");
String tertiarySchool;
tertiarySchool = input.nextLine();
System.out.print("\nInput your tertiary education inclusive years (xxxx-xxxx): ");
String tertiaryYears;
tertiaryYears = input.nextLine();
System.out.print("\nDo you have any honors/achivements received during your tertiary education? Enter Y if yes, and N if no: ");
char tertiaryQuestion;
tertiaryQuestion = input.nextLine().charAt(0);
if (tertiaryQuestion=='Y'){
System.out.print("\nInput your honor/s or achivement/s:");
String tertiaryAchievements;
tertiaryAchievements = input.nextLine();
return tertiaryAchievements;
}
else if (tertiaryQuestion=='N'){
return "------";
}
}
private static void secondary(String args[]){
Scanner input = new Scanner(System.in);
System.out.print("\nSecondary Education ");
System.out.print("\nInput your secondary education school: ");
String secondarySchool;
secondarySchool = input.nextLine();
System.out.print("\nInput your secondary education inclusive years (xxxx-xxxx): ");
String secondaryYears;
secondaryYears = input.nextLine();
System.out.print("\nDo you have any honors/achivements received during your secondary education? Enter Y if yes, and N if no: ");
char secondaryQuestion;
secondaryQuestion = input.nextLine().charAt(0);
if (secondaryQuestion=='Y'){
System.out.print("\nInput your honor/s or achivement/s:");
String secondaryAchievements;
secondaryAchievements = input.nextLine();
}
else if (secondaryQuestion=='N'){
}
}
public static void primary(String args[]){
Scanner input = new Scanner(System.in);
System.out.print("\nPrimary Education ");
System.out.print("\nInput your primary education school: ");
String primarySchool;
primarySchool = input.nextLine();
System.out.print("\nInput your primary education inclusive years (xxxx-xxxx): ");
String primaryYears;
primaryYears = input.nextLine();
System.out.print("\nDo you have any honors/achivements received during your primary education? Enter Y if yes, and N if no: ");
char primaryQuestion;
primaryQuestion = input.nextLine().charAt(0);
if (primaryQuestion=='Y'){
System.out.print("\nInput your honor/s or achivement/s:");
String primaryAchievements;
primaryAchievements = input.nextLine();
}
else{
System.out.print("------");
}
}
public static void cv(String args[]){
System.out.println(" Curriculum Vitae");
System.out.print("\nName:" + firstName + " " + middleName + " "+ lastName);
System.out.print("\nBirthdate:" + birthDate);
System.out.print("\nMarital Status:" + maritalStatus);
System.out.print("\nHome Address:" + homeAddress);
System.out.print("\nProvincial Address:" + provincialAddress);
System.out.print("\nMobile Number:" + mobileNumber );
System.out.print("\nAnother Mobile Number:" + anotherMobile);
System.out.print("\nLandline:" + landlineNumber);
System.out.print("\nYear: " + primaryYears);
}
}
However, I always get the error that
C:\Users\BEST\Desktop\wew>javac curriculumVitae1.java
curriculumVitae1.java:33: error: method cv in class curriculumVitae1 cannot be applied to given types;
curriculumVitae1.cv();
^
required: String[]
found: no arguments
reason: actual and formal argument lists differ in length
1 error
Please help me on how can I print out another variable from other function. Or some alternatives that I can do.
Your methods expect an (String[] args) however since you don't use them I would remove them. Try
public static void cv() {
The error details highlight that you're calling the method without providing the required parameters in the method signature public static void cv(String args[]):
The required part tells you what types of arguments are expected, here String[] and the found part tells you what it saw instead, here it saw you passed no arguments.
The reason tells you that the actual (what you provided) number of arguments differs from the formal (what the method signature defines) number of arguments expected, i.e. not enough or too many arguments were provided.
You can also get this from the original error message:
error: method cv in class curriculumVitae1 cannot be applied to given types;
curriculumVitae1.cv();
It doesn't explicitly state it, but from the line of code shown below you can see that the "given types" are nothing because the method was called with no arguments—nothing inside the parentheses.
Like Peter Lawrey said, you can just remove the String args[] from your method signature since you don't use it.
Hope this helps you understand error messages and what they're telling you a little better!
Make the following changes to your program:
Change the access specifier of main() method from private to public. Otherwise the code will throw the error - Does not contain a main method
Since you have firstName, middleName, lastName, birthDate etc. declared as static variables do not declare them as local variables in main method. Assign the values to the already declared static variables in the main() method as shown below:
public static void main (String args[]){
Scanner input = new Scanner(System.in);
System.out.print("\nCurriculum Vitae");
System.out.print("\nInput your last name: ");
//String lastName;
lastName = input.nextLine();
System.out.print("\nInput your first name: ");
//String firstName;
firstName = input.nextLine();
System.out.print("\nInput your middle name: ");
//String middleName;
middleName = input.nextLine();
System.out.print("\nInput your birthdate: ");
//String birthDate;
birthDate = input.nextLine();
System.out.print("\nInput your marital status (Married, Widowed, Separated,
Divorced, Single) : ");
//String maritalStatus;
maritalStatus = input.nextLine();
System.out.print("\nInput your home address: ");
//String homeAddress;
homeAddress = input.nextLine();
//System.out.println();
cv();
}
Remove the String[] args argument from cv() method as it is not being used.
Since cv() is a static method, it can be called directly from the main().
Return the string type varaible from tertiary() method as it is giving a compile error. You can do so by declaring tertiaryAchievements variable outside the if-else block and then returning it as shown below:
String tertiaryAchievements="";
if (tertiaryQuestion=='Y')
I just started to code in Java and I have a question. After my "else" statement, I want to repeat my code again. How do I do that? Is there a keyword or something?
import java.util.Scanner;
public class UserInputStory {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
userinput:
System.out.println("Enter you name:");
String name = input.nextLine();
System.out.println("OK! Now enter your age:");
int age;
age = input.nextInt();
System.out.println("Good! And the city you live in, please:");
Scanner in = new Scanner(System.in);
String city = in.nextLine();
System.out.println("So, let's check");
System.out.println(
"Your name is " + name + ". You are " + age + " years old and you currently live in " + city + ".");
System.out.println("Is that right?");
Scanner inp = new Scanner(System.in);
String yesno = inp.nextLine();
if (yesno.equals("yes") || yesno.equals("Yes") || yesno.equals("YES")) {
System.out.println("Great job!");
}
else {
System.out.println("Let's try again then!");
}
}
}
Place the body of your code that you want repeating inside a while loop and break when your end-condition is true:
public static void main(String[] args) {
while(true) {
Scanner input = new Scanner(System.in);
userinput:
System.out.println("Enter you name:");
String name = input.nextLine();
System.out.println("OK! Now enter your age:");
int age;
age = input.nextInt();
System.out.println("Good! And the city you live in, please:");
Scanner in = new Scanner(System.in);
String city = in.nextLine();
System.out.println("So, let's check");
System.out.println("Your name is " + name + ". You are " + age + " years old and you currently live in " + city + ".");
System.out.println("Is that right?");
Scanner inp = new Scanner(System.in);
String yesno = inp.nextLine();
if (yesno.equals("yes") || yesno.equals("Yes") || yesno.equals("YES")) {
System.out.println("Great job!");
break;
}
else {
System.out.println("Let's try again then!");
}
}
}
You can envelop our whole code by:
while(1)
ut its not a good approach and there must be some condition applied (depending upon the xontext of your program) which can take you out of the loop
It's not letting me put my name in but it does the age works fine.
I know i can change the order of the statements but is there another way I could do it?
import java.util.Scanner;
public class ScannerErr2
{
public static void main(String [] args)
{
Scanner keyboard= new Scanner(System.in);
String name;
int age;
System.out.print("Enter your age : ");
age= keyboard.nextInt();
System.out.print("Enter your name: ");
name= keyboard.nextLine();
System.out.println("Age : "+age);
System.out.println("Name: "+name);
}
}
You problem is that the next int doesn't consider the new line character which goes in the input for your name part. Hence name is returned as blank.
You can change your code in 2 ways:
System.out.print("Enter your age : ");
age = keyboard.nextInt();
keyboard.nextLine();
System.out.print("Enter your name: ");
name = keyboard.nextLine();
or
System.out.print("Enter your age : ");
age = Integer.parseInt(keyboard.nextLine().trim());
System.out.print("Enter your name: ");
name = keyboard.nextLine();
I personally like the second way.