The Following code is a simple java program where I am just getting an input of a student details but the program doesn't do anything it just stays like this no compilation error or does not take any input
import java.util.Scanner;
public class Scannerexample {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int Rollno = scan.nextInt();
String firstname = scan.nextLine();
String lastname = scan.nextLine();
String Department = scan.nextLine();
Boolean Result = scan.hasNext();
char gender = scan.next().charAt(0);
System.out.println("Enter Rollno "+ Rollno);
System.out.println("Enter Firstname "+ firstname);
System.out.println("Enter Lastname "+ lastname);
System.out.println("Enter Department "+ Department);
System.out.println("Enter Result "+ Result);
System.out.println("Enter Gender "+ gender);
scan.close();
}
}
Each call of scan.nextSomething waits for input. So the way you have written the program you wait for inputting of all the fields and then print them. Try typing some fields and press enter to see the result in the end.
What you probably wanted is something like:
System.out.println("Enter rollno: ");
int rollno = scan.nextInt();
System.out.println("You entered rollno: "+ rollno);
Also there are some java conventions which are nice and make the code readable :) For example variables start with lowercase and classes are in CamelCase
So what your Code does is every time you call
scan.nextLine();
The Program waits for your Input, until you hit 'Enter'.
So if you want to write something before the Input, you have to do it like this:
System.out.print("Enter Rollno: ");
int rollno = scan.nextInt();
System.out.print("Enter Firstname: ");
String firstname = scan.next();
// Any more.
Keep an eye that you only use 'print()' instead of 'println()' so that your input is on the same Line.
Also use scan.next(), to only grab the input, and not the complete line in terminal.
be carefull with scan.next() or scan.nextLine()
System.out.print("Enter Rollno: ");
int rollno = scan.nextInt();
System.out.print("Enter Firstname: ");
String firstname = scan.next();
System.out.println(firstname);
// Any more.
System.out.print("Enter Lastname: ");
String lastname = scan.next();
System.out.println(lastname);
in this case, if you input Firstname as: John Doe, it will not let you to input Lastname, because it will read next string in line.
scan.next() read strings up to "space", then another scan.next() will read next strings up to next "space".
Related
I am a newbie with java and the class scanners.
I have two Codes and I dont get the point why one of them throws a InputMismatchException.
I look forward to the answers.
Here both codes:
1st one with the Exception Error:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String firstName, lastName, completeName;
int age;
System.out.println("Please enter your first name: ");
firstName = sc.nextLine();
System.out.println("Please enter your last name: ");
lastName = sc.nextLine();
System.out.println("Please enter your complete name and your age: ");
completeName = sc.next();
age = sc.nextInt();
System.out.println("Your complete name is: " + completeName);
System.out.println("Your age is: " + age);
}
Console:
Please enter your first name:
Peter
Please enter your last name:
Henrik
Please enter your complete name and your age:
Peter Henrik 22
(InputMismatchException)
2nd one with no error:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String firstName, lastName;
int age;
System.out.println("Please enter your first name: ");
firstName = sc.nextLine();
System.out.println("Please enter your last name: ");
lastName = sc.nextLine();
System.out.println("Please enter your age: ");
age = sc.nextInt();
System.out.println("Your complete name is: " + firstName + " " + lastName);
System.out.println("Your age is: " + age);
}
Console:
Please enter your first name:
Peter
Please enter your last name:
Henrik
Please enter your age:
22
Your complete name is: Peter Henrik
Your age is: 22
Your first code throws InputMismatchException because sc.next() reads the first complete token ("Peter") up to the whitespace (since whitespace is the default delimiter for Scanner in Java), thus after that, the sc.nextInt() method will read "Henrik" which is a String unlike your expectation to read the age (22).
Here's what you can do instead in order to read the complete name of the user as well as the age [CONDITION: You'll have to enter age in a new line]:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String firstName, lastName,completeName;
int age;
System.out.println("Please enter your first name: ");
firstName = sc.nextLine();
System.out.println("Please enter your last name: ");
lastName = sc.nextLine();
System.out.println("Please enter your complete name: ");
completeName = sc.nextLine();
System.out.println("Please enter your age: ");
age = sc.nextInt();
System.out.println("Your complete name is: " + completeName);
System.out.println("Your age is: " + age);
}
PS: An alternate solution can be to read the complete name and the age in a single line as you did and then split up the tokens using the String split() method in Java.
Having a look at the Javadoc of Scanner#next() will tell you the following:
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
The default delimiter for the Scanner is a whitespace.
Knowing this, you provide the following input
Peter Henrik 22
and try to read this input via the following
completeName = sc.next();
age = sc.nextInt();
The call to sc.next() will read the first complete token up to the whitespace, which is "Peter".
So Henrik 22 is still available in the Scanner buffer.
Therefore sc.nextInt() will read Henrik and try to parse it to an int hence the InputMismatchException.
To read both tokens to get the complete name, simply change
completeName = sc.next();
to
completeName = sc.next() + " " + sc.next();
However, names don't always consist of only two parts. Since there could be names that more than two single tokens, you should / could do it like the following (provided you still want to enter the complete name and age in one line):
String line = sc.nextLine(); // read the whole line
// everything up to the last token is the name
completeName = line.substring(0, line.lastIndexOf(" "));
// last token is the age
age = line.substring(line.lastIndexOf(" ") + 1);
I'm new to java and I made this program, the problem I'm asking the user to input their age and name then the program should use the input to print the statement. however the when I type the age then press enter the program executes all the statements without waiting for me to enter my name.. how can I fix this?
Scanner input = new Scanner(System.in);
int age;
String name;
System.out.println("Please enter your age ");
age = input.nextInt();
System.out.println("and now enter your name");
name = input.nextLine();
System.out.println("Your name is " +name + " and you're " +age + "years old");
You can use nextLine() for both:
System.out.println("Please enter your age ");
age = Integer.parseInt(input.nextLine());
System.out.println("and now enter your name");
name = input.nextLine();
The problem is that when you hit Enter after you input the age, the resulting newline is interpreted as the end of the input for the following nextLine().
You could also use next() instead of nextLine(), but then John Doe would be interpreted as just John because next() uses whitespace as a separator.
Use next() instead of nextLine() at name variable.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int age;
String name;
System.out.println("Please enter your age ");
age = input.nextInt();
System.out.println("and now enter your name");
name = input.next();
System.out.println("Your name is " +name + " and you're " +age + " years old");
}
I have a question. I know you can prompt a user multiple times with scanner as so
public static void main(String[] args) {
String First;
String Last;
int Age;
Scanner input = new Scanner(System.in);
System.out.print("What is the First name of person?");
First = input.next();
System.out.print("What is the Last name of person?");
Last = input.next();
System.out.print("What is the Age of person?");
Age = input.next();
}
But is there a way there to prompt all in one line?
For example I want to enter
Console-What is the First, Last, and Age of the person?
User- First Last Age
First, Java variables start with a lower case letter by convention (yours look like class names). Second, this
Age = input.next();
gives you a compiler error. Because Age is an int. You can certainly split the single line as others have suggested, but you can also construct a Scanner(String) and use it with something like
Scanner input = new Scanner(System.in);
System.out.println("Please enter the first name last name and age of the person: ");
System.out.println("(first last age)");
String line = input.nextLine();
Scanner scan = new Scanner(line);
String first = scan.next();
String last = scan.next();
int age = scan.nextInt();
System.out.printf("Person: %s, %s (%d)%n", last, first, age);
Grab a line and split the string:
Scanner input = new Scanner(System.in);
System.out.print("What is the First, Last, and Age of the person?");
String line = input.nextLine();
String[] parts = line.split(" ");
if(parts.length < 3){
//error, ask again
}
else{
String first = parts[0];
String last = parts[1];
String age = parts[2];
}
I need to write a test class that will do the following:
a. Let the user input an integer and display it.
b. Let the user input a float value and display it.
c. Let the user input his/her name (no white spaces) and display the
name as: “Hello <name>, welcome to Scanner!”
d. Let the user input a character and display it.
e. Let the user input any string (with white spaces) and display it.
My questions is, how can I simply scan just a Character and display it? And in number 2, How can I input a String with white spaces and display it? (letters "d" and "e")
I've searched around, but I cannot find the simplest solution (since I'm new to Java and programming).
Here is my code so far:
package aw;
import java.io.PrintStream;
import java.util.Scanner;
public class NewClass1
{
public static void main(String[] args)
{
int num;
double num2;
String name;
char c;
Scanner sc = new Scanner(System.in);
PrintStream ps = new PrintStream(System.out);
//for integer
System.out.println("Enter a number: ");
num = sc.nextInt();
ps.printf("%d\n", num);
//for float
System.out.println("Enter a float value: ");
num2 = sc.nextDouble();
ps.printf("%.2f\n", num2);
//for name w/o white space
System.out.print("Enter your first name: ");
name = sc.next();
ps.printf("Hello %s, welcome to Scanner\n", name);
//for character
System.out.print("Enter a character: ");
c = sc.findWithinHorizon(".", 0).charAt(0);
System.out.print(“%c”, c);
//for name w/ white space
System.out.print("Enter your full name: ");
name = sc.nextLine();
System.out.print(“%s”, name);
}
}
I hope you can help me. Thanks!
First, there's no need to wrap System.out in a PrintStream because out already supports formatting with format() or printf() methods.
Next, you need to understand that when you input a line of data you also terminate it with a new line \n. The next<Type>() methods only consume the <Type> and nothing else. So, if a next<Type>() call may match \n, you need to skip over any extra new lines \n with another nextLine() before.
Here's your code with fixes:
int num;
double num2;
String name;
char c;
Scanner sc = new Scanner(System.in);
//for integer
System.out.print("Enter a number: ");
num = sc.nextInt();
System.out.printf("%d\n", num);
//for float
System.out.print("Enter a float value: ");
num2 = sc.nextDouble();
System.out.printf("%.2f\n", num2);
//for name w/o white space
System.out.print("Enter your first name: ");
name = sc.next();
System.out.printf("Hello %s, welcome to Scanner\n", name);
//for character
System.out.print("Enter a character: ");
c = sc.findWithinHorizon(".", 0).charAt(0);
System.out.printf("%c\n", c);
sc.nextLine(); // skip
//for name w/ white space
System.out.print("Enter your full name: ");
name = sc.nextLine();
System.out.printf("%s", name);
Use Scanner.next(Pattern) and pass Pattern.compile("[A-Za-z0-9]") to let scanner accept only 1 character defined. You can pass any regex as argument and check for next() Scanner.next(); for next line with spaces
Use this:
//for a single char
char Character = sc.findWithinHorizon(".", 0).charAt(0);
//for a name with white space
System.out.print("Enter your full name: ");
String name2 = sc.next();
String surname = sc.next();
System.out.println(name2 + " " + surname);
I'm attempting to scan in strings one after another and some may contain spaces. As my code functions currently it will only work if each string you type in is one word. What's the proper way to scan in consecutive lines of text, regardless of there being spaces in the line or not.
System.out.print("Enter your first name: ");
fName = scan.next();
System.out.print("Enter your last name: ");
lName = scan.next();
System.out.print("Enter your street and house number: ");
address = scan.next();
System.out.print("Enter your city: ");
city = scan.next();
System.out.print("Enter your state: ");
state = scan.next();
System.out.print("Enter your telephone number (no spaces): ");
teleNum = scan.next();
System.out.print("Enter your zip code: ");
zip = scan.next();
String[] prompts = {
"Enter your city: ",
"Enter your state: ",
};
Scanner scanner = new Scanner(System.in);
String line = "";
for (String prompt : prompts) {
System.out.println(prompt);
if (scanner.hasNextLine()) {
line += scanner.nextLine();
}
}
System.out.println(line);