Prevent user from entering whitespace in Java - java

I want the user to only enter his age. So I did this program :
Scanner keyb = new Scanner(System.in);
int age;
while(!keyb.hasNextInt())
{
keyb.next();
System.out.println("How old are you ?");
}
age = keyb.nextInt();
System.out.println("you are" + age + "years old");
I found how to prevent user from using string by using the while loop with keyb.hasNextInt(), but how to prevent him from using the whitespace or from entering more input than his age ?
For example I want to prevent this kind of typing "12 m" or "12 12"
Also, how can I clear all existing data in the buffer ? I'm facing an infinite loop when I try to use this :
while(keyb.hasNext())
keyb.next();

You want to get the whole line. Use nextLine and check that for digits e.g.
String possibleAge = "";
do {
System.out.println("How old are you ?");
possibleAge = keyb.nextLine();
} while (!possibleAge.matches("\\d+"))

Your problem is that the default behaviour of Scanner is to use any whitespace as the delimiter. This includes spaces. This means that a 3 a is in fact three tokens, not one. You can change the delimiter to a new line so that a 3 a becomes a single token, which will then return false for hasNextInt.
I've also added an initial question, because in your example the first input was taken before asking any questions.
Scanner keyb = new Scanner(System.in);
keyb.useDelimiter("\n"); // You can try System.lineSeparator() but it didn't work in IDEA
int age;
System.out.println("How old are you?");
while(!keyb.hasNextInt())
{
keyb.next();
System.out.println("No really. How old are you?");
}
age = keyb.nextInt();
System.out.println("You are " + age + " years old");

String age = "11";
if (age.matches(".*[^0-9].*")) {
System.out.println("Invalid age");
} else {
System.out.println("valid age");
}
If age contains other then digits then it will print invalid age.

Related

How can I make sure that the user did not enter his/her entire name in the First Text Field named as "First Name"

