Scanner nextLine is being skipped [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(25 answers)
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 4 years ago.
So this is the code I am using:
System.out.println("Create a name.");
name = input.nextLine();
System.out.println("Create a password.");
password = input.nextLine();
But when it reaches this point it just says "Create a name." and "Create a password." both at the same time and then I have to type something. So it's basically skipping the Scanner parts where I need to type a String. After "Create a name." and "Create a password." is outprinted and I type then, both name and password are changing to what I typed in. How do I fix this?
This is the full class. I am just testing so it isn't actually going to be a program:
package just.testing;
import java.util.Scanner;
public class TestingJava
{
static int age;
static String name;
static String password;
static boolean makeid = true;
static boolean id = true;
public static void main(String[] args){
makeid(null);
if(makeid == true){
System.out.println("Yay.");
}else{
}
}
public static void makeid(String[] args){
System.out.println("Create your account.");
Scanner input = new Scanner(System.in);
System.out.println("What is your age?");
int age = input.nextInt();
if(age<12){
System.out.println("You are too young to make an account.");
makeid = false;
return;
}
System.out.println("Create a name.");
name = input.nextLine();
System.out.println("Create a password.");
password = input.nextLine();
return;
}
}
And sorry for my bad grammar. I am not English so it is kinda hard for me to explain this.

The nextInt() ate the input number but not the EOLN:
Create your account.
What is your age?
123 <- Here's actually another '\n'
so the first call to nextLine() after create name accept that as an input.
System.out.println("Create a name.");
name = input.nextLine(); <- This just gives you "\n"
User Integer.parseInt(input.nextLine()) or add another input.nextLine() after reading the number will solve this:
int age = Integer.parseInt(input.nextLine());
or
int age = input.nextInt();
input.nextLine()
Also see here for a duplicated question.

This doesnt actually tell you why the lines are being skipped, but as you're capturing names and passwords you could use Console:
Console console = System.console();
String name = console.readLine("Create a name.");
char[] password = console.readPassword("Create a password.");
System.out.println(name + ":" + new String(password));

You can also use next() instead of nextLine(). I have tested it in eclipse. its working fine.

next() will work but it will not read the string after space.

Related

When user presses "enter" key or space enter then error message pops up

I would like to print an error message when the user presses enter or space enter instead of a string. I have tried isEquals("") and isEmpty() but haven't found anything that works yet.
Here's my code:
import java.util.Scanner;
public class check{
public static void main(String args[]){
System.out.println("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.next();
if(input.equals("")){
System.out.println("Empty");
} else {
System.out.println("number inputed");
}
}
}
One way to do this, change keyboard.next() to keyboard.nextLine(), use trim() to remove unnecessary spaces, check with isEmpty().
String input = keyboard.nextLine().trim();
if (input.isEmpty()) {
// error message
} else {
// good to go
}
import java.util.Scanner;
public class check{
public static void main(String args[]){
System.out.println("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
if(input.trim().equals("")){
System.out.println("Empty");
} else {
System.out.println("number inputed");
}
}
}
Strangely, I don't get an error when running your code. However, I noticed that your code simply doesn't react to an empty input (just pressing enter). If you want to check for that, you can use keyboard.nextLine().
Judging by the rest of your code, it seems like you want the user to input only a number. An easy way to check if the user entered an integer if you're using Scanner is keyboard.hasNextInt().
Meaning you can do something like this:
if(keyboard.hasNextInt()) {
int yourNumber = keyboard.nextInt();
System.out.println("Your number is: " + your Number);
}
else {
System.out.println("Please enter a valid integer");
}
To check whether the string input is empty, you can use the String.isEmpty() method. Look below:
String input = keyboard.nextLine();
if(!input.isEmpty()) {
//the input is not empty!
}
else {
//the input is empty!
}
Note, however, that since you want to receive numbers as inputs you should not retrieve them as strings. Below is an example where the program retrieves a double from the user. Scanner provides many methods to validate the user's input. In this case, I'm using hasNextDouble() to check whether the input is a number.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");
while(!scanner.hasNextDouble()) {
System.out.println("That's not a number!");
scanner.next();
}
double numberInput = scanner.nextDouble();
System.out.println("The entered number was " + numberInput);
I made a sample program similar to yours and used nextLine() instead of next(). When user enters space and clicks enter he will print "space" else "a number".

Repeating error message inside a while loop [duplicate]

This question already has answers here:
Loop user input until conditions met
(3 answers)
Closed 7 years ago.
I'm currently working my way through a Udemy Java course and am practicing what i have learnt thus far.
I have the following simple program which i am planning on using to get the user to input his name.
import java.util.Scanner;
public class Adventure {
public static final int menuStars = 65;
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
String firstName = "";
String lastName = "";
boolean validName = false;
while(!validName){
//Entering first name
System.out.println("Please enter your first name.");
try {
firstName = input.nextLine();
if(firstName.length() == 0){
throw new Exception("Please enter a first name of at least 1 character.");
}else{
//Entering last name
System.out.println("Please enter your last name.");
lastName = input.nextLine();
if(lastName.length() == 0){
throw new Exception("Please enter a last name of at least 1 character");
}else{
System.out.println("You have entered " + firstName +" " + lastName);
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
continue;
}
//Used to terminate loop when both first & last names are valid
validName = true;
}
}
}
I want to make the program repeat the error message when the user inputs a blank name instead of restarting the entire program from the beginning.
E.g When the user enters a blank first name, i want the program to keep repeating "Please enter a first name of at least 1 character" and when the user enters a blank last name, for it to keep repeating "Please enter a last name of at least 1 character" until the user enters a valid name.
However, currently when the user enters a blank first name or last name, my program will repeat itself from the very beginning instead of repeating just the error message.
How would i go about making the program repeat just the error message?
Use a boolean variable that stores true when "Please enter your first name." is printed. Check before printing this string each time if this variable is false or not. Also, initialize it to false before the loop. Same idea goes for last name.
if(!printed)
{
System.out.println("Please enter your first name.");
printed=true;
}
havent tested that but i am guessing it can be like that, with out try/catch though, it just makes no sense to me using it in the way you have it on your code
String firstName = "";
String lastName = "";
System.out.println("Please enter your first name.");
firstName = input.nextLine();
while(firstName.length<1){
System.out.println("Please enter a first name of at least 1 character.");
firstName = input.nextLine();
}
lastName=input.nextLine();
while(firstName.length<1){
System.out.println("Please enter a last name of at least 1 character.");
lastName = input.nextLine();
}
System.out.println("You have entered " + firstName +" " + lastName);
Edit, some basic info about exceptions
try catch is used when something unexpected happens and you try to find a way round it. for example if an array of 10 positions is expected at some point and a smaller array (lets say 4 positions) is being used. Then this would cause an exception causing the program to terminate with no further information.
With try catch you can check what the problem is, and try to either inform the user to do something(if they can) or close the program in a better way, using System.exit() for example and saving all the work that was done till that point
An other example is that if you ask for 2 numbers to do an addition. if the user enters letters instead of number the int sum=numbA+numbB; would throw and exception. This of course could be handled using an if. but even better would be something like this
A whitespace is actually considered a character, so the check of (length == 0) doesn't work for your purposes.
Although the following code below is incomplete (ex: handles the potentially undesirable case of firstname=" foo", (see function .contains()), it does what the original post asks - when the user enters a blank first/last name, it keeps repeating "Please enter a first/last name of at least 1 character" until the user enters a valid first/last name.
import java.util.Scanner;
public class Adventure {
public static final int menuStars = 65;
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
String firstName = "";
String lastName = "";
boolean firstNameLegal = false;
boolean lastNameLegal = false;
// Entering first name
while (!firstNameLegal) {
System.out.println("Please enter your first name.");
firstName = input.nextLine();
if (!firstName.equals(" "))
firstNameLegal = true;
else
System.out.println("Please enter a first name of at least 1 character.");
}
// Entering last name
while(!lastNameLegal){
System.out.println("Please enter your last name.");
lastName = input.nextLine();
if(!lastName.equals(" "))
lastNameLegal = true;
else
System.out.println("Please enter a last name of at least 1 character.");
}
System.out.println("You have entered " + firstName +" " + lastName);
}
}

Program for testing input and throwing exceptions how to restart when exception thrown JAVA

Essentially the idea of this program is to test user input and throw exceptions that I've created when invalid data is entered. For example: name cannot be empty and must be all alpha characters (no special or numeric). I have embedded this in a do-while loop that will continue so long as q is not entered to quit. I'm reading in the user input via scanner line and then sending the string inputted to a function that validates whether it meets the criteria. If it does not, then the function throws my custom exceptions. It all works fine EXCEPT when the exception is thrown it still takes that string and puts it in the new Person object.
How do I throw the exception to the user but THEN require them to re-enter the name or age until it's entered correctly?
do{
Scanner input = new Scanner(System.in);
System.out.println("Enter person info or q to quit.");
System.out.print("Please enter the name of this person:");
String name = input.nextLine();
if(name.equalsIgnoreCase("q"))
{
break;
}
try{
isName(name);
}catch (InvalidNameException n){
System.out.println(n);
}
System.out.print("Please enter an age for this person:");
String age = input.nextLine();
try{
isValidAge(age);
}catch(InvalidAgeException a){
System.out.println(a);
}
public static void isName(String name) throws InvalidNameException
{
if(name.isEmpty())
{
throw new InvalidNameException("You did not enter a name.");
}
String[] namez = name.split(" ");
for(int i=0;i<namez.length;i++)
{
char[] charz = namez[i].toCharArray();
for (char n : charz)
{
if(!Character.isLetter(n))
{
throw new InvalidNameException("You have entered an invalid name.");
}
}
}
}
Put a continue; in your exception handling. It will break the loop an reenters it.
I would assume that the error lies within the compatibility of your isName() method and the method loop shown. It probably happens after it sets the name to a variable too. I cant tell you anything really specific because I cant see the isName method though.
The easiest way I know of doing this is to validate the obtained String using a regular expression. You can do something like this:
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = input.nextLine();
String regex = "[A-Z a-z]+(\\s)[A-Z a-z]+";
System.out.println(name.matches(regex)? "matches": "does not match");
The expression regex is used to evaluate a sequence of alpha characters (no numbers or special characters) separated by a space. So, something like: "Joe Smith" will pass validation, but something like "Joe 123Klkjsd" will not.
You can take this code and test the input String in a while() loop:
while(!name.matches(regex))
{
// Prompt the user to re-enter a valid name and assign to name variable
}
Something like that should work.
It would be better to evaluate each variable within a do-while loop. Thus if there is an error in the variable age would not necessarily re-enter the name.
Scanner input = new Scanner(System.in);
String name;
String age;
System.out.println("Enter person info or q to quit.");
do{
System.out.print("Please enter the name of this person: ");
name = input.nextLine();
if(name.equalsIgnoreCase("q")) break;
try{
isName(name);
break;
}catch (InvalidNameException n){
System.out.println(n);
continue;
}
} while (true);
if(!name.equalsIgnoreCase("q"))
do{
System.out.print("Please enter an age for this person: ");
age = input.nextLine();
if(age.equalsIgnoreCase("q")) break;
try{
isValidAge(age);
System.out.printf("Nombre; %s\nEdad: %s",name,age);
break;
}catch (InvalidAgeException a){
System.out.println(a);
continue;
}
} while (true);

I'm having trouble only inputting letters, not numbers

For my project I need to input a first and last name with no numbers but I simply can't find anything online. If you could help, that would be terrific.
Also if you have the time, I need to flip the first and last name with a comma when the user inputs them.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class PhoneListr {
public static void main (String[] args) throws IOException {
String firstName;
String lastName;
System.out.println ("Please enter your first name:");
firstName = PhoneList ("");
System.out.println ("Please enter your last name:");
lastName = PhoneList ("");
System.out.println ("Your full name is: " + lastName + "," + firstName);
}
public static String PhoneList (String input) throws IOException {
boolean continueInput = false;
while (continueInput == false) {
BufferedReader bufferedReader = new BufferedReader (new InputStreamReader (System.in));
input = bufferedReader.readLine();
continueInput = true;
if(input.matches("[a-zA-Z]+")) {
continueInput = true;
}
else {
System.out.println ("Error, you may only use the alphabet");
continueInput = false;
}
}
return input;
}
}
use String.matches(regex):
if(input.matches("[a-zA-Z]+")) {
System.out.println("your input contains no numerics");
}
else {
System.out.println("only alphabets allowed");
}
the above regex checks a through z, or A through Z, inclusive (range).
For this type of string matching you need to use Regular Expressions, or "RegEx"es. It is a very big topic to cover but here's an introduction. RegExes are tools used to test whether strings match certain criteria, and/or to pull certain patterns out of that string or replace certain parts that match those patterns with something else.
Here is an example using a RegEx to test whether your input contains a digit:
if(input.matches("\\d")) {
// matched a digit, do something
}
Based on OP problem and clarification here are few suggestions.
Chaitanya solution handles the check for only alphabets perfectly.
About the neglected areas of problem :
i would advice you to make two variable firstName and lastName inside the main()
String firstName;
String lastName;
Change retun type of method phoneList() to String
return the entered name input insted of number inside the method phoneList ( dont actually see why you are returning number) and store it inside the firstName and lastName
System.out.println ("Please enter your first name:");
firstName = PhoneList (0);
System.out.println ("Please input your last name:");
lastNamr =PhoneList (0);
now to print it in the "comma format" use
System.out.println("full name is: " +lastName+ "," +firstName);
As i read your program again , its a mess!!
About the method phoneList()
Use regex condition to set continueInput to true/flase and not exploit execptions.
P.s. I would appreciate "editing" to post , if any fellow member find any mistakes above, using a mobile, not sure about formatting etc. Thanks. :-) (y)
You can also use
if(input.matches("[^0-9]"))
{
System.out.println("Don't input numbers!");
continueInput = false;}
Can't understand what 2nd question asks. For answer what I get from your 2nd question is like this.
In main function change the code like this
String first_name = null;
String last_name = null;
System.out.println ("Please enter your first name:");
first_name = PhoneList();
System.out.println ("Please input your last name:");
second_name = PhoneList();
System.out.println (second_name+","+first_name);
then in PhoneList function last line should be changed to
return input;
Please check for a link! for more info
You can add a check by passing the argument to method StringUtils.isNumeric
This returns true if the String entered is numeric

Restrict string input from user to alphabetic and numerical values [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
Basically, my situation requires me to check to see if the String that is defined by user input from the keyboard is only alphabetical characters in one case and only digits in another case. This is written in Java.
my current code:
switch (studentMenu) {
case 1: // Change all four fields
System.out.println("Please enter in a first name: ");
String firstNameIntermediate = scan.next();
firstName = firstNameIntermediate.substring(0,1).toUpperCase() + firstNameIntermediate.substring(1);
System.out.println("Please enter in a middle name");
middleName = scan.next();
System.out.println("Please enter in a last name");
lastName = scan.next();
System.out.println("Please enter in an eight digit student ID number");
changeID();
break;
case 2: // Change first name
System.out.println("Please enter in a first name: ");
firstName = scan.next();
break;
case 3: // Change middle name
System.out.println("Please enter in a middle name");
middleName = scan.next();
break;
case 4: // Change last name
System.out.println("Please enter in a last name");
lastName = scan.next();
case 5: // Change student ID:
changeID();
break;
case 6: // Exit to main menu
menuExit = true;
default:
System.out.println("Please enter a number from 1 to 6");
break;
}
}
}
public void changeID() {
studentID = scan.next();
}
I need to make sure the StudentID is only numerical and each of the name segments are alphabetical.
java.util.Scanner can already check if the next token is of a given pattern/type with the hasNextXXX methods.
Here's an example of using boolean hasNext(String pattern) to validate that the next token consists of only letters, using the regular expression [A-Za-z]+:
Scanner sc = new Scanner(System.in);
System.out.println("Please enter letters:");
while (!sc.hasNext("[A-Za-z]+")) {
System.out.println("Nope, that's not it!");
sc.next();
}
String word = sc.next();
System.out.println("Thank you! Got " + word);
Here's an example session:
Please enter letters:
&###$
Nope, that's not it!
123
Nope, that's not it!
james bond
Thank you! Got james
To validate that the next token is a number that you can convert to int, use hasNextInt() and then nextInt().
Related questions
Validating input using java.util.Scanner - has many examples!
It's probably easiest to do this with a regular expression. Here's some sample code:
import java.util.regex.*;
public class Test
{
public static void main(String[] args) throws Exception
{
System.out.println(isNumeric("123"));
System.out.println(isNumeric("abc"));
System.out.println(isNumeric("abc123"));
System.out.println(isAlpha("123"));
System.out.println(isAlpha("abc"));
System.out.println(isAlpha("abc123"));
}
private static final Pattern NUMBERS = Pattern.compile("\\d+");
private static final Pattern LETTERS = Pattern.compile("\\p{Alpha}+");
public static final boolean isNumeric(String text)
{
return NUMBERS.matcher(text).matches();
}
public static final boolean isAlpha(String text)
{
return LETTERS.matcher(text).matches();
}
}
You should probably write methods of "getAlphaInput" and "getNumericInput" which perform the appropriate loop of prompt/fetch/check until the input is correct. Or possibly just getInput(Pattern) to avoid writing similar code for different patterns.
You should also work out requirements around what counts as a "letter" - the above only does a-z and A-Z... if you need to cope with accents etc as well, you should look more closely at the Pattern docs and adapt appropriately.
Note that you can use a regex to validate things like the length of the string as well. They're very flexible.
Im not sure this is the best way to do, but you could use Character.isDigit() and Character.IsLiteral() mabybe like this:
for( char c : myString.toCharArray() ) {
if( !Character.isLiteral(c) ) {
//
}
}
try regexp: \d+ -- numerical, [A-Za-z]+ -- alphabetical
I don't think you can prevent the users from entering invalid values, but you have the option of validating the data you receive. I'm a fan of regular expressions. Real quick, something like this maybe (all values initialized to empty Strings):
while (!firstName.matches("^[a-zA-Z]+$")) {
System.out.println("Please enter in a first name");
firstName = scan.next();
}
...
while (!studentID.matches("^\\d{8}$")) {
System.out.println("Please enter in an eight digit student ID number");
changeID();
}
If you go this route, you might as well categorize the different cases you need to validate and create a few helper methods to deal with each.
"Regex" tends to seem overwhelming in the beginning, but learning it has great value and there's no shortage of tutorials for it.
That is the code
public class InputLetters {
String InputWords;
Scanner reader;
boolean [] TF;
boolean FT;
public InputLetters() {
FT=false;
while(!FT){
System.out.println("Enter that you want to: ");
reader = new Scanner(System.in);
InputWords = reader.nextLine();
Control(InputWords);
}
}
public void Control(String s){
String [] b = s.split(" ");
TF = new boolean[b.length];
for(int i =0;i<b.length;i++){
if(b[i].matches("^[a-zA-Z]+$")){
TF[i]=true;
}else
{
TF[i]=false;
}
}
for(int j=0;j<TF.length;j++){
if(!TF[j]){
FT=false;
System.out.println("Enter only English Characters!");
break;
}else{
FT=true;
}
}
}

Categories