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];
}
Related
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".
So I am doing a project to put values into a scanner object and retrieve them. I am having a problem with the first input. The user is asked to input an ID and then should be asked for the last name.The problem is that when I run the first question it displays it but skips the first scanner input and jumps to the second question and input returns to normal. So what is happening here? And how do I solve this?
//Prompt user for each value
System.out.println("Enter employee Id number:");
String inputId = scanner.nextLine();
System.out.println("Enter employees last name:");
String inputLastName = scanner.nextLine();
System.out.println("Enter employees first name:");
String inputFirstName = scanner.nextLine();
System.out.println("Enter employees salary:");
String inputSalary = scanner.nextLine();
Double inSalary = Double.parseDouble(inputSalary);
i have same problem with you, and i change .nextLine() with .next()
and that is how i fix my problem
try this
System.out.println("Enter employee Id number:");
String inputId = scanner.next();
System.out.println("Enter employees last name:");
String inputLastName = scanner.next();
System.out.println("Enter employees first name:");
String inputFirstName = scanner.next();
System.out.println("Enter employees salary:");
String inputSalary = scanner.next();
Double inSalary = Double.parseDouble(inputSalary);
I've seen a couple of threads that are similar to this question, but had trouble finding the solution to my specific question.
The code I am writing is for a teacher to input a student's name and grades and receive an output of the final letter grade.
The area I am having trouble with is the last name input gets grouped together with the first name input, instead of asking the question by itself. How do I prompt these to appear as separate questions?
import java.util.*;
public class AssignmentTest {
public static void main (String [] args) {
Scanner console = new Scanner (System.in);
int iStudentID = 0; //StudentID
String sLastName = ""; //Last Name
String sFirstName = ""; //First Name
int iAssignmentsScore = 0; //Assignment Input
int iQuizzesScore = 0; //Quizzes Input
int iMidtermsScore = 0; //Midterm Input
int iFinalScore = 0;; //Final Input
//USER INPUT
//StudentID Input
System.out.println("Please enter the StudentID: ");
iStudentID = console.nextInt() ;
//Last Name Input
System.out.println ("Please enter the student's last name: ");
sLastName = console.nextLine() ;
//First Name Input
System.out.println ("Please enter the student's first name: ");
sFirstName = console.nextLine() ;
//Assignment Input
System.out.println ("Please enter the student's assignment score: ");
iAssignmentsScore = console.nextInt() ;
//Quiz Input
System.out.println ("Please enter the student's quiz score: ");
iQuizzesScore = console.nextInt ();
//Midterm Input
System.out.println ("Please enter the student's midterm score: ");
iMidtermsScore = console.nextInt ();
//Final Input
System.out.println ("Please enter the student's final score: ");
iFinalScore = console.nextInt ();
}
}
Since sFirstName and lFirstName , each consist of a word you should use
next()
Finds and returns the next complete token from this scanner.
Instead of
nextLine()
Advances this scanner past the current line and returns the input that
was skipped.
#madprogrammer has better explanation:
Actually, the issue is after iStudentID = console.nextInt() ; returns,
there is still a new line character in the buffer, so that when
sLastName = console.nextLine() ; is called, it skips of this
automatically (returning an empty String) - this is a very common
mistake
try this
System.out.println ("Please enter the student's last name: ");
sLastName = console.nextLine() ;
console.nextLine();
I think this may be as simple as adding another new line character \n. For example
System.out.println ("\nPlease enter the student's first name: ");
you should use next() instead of nextLine()
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);