This question says ask for the 'First Name' and the 'Last Name' from the user and then show the message Welcome with the full name of the user . also make sure that the user does not enter his/her full name in the first Text Field which asks for First Name only
I thought that if the user enters his/her full name in the first text field , we can know that from the fact that he/she entered a space or (' ') or not . If not we can simply show the message Welcome + full name . However it didn't work the way I thought it would ... Can somebody help me with itenter image description here
If I understand you the below will work accomplish what you need by ignoring the data after the space and asking the user for their last name.
code:
public static void main(String[] args) {
// Properties
Scanner keyboard = new Scanner(System.in);
String firstName, lastName
// Ask the user for their first name
System.out.println("What is your first name? ");
System.out.print("--> "); // this is for style and not needed
firstName = keyboard.next();
// Ask the user for their last name
System.out.println("What is your last name? ");
System.out.print("--> "); // this is for style and not needed
lastName = keyboard.next();
// Display the data
System.out.println("Your first name is : " + firstName);
System.out.println("Your last name is : " + lastName);
}
There is actually a few ways you can do this, but if I understand your question correctly a simple way would be below, which is from http://math.hws.edu/javanotes/c2/ex6-ans.html and helped me understand Java more when I was learning it, you just would alter it to your needs.
code:
public class FirstNameLastName {
public static void main(String[] args) {
String input; // The input line entered by the user.
int space; // The location of the space in the input.
String firstName; // The first name, extracted from the input.
String lastName; // The last name, extracted from the input.
System.out.println();
System.out.println("Please enter your first name and last name, separated by a space.");
System.out.print("? ");
input = TextIO.getln();
space = input.indexOf(' ');
firstName = input.substring(0, space);
lastName = input.substring(space+1);
System.out.println("Your first name is " + firstName + ", which has "
+ firstName.length() + " characters.");
System.out.println("Your last name is " + lastName + ", which has "
+ lastName.length() + " characters.");
System.out.println("Your initials are " + firstName.charAt(0) + lastName.charAt(0));
}
}
edit:
If this doesn't make sense I can give a better explanation with a better example with more detail.
More notes on similar problems.
https://www.homeandlearn.co.uk/java/substring.html
The problem with your code is, that you check every single charackter and then do the if/else for every single charackter. which means if the last charackter is not a whitespace it will at the end process the else tree.
The solution is to just check once:
if(fn.contains(' '){
//Do what you want to do, if both names were entered in the first field
}else{
//Everything is fine
}

Splitting a user inputted string and then printing the string

I am working through a piece of self study, Essentially I am to ask the User for a string input such as "John, Doe" IF the string doesnt have a comma, I am to display an error, and prompt the user until the string does indeed have a comma (Fixed.). Once this is achieved I need to parse the string from the comma, and any combination of comma that can occur (i.e. John, doe or John , doe or John ,doe) then using the Scanner class I need to grab John doe, and split them up to be separately printed later.
So far I know how to use the scanner class to grab certain amounts of string up to a whitespace, however what I want is to grab the "," but I haven't found a way to do this yet, I figured using the .next(pattern) of the scanner class would be what I need, as the way it was written should do exactly that. however im getting an exception InputMismatchException doing so.
Here is the code im working with:
while (!userInput.contains(",")) {
System.out.print("Enter a string seperated by a comma: ");
userInput = scnr.nextLine();
if (!userInput.contains(",")) {
System.out.println("Error, no comma present");
}
else {
String string1;
String string2;
Scanner inSS = new Scanner(userInput);
String commaHold;
commaHold = inSS. //FIXME this is where the problem is
string1 = inSS.next();
string2 = inSS.next();
System.out.println(string1 + " " + string2);
}
}
This can be achieved simply by splitting and checking that the result is an array of two Strings
String input = scnr.nextLine();
String [] names = input.split (",");
while (names.length != 2) {
System.out.println ("Enter with one comma");
input = scnr.nextLine();
names = input.split (",");
}
// now you can use names[0] and names[1]
edit
As you can see the code for inputting the data is duplicated and so could be refactored

Java scanner input mismatch when using space in input

I am using the scanner in java and am trying to enter a space in my input for option 2 (removing a user from my hashmap) but when I add a space in my answer I get an InputMismatchException. while researching I came across this thread Scanner Class InputMismatchException and Warnings that says to use this line of code to solve the issue: .useDelimiter(System.getProperty("line.separator")); i have added this and now my option 2 goes into a never-ending loop of me inputting data. Here is my code:
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
AddressBook ad1 = new AddressBook();
String firstName="";
String lastName="";
String key="";
int choice=0;
do{
System.out.println("********************************************************************************");
System.out.println("Welcome to the Address book. Please pick from the options below.\n");
System.out.println("1.Add user \n2.Remove user \n3.Edit user \n4.List Contact \n5.Sort contacts \n6.Exit");
System.out.print("Please enter a choice: ");
choice = scan.nextInt();
if(choice==1){
//Add user
System.out.print("Please enter firstname: ");
firstName=scan.next();
System.out.print("Please enter lastname: ");
lastName=scan.next();
Address address = new Address();
key = lastName.concat(firstName);
Person person = new Person(firstName,lastName);
ad1.addContact(key,person);
System.out.println("key: " + key);
}
else if(choice==2){
//Remove user
System.out.println("Please enter name of user to remove: ");
scan.useDelimiter(System.getProperty("line.separator"));
key=scan.next();
System.out.println("name:" + key);
ad1.removeContact(key);
}
else if(choice==3){
//Edit user
}
else if(choice==4){
//List contact
ad1.listAllContacts();
}
else if(choice==5){
//Sort contacts
}
}while(choice!=6);
}
}
The reason why I need to use a space is to remove a user from my hashmap I need to enter their full name as the key is a concatenation of their last and firstname, any help will be appreciated
nextInt() behaves similar to next() that is when it read a line it places the cursor behind it.
Example:
You give 6 as input
6
^(scanner's cursor)
So next time when you call nextLine(). It will return the whole line after that cursor which is empty in this case.
To fix this issue you need to call an extra nextLine() so that the Scanner closes the previous line it was reading and move on to the next line.
You could do this
System.out.print("Please enter a choice: ");
choice = scan.nextInt(); // Reads the int
scan.nextLine(); // Discards the line
And in choice 2 since you want full name of user you could just use nextLine() to get whole line along with space.
//Remove user
System.out.println("Please enter full name of user to remove: ");
key=scan.nextLine();
System.out.println("name:" + key);
ad1.removeContact(key);
Or you could do something similar to what you did in choice 1
System.out.print("Please enter firstname: ");
firstName=scan.next();
System.out.print("Please enter lastname: ");
lastName=scan.next();
key = lastName.concat(firstName);
System.out.println("name:" + key);
ad1.removeContact(key);
scan.nextLine(); // This is will make sure that in you next loop `nextInt()` won't give an input mismatch exception

2nd JOptionPane won't come up

I'm just starting out with Java and programming in general. Could someone please explain to me why the second dialog box won't show up after I've entered the information for the first one?
Thanks!
// Java Practice
import javax.swing.JOptionPane;
import java.util.Scanner;
public class DialogTest
{
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
String firstname;
String lastname;
int age;
JOptionPane.showInputDialog("What is " +
"your first name?");
firstname = keyboard.nextLine();
JOptionPane.showInputDialog("What is " +
"your last name?");
lastname = keyboard.nextLine();
JOptionPane.showInputDialog("How old are you?");
age = keyboard.nextInt();
JOptionPane.showMessageDialog(null, "I see, so your name is: " + firstname + lastname + " and you are" + age + " years old.");
System.exit(0);
}
}
JOptionPane.showInputDialog() returns a String that contains the value entered by the user. Instead of using the Scanner class, store the return value of the method call into your variables:
String firstname, lastname, age;
firstname = JOptionPane.showInputDialog("What is " +
"your first name?");
lastname = JOptionPane.showInputDialog("What is " +
"your last name?");
age = JOptionPane.showInputDialog("How old are you?");
JOptionPane.showMessageDialog(null, "I see, so your name is: " + firstname + lastname + " and you are" + age + " years old.");
You don't need both JOptionPane and Scanner. You only need one (I highly recommend Scanner over the other).
What's happening is this: The call to JOptionPane is opening a dialog for your user to enter a value. That value is returned by this method call, which you do nothing with. Then after the dialog is finished, you call keyboard.nextLine() which blocks the program until the user enters another value into the command line window (or your IDE if you're running it through that).
If you want to see both options available to you, try commenting out the keyboard lines and setting firstname = JOptionPane... and so on. Once you've tried out that program, do the opposite: comment out the JOptionPane calls and replace them with System.out.println calls.
As someone who began learning input handling via JOptionPane, I believe Scanner is a much better utility.

How to change cursor's place at java

I am doing a project with using arraylist. I want a alphabet and a number in order from user .
char karakter = klavye.next().charAt(0);
int sayi = klavye.nextInt();
When i write that after first input cursor pass to the bottom line
like:
A
7
But i want like that A 7 Why do not they side by side? How can i do this?
If I am understanding you correctly you just want the user to be able to enter two tokens on the same line. One approach is to just get the whole line and then split it into tokens.
Scanner klavye = new Scanner(System.in);
String tokens[] = klavye.nextLine().split(" ");
while(tokens.length < 2) {
System.out.println("Bad line, enter again:");
tokens = klavye.nextLine().split(" ");
}
char karakter = tokens[0].charAt(0);
System.out.println("karakter = " + karakter);
int sayi = Integer.valueOf(tokens[1]);
System.out.println("sayi = " + sayi);
The user should type A 7 then press the enter key only once at the end.

Categories

Resources