How do I get the name input to read whitespaces - java

So im having trouble getting the first read input to read all inputs on the line. But for some reason it doesnt take into consideration of whitespaces. in fact, it considers the whitespace from the print information as part of the whitespace. only name has this problem. ID does not have this problem. I would just like to know how to fix this one problem since it is giving me the most trouble.
public class Project2 {
public static Scanner sc = new Scanner (System.in);
public static void main(String[] args) {
PersonList PersonList = new PersonList();
System.out.print("Welcome to my personal Management Program\n\n");
System.out.print("\nChoose one of the following options: \n\n");
//print out options for user
for (;;) {
int input = 0;
System.out.print("1- Enter the information of a faculty\n");
System.out.print("2- Enter the information of a student\n");
System.out.print("3- Print tuition person for a student\n");
System.out.print("4- Print faculty information\n");
System.out.print("5- Enter the information of a staff member\n");
System.out.print("6- Print the information of a staff member\n");
System.out.print("7-Exit the program\n\n");
System.out.print("\tEnter a selection: ");
input = sc.nextInt();
if (input == 1) {
faculty f = new faculty();
System.out.print("Enter the faculty info:\n");
System.out.print("\tName of Faculty: ");
f.name = sc.nextLine();
System.out.print("\tID: ");
f.ID = sc.nextLine();
String rank, department;
for(;;) {
System.out.print("\n\tRank: ");
rank = sc.nextLine();
if (rank.equalsIgnoreCase("professor") || rank.equalsIgnoreCase("adjunct")) {
f.rank = rank;
break;
}
else {
System.out.print("\"" + rank +"\" is invalid");
}
}
for(;;) {
System.out.print("\tDepartment: ");
department = sc.nextLine();
if (department.equalsIgnoreCase("mathematics") || department.equalsIgnoreCase("engineering") || department.equalsIgnoreCase("sciences")) {
f.Department = department;
break;
}
else {
System.out.print("\"" + department +"\" is invalid");
}
}
System.out.println("Faculty added!");
PersonList.addPerson(f);
}

When you read the selection input = sc.nextInt() it returns the next integer it finds, stopping right after that. It returns the choice typed but it does not read the newline. If you typed 1 (space one space) it would skip over the leading space then read the 1 and stop; it would not read the following space or the newline.
So when you get to the faculty name f.name = sc.nextLine() it reads whatever was remaining from the input = line, which is probably just a newline, and returns that for the name.
Now when you get to f.ID = sc.nextLine() the input buffer is clear so it reads ID as you expect it to.
A simple solution is to just finish reading the line by adding a nextLine() after reading the selection:
System.out.print("\tEnter a selection: ");
input = sc.nextInt();
sc.nextLine(); // Read the remainder of the line and throw it away
Read the javadoc for java.util.Scanner and for nextInt() and nextInt(radix)

Related

save several names in a string array [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
The question is that write a class named Seyyed includes a method named seyyed. I should save the name of some people in a String array in main method and calculate how many names begin with "Seyyed". I wrote the following code. But the output is unexpected. The problem is at line 10 where the sentence "Enter a name : " is printed two times at the first time.
import java.util.Scanner;
public class Seyyed {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
String[] names = new String[n];
for (int i = 0; i < names.length; i++) {
System.out.println("Enter a name : ");
names[i] = in.nextLine();
}
int s = seyyed(names);
System.out.println("There are " + s + " Seyyed");
in.close();
}
static int seyyed(String[] x) {
int i = 0;
for (String s : x)
if (s.startsWith("Seyyed"))
i++;
return i;
}
}
for example When I enter 3 to add 3 names the program 2 times repeats the sentence "Enter a name : " and the output is something like this:
Enter the number of names :3
Enter a name :
Enter a name :
Seyyed Saber
Enter a name :
Ahmad Ali
There are 1 Seyyed
I can enter 2 names while I expect to enter 3 names.
The problem occurs as you hit the enter key, which is a newline \n character. nextInt() consumes only the integer, but it skips the newline \n. To get around this problem, you may need to add an additional input.nextLine() after you read the int, which can consume the \n.
Right after in.nextInt(); just add in.nextLine(); to consume the extra \n from your input. This should work.
Original answer: https://stackoverflow.com/a/14452649/7621786
When you enter the number, you also press the Enter key, which does an "\n" input value, which is captured by your first nextLine() method.
To prevent that, you should insert an nextLine() in your code to consume the "\n" character after you read the int value.
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
in.nextLine();
String[] names = new String[n];
Good answer for the same issue: https://stackoverflow.com/a/7056782/4983264
nextInt() will consume all the characters of the integer but will not touch the end of line character. So when you say nextLine() for the first time in the loop it will read the eol left from the previous scanInt(), so basically reading an empty string. To fix that use a nextLine() before the loop to clear the scanner or use a different scanner for Strings and int.
Try this one:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
in.nextLine();
String[] names = new String[n];
for (int i = 0; i < names.length; i++) {
System.out.println("Enter a name : ");
names[i] = in.nextLine();
}
int s = seyyed(names);
System.out.println("There are " + s + " Seyyed");
in.close();
}
static int seyyed(String[] x) {
int i = 0;
for (String s : x)
if (s.startsWith("Seyyed"))
i++;
return i;
}

How can I get multiple user inputs and save their value? [duplicate]

How could I read input from the console using the Scanner class? Something like this:
System.out.println("Enter your username: ");
Scanner = input(); // Or something like this, I don't know the code
Basically, all I want is have the scanner read an input for the username, and assign the input to a String variable.
A simple example to illustrate how java.util.Scanner works would be reading a single integer from System.in. It's really quite simple.
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
To retrieve a username I would probably use sc.nextLine().
System.out.println("Enter your username: ");
Scanner scanner = new Scanner(System.in);
String username = scanner.nextLine();
System.out.println("Your username is " + username);
You could also use next(String pattern) if you want more control over the input, or just validate the username variable.
You'll find more information on their implementation in the API Documentation for java.util.Scanner
Scanner scan = new Scanner(System.in);
String myLine = scan.nextLine();
Reading Data From The Console
BufferedReader is synchronized, so read operations on a BufferedReader can be safely done from multiple threads. The buffer size may be specified, or the default size(8192) may be used. The default is large enough for most purposes.
readLine() « just reads data line by line from the stream or source. A line is considered to be terminated by any one these: \n, \r (or) \r\n
Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace(\s) and it is recognised by Character.isWhitespace.
« Until the user enters data, the scanning operation may block, waiting for input.
« Use Scanner(BUFFER_SIZE = 1024) if you want to parse a specific type of token from a stream.
« A scanner however is not thread safe. It has to be externally synchronized.
next() « Finds and returns the next complete token from this scanner.
nextInt() « Scans the next token of the input as an int.
Code
String name = null;
int number;
java.io.BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
name = in.readLine(); // If the user has not entered anything, assume the default value.
number = Integer.parseInt(in.readLine()); // It reads only String,and we need to parse it.
System.out.println("Name " + name + "\t number " + number);
java.util.Scanner sc = new Scanner(System.in).useDelimiter("\\s");
name = sc.next(); // It will not leave until the user enters data.
number = sc.nextInt(); // We can read specific data.
System.out.println("Name " + name + "\t number " + number);
// The Console class is not working in the IDE as expected.
java.io.Console cnsl = System.console();
if (cnsl != null) {
// Read a line from the user input. The cursor blinks after the specified input.
name = cnsl.readLine("Name: ");
System.out.println("Name entered: " + name);
}
Inputs and outputs of Stream
Reader Input: Output:
Yash 777 Line1 = Yash 777
7 Line1 = 7
Scanner Input: Output:
Yash 777 token1 = Yash
token2 = 777
There is problem with the input.nextInt() method - it only reads the int value.
So when reading the next line using input.nextLine() you receive "\n", i.e. the Enter key. So to skip this you have to add the input.nextLine().
Try it like that:
System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (it consumes the \n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();
There are several ways to get input from the user. Here in this program we will take the Scanner class to achieve the task. This Scanner class comes under java.util, hence the first line of the program is import java.util.Scanner; which allows the user to read values of various types in Java. The import statement line should have to be in the first line the java program, and we proceed further for code.
in.nextInt(); // It just reads the numbers
in.nextLine(); // It get the String which user enters
To access methods in the Scanner class create a new scanner object as "in". Now we use one of its method, that is "next". The "next" method gets the string of text that a user enters on the keyboard.
Here I'm using in.nextLine(); to get the String which the user enters.
import java.util.Scanner;
class GetInputFromUser {
public static void main(String args[]) {
int a;
float b;
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
s = in.nextLine();
System.out.println("You entered string " + s);
System.out.println("Enter an integer");
a = in.nextInt();
System.out.println("You entered integer " + a);
System.out.println("Enter a float");
b = in.nextFloat();
System.out.println("You entered float " + b);
}
}
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] arguments){
Scanner input = new Scanner(System.in);
String username;
double age;
String gender;
String marital_status;
int telephone_number;
// Allows a person to enter his/her name
Scanner one = new Scanner(System.in);
System.out.println("Enter Name:" );
username = one.next();
System.out.println("Name accepted " + username);
// Allows a person to enter his/her age
Scanner two = new Scanner(System.in);
System.out.println("Enter Age:" );
age = two.nextDouble();
System.out.println("Age accepted " + age);
// Allows a person to enter his/her gender
Scanner three = new Scanner(System.in);
System.out.println("Enter Gender:" );
gender = three.next();
System.out.println("Gender accepted " + gender);
// Allows a person to enter his/her marital status
Scanner four = new Scanner(System.in);
System.out.println("Enter Marital status:" );
marital_status = four.next();
System.out.println("Marital status accepted " + marital_status);
// Allows a person to enter his/her telephone number
Scanner five = new Scanner(System.in);
System.out.println("Enter Telephone number:" );
telephone_number = five.nextInt();
System.out.println("Telephone number accepted " + telephone_number);
}
}
You can make a simple program to ask for the user's name and print whatever the reply use inputs.
Or ask the user to enter two numbers and you can add, multiply, subtract, or divide those numbers and print the answers for user inputs just like the behavior of a calculator.
So there you need the Scanner class. You have to import java.util.Scanner;, and in the code you need to use:
Scanner input = new Scanner(System.in);
input is a variable name.
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name: ");
s = input.next(); // Getting a String value
System.out.println("Please enter your age: ");
i = input.nextInt(); // Getting an integer
System.out.println("Please enter your salary: ");
d = input.nextDouble(); // Getting a double
See how this differs: input.next();, i = input.nextInt();, d = input.nextDouble();
According to a String, int and a double varies the same way for the rest. Don't forget the import statement at the top of your code.
A simple example:
import java.util.Scanner;
public class Example
{
public static void main(String[] args)
{
int number1, number2, sum;
Scanner input = new Scanner(System.in);
System.out.println("Enter First multiple");
number1 = input.nextInt();
System.out.println("Enter second multiple");
number2 = input.nextInt();
sum = number1 * number2;
System.out.printf("The product of both number is %d", sum);
}
}
When the user enters his/her username, check for valid entry also.
java.util.Scanner input = new java.util.Scanner(System.in);
String userName;
final int validLength = 6; // This is the valid length of an user name
System.out.print("Please enter the username: ");
userName = input.nextLine();
while(userName.length() < validLength) {
// If the user enters less than validLength characters
// ask for entering again
System.out.println(
"\nUsername needs to be " + validLength + " character long");
System.out.print("\nPlease enter the username again: ");
userName = input.nextLine();
}
System.out.println("Username is: " + userName);
To read input:
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
To read input when you call a method with some arguments/parameters:
if (args.length != 2) {
System.err.println("Utilizare: java Grep <fisier> <cuvant>");
System.exit(1);
}
try {
grep(args[0], args[1]);
} catch (IOException e) {
System.out.println(e.getMessage());
}
import java.util.*;
class Ss
{
int id, salary;
String name;
void Ss(int id, int salary, String name)
{
this.id = id;
this.salary = salary;
this.name = name;
}
void display()
{
System.out.println("The id of employee:" + id);
System.out.println("The name of employye:" + name);
System.out.println("The salary of employee:" + salary);
}
}
class employee
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
Ss s = new Ss(sc.nextInt(), sc.nextInt(), sc.nextLine());
s.display();
}
}
Here is the complete class which performs the required operation:
import java.util.Scanner;
public class App {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final int valid = 6;
Scanner one = new Scanner(System.in);
System.out.println("Enter your username: ");
String s = one.nextLine();
if (s.length() < valid) {
System.out.println("Enter a valid username");
System.out.println(
"User name must contain " + valid + " characters");
System.out.println("Enter again: ");
s = one.nextLine();
}
System.out.println("Username accepted: " + s);
Scanner two = new Scanner(System.in);
System.out.println("Enter your age: ");
int a = two.nextInt();
System.out.println("Age accepted: " + a);
Scanner three = new Scanner(System.in);
System.out.println("Enter your sex: ");
String sex = three.nextLine();
System.out.println("Sex accepted: " + sex);
}
}
There is a simple way to read from the console.
Please find the below code:
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Reading of Integer
int number = sc.nextInt();
// Reading of String
String str = sc.next();
}
}
For a detailed understanding, please refer to the below documents.
Doc
Now let's talk about the detailed understanding of the Scanner class working:
public Scanner(InputStream source) {
this(new InputStreamReader(source), WHITESPACE_PATTERN);
}
This is the constructor for creating the Scanner instance.
Here we are passing the InputStream reference which is nothing but a System.In. Here it opens the InputStream Pipe for console input.
public InputStreamReader(InputStream in) {
super(in);
try {
sd = StreamDecoder.forInputStreamReader(in, this, (String)null); // ## Check lock object
}
catch (UnsupportedEncodingException e) {
// The default encoding should always be available
throw new Error(e);
}
}
By passing the System.in this code will opens the socket for reading from console.
You can flow this code:
Scanner obj= new Scanner(System.in);
String s = obj.nextLine();
You can use the Scanner class in Java
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
System.out.println("String: " + s);
import java.util.Scanner; // Import the Scanner class
class Main { // Main is the class name
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine(); // Read user input
System.out.println("Username is: " + userName); // Output user input
}
}
you have wrote
Scanner = input()
this is wrong method, you have to make an integer or a string, i would like to prefer string, and then give a string any name that can be i that can be n or anything else, remember that you are giving name to username you can also give name username also, and the code is
String username = sc.nextline();
System.our.println("the username is" + username);
I hope you understand now

How to limit the input to the Scanner?

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int inputInt = checkInput(in, "Enter an integer and a base: ");
int inputBase = checkInput(in, "");
}
public static int checkInput(Scanner in, String prompt) {
System.out.print(prompt);
while (!in.hasNextInt()) {
in.next();
System.out.println("Sorry, that is an invalid input.");
System.out.print(prompt);
}
return in.nextInt();
}
This method works and doesn't return any bad input i.e., ; p "hello".
My question is how can I limit the number of inputs the scanner will read. Say I input 5 five % ; but I only want 5 and five to be passed in to my method and the rest dropped.
I looked through the Java API but couldn't find a method that would limit the amount of user input accepted. Am I just missing it or is there another way to do this?
Edit: I have tried using the .length() method to limit the input but then that doesn't allow integers greater than the .length() parameter.
Here is a working sample of how you could accomplish what you need. I broke it up so that the user is prompted once for each input which makes it easier to validate. I changed your checkInput method to getInput which only returns valid user input as a String where it is then converted into an int.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int inputInt = Integer.parseInt(getInput(in, "Enter an integer: "));
int inputBase = Integer.parseInt(getInput(in, "Enter a base: "));
System.out.println("Int: " + inputInt + ", base: " + inputBase);
}
public static String getInput(Scanner in, String prompt) { // Get valid user input
System.out.print(prompt); // Tell user what to input
String text = "";
while (true) { // Keep looping until valid input is found
text = in.nextLine(); // Get input from stdin
if(isInteger(text)) // Check if they put in integer
break; // Exit loop
System.out.print("Try again, " + prompt); // Wasn't valid, prompt again
}
return text; // Return valid user input
}
private static boolean isInteger(String str) { // Check if string is integer
try {
Integer.parseInt(str); // If this doesn't fail then it's integer
return true;
} catch(NumberFormatException e) {
return false; // Wasn't integer
}
}
Sample run:
Enter an integer: 2 dog five 3
Try again, Enter an integer: 2
Enter a base: cat
Try again, Enter a base: 3
Int: 2, base: 3
It helps to separate functionality - you were trying to read input, validate input, and convert to int all in one method. If you break it up it becomes easier to manage.
Scanner sc= new Scanner(System.in);
String string = sc.findInLine(".{500}"); // length of your input you want
findInLine(String pattern)
method of Scanner class of java.util package. This method returns a String object that satisfies the pattern specified as method argument.
see this article
If you want to only get the first two words (or strings delimited by spaces) you can use the str.split(" "); method.
For example:
String input = in.nextLine(); // Gets the next line the user enters (as a String)
String[] inputWords = input.split(" "); // inputWords[0] is first word, inputWords[1]
// is second word... etc
String validInput = inputWords[0] + " " + inputWords[1]; // Combines the first and
// second words into a string, so if you had "5 five %" validInput would be "5 five"
// inputWords[0] is "5", inputWords[1] is "five", inputWords[3] is "%" etc for any other words...
This will essentially limit the number of inputs to two words. I hope this helps!
Scanner scan = new Scanner(System.in);
System.out.println ("enter a 2 numbers");
String s;
s = scan.nextLine();
Scanner scan2 = new Scanner(s);
int one = scan2.nextInt();
int two = scan2.nextInt();
System.out.println (" int 1 = " + one + " int 2 = " + two);
enter a 2 numbers
23 45 68 96 45
int 1 = 23 int 2 = 45
Process completed.

Using Scanner - at java.util.Scanner.next(Unknown Source) java.util.NoSuchElementException

My full code is pasted here. Below are the 2 methods that are related to my question.
private static boolean playGameAgain()
{
char playAgain = 'y';
Scanner input = new Scanner(System.in);
while(playAgain != 'n')
{
System.out.println("Go again?(y/n)");
/// PROBLEM HERE.... Somehow, it will NOT wait for INPUT. It just throws an error
playAgain = input.next().charAt(0);
}
input.close();
return (playAgain != 'y')?false:true;
}
// [Trimmed]
public static void initialize(ArrayList<String> names, ArrayList<Integer> scores)
{
Scanner input = new Scanner(System.in);
for (int i = 1; i <= 5; i++)
{
System.out.println("Enter the name for score #" + i + ":");
names.add(input.nextLine());
System.out.println();
System.out.println("Enter the score for score #" + i + ":");
while(!input.hasNextInt())
{
//input.nextLine();
System.out.println("Please input a valid integer value for the score for #" + i + ":");
if(!input.hasNextInt())
input.nextLine();
}
scores.add(input.nextInt());
input.nextLine();
}
input.close();
}
I have tried many combinations of how to read in one character. This used to work, that I could read in one character by using:
Scanner input = new Scanner(System.in);
char temp = input.next().charAt(0);
But, somehow, in this program I wrote, it won't work.
It's a program that will read in 5 user names (strings) & 5 scores (integers) and put them in 2 arrays. It will sort the arrays in descending order and then it will print them out. So, the only problem I have is asking if they want to play again and taking some char input to see if they want to play again (y/n)?
Please help if you can. I've tried many combinations of: if (input.hasNext()), to no avail.
You are not setting playAgain to something other than 'y' in playGameAgain(). You have a bug here.

Java - Adding constraints

I have made this class for fun, and now I want to add some constraints and if statements. But don't know how.
Problem 1) I don't know how to do an if statement on System.out.print outputs. Say, if the user enter more than 50 characters then they'll be stopped.
I know how to do this in MySQL but not in Java as I'm very inexperienced ATM. :|
Problem 2) I also want to restrict myself from entering digits if it's nextLine, or text if it's nextInt.
Can anyone help me on these two problems?
import java.util.Scanner;
class AppForm {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name... ");
System.out.println("Your name is " + sc.nextLine());
System.out.print("Enter your age... ");
System.out.println("Your age is " + sc.nextInt());
}
}
Thanks.
You should start by breaking apart the input and output code by storing the result of nextLine() in a variable:
System.out.print("Enter your name... ");
String line = sc.nextLine();
System.out.println("Your name is " + line);
You can then perform any check you need on the line string variable. The typical paradigm in the case of an interactive program is to print out an error message and ask the user to repeat the entry in case of invalid input:
System.out.print("Enter your name... ");
String line = sc.nextLine();
while (line.length() > 50) {
System.out.println("Error: you entered more than 50 characters");
// Ask the user for their name again...
System.out.print("Enter your name... ");
line = sc.nextLine();
}
System.out.println("Your name is " + line);
Unfortunately there is no way to prevent the user from typing invalid characters - you can only check the content of the line after the user has finished typing and your program receives the typed line.
I would recommend at taking a look at while loops.
Some possibilities:
String name;
do {
System.out.print("Enter your name... ");
String line = sc.nextLine();
while (StringUtils.isEmpty(name) || name.length() > 50)
Or:
String name;
while (StringUtils.isEmpty(name)) {
System.out.print("Enter your name... ");
name = sc.nextLine();
if (name.length >= 50) {
System.out.println("Max name length is 50");
}
}
But there are plenty of flow control options.

Categories

Resources