Scanner skipping input, possible white space? [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
I just started Java and wanted to tinker with the syntax. Whenever I input "F" into gender and age being greater than or equal to 20 I should be prompted to input if the user is married or not, for some reason the scanner is skipping over it. Everything else works fine.
Output I'm getting:
Whats is your gender (M or F): F
First name: Kim
Last name: Kardashian
Age: 32
Are you married, Kim (Y or N)?
Then I shall call you Ms. Kardashian.
Code:
import java.util.Scanner;
public class GenderGame
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int age = 0;
String Gender = null, fName = null, lName = null, M = null, type = null;
System.out.print("Whats is your gender (M or F): ");
Gender = sc.nextLine();
Gender = Gender.toUpperCase();
System.out.print("First name: ");
fName = sc.nextLine();
System.out.print("Last name: ");
lName = sc.nextLine();
System.out.print("Age: ");
age = sc.nextInt();
if(Gender.equals("F") && age >= 20)
{
System.out.print("\nAre you married, " + fName + " (Y or N)? ");
M = sc.nextLine();
M = M.toUpperCase();
if(M.equals("Y"))
{
type = "Mrs. ";
type = type.concat(lName);
}
else
{
type = "Ms. ";
type = type.concat(lName);
}
}
else if(Gender.equals("F") && age < 20)
{
type = fName.concat(" " + lName);
}
else if(Gender.equals("M") && age >= 20)
{
type = "Mr. ";
type = type.concat(lName);
}
else if(Gender.equals("M") && age < 20)
{
type = fName.concat(" " + lName);
}
else
{
System.out.println("There was incorrect input. EXITING PROGRAM");
System.exit(1);
}
System.out.println("\nThen I shall call you " +type+ ".");
}
}

The nextInt() method of Scanner leaves the new line character out, that is, it does not consume it. This newline character is is consumed by your nextLine() method, which is why you do not see it wait for your input.
To avoid this, call sc.nextLine() after age = sc.nextInt();, then leave the rest of code unchanged.
...
System.out.print("Age: ");
age = sc.nextInt();
sc.nextLine(); //added
if(Gender.equals("F") && age >= 20)
{
System.out.print("\nAre you married, " + fName + " (Y or N)? ");
M = sc.nextLine();
M = M.toUpperCase();
if(M.equals("Y"))
{
type = "Mrs. ";
type = type.concat(lName);
}
...

Related

Java iterate through array [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 6 years ago.
I am trying to write a java program with 2 arrays 1 for name (String) and the other representing age (integer) the program should iterate and ask for a max of 10 names and ages of each, then display all array items as well as max and min ages of each, or unless the user enters 'done' or 'DONE' mid-way through.
I have the following code although struggling to loop around and ask user for names and ages x10.
Any suggestions?
Thank you.
import java.util.Scanner;
public class AgeName {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int numTried = 1;
int ageTried = 1;
boolean stop = false;
String name = "";
String[] num = new String[10];
int[] age = new int[10];
while(numTried <= 10 && ageTried <=10 && !stop){
System.out.print("Enter name " + numTried + ": ");
name = input.nextLine();
System.out.print("Now enter age of " + name + ": ");
int userAge = input.nextInt();
if(name.toUpperCase().equals("DONE")){
stop = true;
}else{
num[numTried - 1] = name;
age[ageTried -1] = userAge;
}
numTried ++;
ageTried ++;
}
for(String output : num){
if(!(output == null)){
System.out.print(output + "," );
}
}
input.close();
}
}
You can use a Map<String,Integer>:
HashMap<String, Integer> map = new HashMap<String, Integer>();
String[] num = new String[10];
for (int i = 0; i < 10; i++) {
System.out.print("Enter name " + numTried + ": ");
name = input.nextLine();
System.out.print("Now enter age of " + name + ": ");
int userAge = input.nextInt();
num[i] = name;
map.put(name, userAge);
}
for (String output : num) {
if (!(output == null)) {
System.out.print(output + ","+ map.get(output));
}
}
Map as its name suggests allows you to map one object type to another. the .put() method adds a record that contains a pair of String and an integer and maps the string to the int. The String has to be UNIQUE!!
You should ask in any iteration if the user is done. For example you could set a string variable as answer = "NO", and ask the user at the end of any iteration if he is done. If you try this remember to replace stop variable with answer at your iteration block condition.
System.out.println("Are you done: Choose -> YES or NO?");
answer = input.nextLine();
if (answer == "YES")
break;

Scanning different types of variables in one line

As the title says, I would like to scan the whole line of input just using one input from user. The input should be like "Eric 22 1".
If nextString() shouldn't be used that way, should I just use hasNext?
JAVA CODE :
import java.util.Scanner;
public class tugas1
{
public static void main(String []args)
{
String name;
int age;
boolean sex;
Scanner sc = new Scanner(System.in);
System.out.println("Please input your name, age, and sex(input 1 if you are a male, or 0 if you are a female) :");
name = sc.nextString();
age = sc.nextInt();
sex = sc.nextBoolean();
if(isString(name))
{
if(isInteger(age))
{
if(isBoolean(sex))
{
System.out.println("Correct format. You are :" +name);
}
else
{
System.out.println("Please input the age in integer");
}
}
else
{
System.out.println("Please input the age in integer");
}
}
else
{
System.out.println("Please input the name in string");
}
}
}
After adding and editing the lines :
System.out.println("Please input your name, age, and sex(input 1 if you are a male, or 0 if you are a female) :");
String input = sc.nextLine();
String[] inputAfterSplit = input.split(" ");
String name = inputAfterSplit[0];
int age = Integer.parseInt(inputAfterSplit[1]);
boolean sex = Boolean.parseBoolean(inputAfterSplit[2]);
I would like to add if(name instanceof String). I haven't touched Java since a long time and I forgot is that the way of using instanceof, or is that wrong?
The point is I want to compare if the input var is in int or string or bool.
if(name instanceof String)
{
if(age instanceof Integer)
{
if(sex instanceof Boolean)
{
System.out.println("All checked out")
}
else
{
System.out.println("Not boolean")
}
else
{
System.out.println("Not int")
}
System.out.println("Not string")
}
Will these lines work?
Please input your name, age, and sex
As you need to insert values in specific sequence.
Use nextLine() and perform split
For Example:"Abc 123 true 12.5 M"
String s[]=line.split(" ");
And you will have
s[0]="Abc"
s[1]="123"
s[2]="true"
s[3]="12.5"
s[4]="M"
Than parse them to required type.
String first=s[0];
int second=Integer.parseInt(s[1].trim());
boolean third=Boolean.parseBoolean(s[2].trim());
double forth=Double.parseDouble(s[3].trim());
char fifth=s[4].charAt(0);
As your code suggest and as David said you can change just this
name = sc.next();//will read next token
age = sc.nextInt();
sex = (sc.next()).charAt(0);//change sex to character for M and F
//or //sex = sc.nextInt();//change it to int
first thing when we use scanner , we dont have a method called nextString()
so instead we must use next() which is to read string.
secondly when you want to read whole line then use nextLine() which will read entire line in the form of text and put it in a string.
now the String which is read as entire line can be split based on split character(assume it is space in our case)
then get the string array and parse each element to required type.
better if we use try/catch while parsing so that we can catch exception for unwanted format for the input and throw it to user.
sample code without try/catch but you use try/catch as per your need
Scanner sc = new Scanner(System.in);
System.out.println("Please input your name, age, and sex(input 1 if you are a male, or 0 if you are a female) :");
String input = sc.nextLine();
String[] inputAfterSplit = input.split(" ");
String firstParam = inputAfterSplit[0];
int secondParam=Integer.parseInt(inputAfterSplit[1]);
boolean thirdParam=Boolean.parseBoolean(inputAfterSplit[2]);
Reworked it all, this is the remake of the code just in case people are having same problem as mine..
int in the delcaration should be changed into Integer
import java.util.Scanner;
import java.lang.*;
public class tugas1
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Input number of line :");
int lineNum = sc.nextInt();
String[] name = new String[lineNum];
Integer[] age = new Integer[lineNum];
String[] gender = new String[lineNum];
System.out.println("Please input your name, age, and gender(Male/Female) \n(Separate each line by an enter) :");
for ( int i = 0; i < lineNum; i++)
{
System.out.print("Line " + (i+1) + " : ");
name[i] = sc.next();
age[i] = sc.nextInt();
gender[i] = sc.next();
}
for ( int j = 0; j < lineNum; j++ )
{
if (name[j] instanceof String)
{
if (age[j] instanceof Integer)
{
if (gender[j] instanceof String)
{
System.out.println("Person #" + (j+1) + " is " + name[j] + ", with age of " + age[j] + " years old, and gender " + gender[j]);
}
else
{
System.out.println("Gender is missing");
}
}
else
{
System.out.println("Age and Gender are");
}
}
else
{
System.out.println("Name, Age and Gender are missing");
}
}
}
}

While(true)-loop not breaking, scanner

I have a problem with some code. When I try to break my loop using "quit" it wont stop. If I begin with typing quit, it breaks as intended but the second time the loop runs and I type quit it's not breaking. What is the problem?
public static void interactionLoop() {
input = new Scanner(System.in);
String ssn = null;
String message = null;
int accountNr;
double amount;
while(true) {
for(Customers aCustomer : Customers.getCustomerList()) {
System.out.println(aCustomer.getName() + ", " + aCustomer.getSsn());
}
System.out.println("Choose a customer by using SSN.");
System.out.print(">> ");
ssn = input.nextLine();
if(ssn.equals("quit")) {
break;
}
Customers theChosenCustomer = Customers.getCustomerBasedOnSSN(ssn);
ArrayList<Accounts> accList = theChosenCustomer.getAccountList();
for(Accounts anAccount : accList) {
if(anAccount instanceof Savings) {
System.out.print("(Savings, " + anAccount.getAccountNr() + ")" + "\n");
}
if(anAccount instanceof Loans) {
System.out.print("(Loans, " + anAccount.getAccountNr() + ")" + "\n");
}
}
System.out.print("Enter the account that you want to work with using the account number:\n>> ");
accountNr = input.nextInt();
Accounts chosenAccount = theChosenCustomer.getSpecificAccount(accountNr);
System.out.println("Account balance: "+chosenAccount.getBalance());
for(Transaction t : chosenAccount.getTransaction()) {
System.out.println(t.getDateAndTime().getTime() +", " + t.getComment() +": " + t.getAmount());
}
System.out.println("\n");
System.out.print("Please enter the amount of money you wish you withdraw or deposit: ");
while(input.hasNext()) {
amount = input.nextDouble();
input.nextLine();
if(chosenAccount.isValid(amount)){
System.out.print("Please enter a comment: ");
message = input.nextLine();
Calendar transdatetime = Calendar.getInstance();
chosenAccount.makeTransaction(new Transaction(transdatetime,message,amount));
System.out.println("");
interactionLoop();
}
}
}
accountNr = input.nextInt();
From 2nd time onwards Scanner scans Integer from the Std InpuStream but then the newline remains which is taken by
ssn = input.nextLine();
due to which your program does not quit. Same goes for double. Better use
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
then use reader.readLine() and parse it into your desired data type. Eg. Integer.parseInt(reader.readLine())

Validity via comparing strings while iterating through an array

Sorry if my question seems a little vague.
Basically what I am trying to do is error check using string comparison on a constructor object, which is stored in an array. I think I have the right idea: (Count is a static int that iterates whenever an employee is added in another method)
public static void updateTitle(Employee searchArray[]) {
String searchID;
Scanner input = new Scanner(System.in);
System.out.println("Enter Employee ID for manipulation: ");
searchID = input.nextLine();
for (int i = 0; i < count; i++) {
String arrayID = searchArray[i].getEmployeeNumber();
if (searchID.equals(arrayID) == true) {
System.out.println("Employee: " + searchID + " found!");
System.out.println("Employee " + searchID
+ "'s current title is: "
+ searchArray[i].getEmployeeTitle());
System.out.println(" ");
System.out
.println("Would you like to change this employees title? (Y/N)");
System.out.println(" ");
String answer = input.nextLine().toUpperCase();
if (answer.equals("Y")) {
System.out.println("Enter new title: ");
String newTitle = input.nextLine();
searchArray[i].setEmployeeTitle(newTitle);
searchArray[i].updateTitle(newTitle);
}
if (answer.equals("N")) {
break;
}
} else if (searchID.equals(arrayID) == false) {
System.out.println("Please enter a valid ID!");
}
}
}
This successfully error checks, however because it is iterating through the array, it will display an error message before a validation message if the array element is > 0 and is found in the array. Is there any way to analyse every element of the array and produce the error message if and only if the ID is not found in any elements?
you definitely should read a book how to program in Java.
All code below should be rewritten, but I leave it for understanding the error.
public static void updateTitle(Employee searchArray[]) {
String searchID;
Scanner input = new Scanner(System.in);
System.out.println("Enter Employee ID for manipulation: ");
searchID = input.nextLine();
Employee found = null;
for (int i = 0; i < searchArray.length; i++) {
String arrayID = searchArray[i].getEmployeeNumber();
if (searchID.equals(arrayID)) {
found = searchArray[i];
break;
}
}
if (found != null) {
System.out.println("Employee: " + searchID + " found!");
System.out.println("Employee " + searchID + "'s current title is: " + found.getEmployeeTitle());
System.out.println(" ");
System.out.println("Would you like to change this employees title? (Y/N)");
System.out.println(" ");
String answer = input.nextLine();
if (answer.equalsIgnoreCase("Y")) {
System.out.println("Enter new title: ");
String newTitle = input.nextLine();
found.setEmployeeTitle(newTitle);
found.updateTitle(newTitle);
}
} else {
System.out.println("Please enter a valid ID!");
}
}

Print only twelve characters from user submitted string in Java

I have a user input their name as a string and then the name is printed out onto the screen. How can i limit what is printed to only 12 characters so that a user cannot type an insanely long name? Here is my code:
Scanner input = new Scanner(System.in);
System.out.print("Enter your player name: ");
String name= input.next();
System.out.print("\n" + name + " has started the game\n");
Something like:
String name = input.next();
name = name.length() > 12 ? name.substring(0, 11) : name;
and accept some of your previous answers.
{
public static void main (String[]args){
String s = new String();
String n = new String();
s = "ya ali madad";
if (s.length() > 10) {
n = s.substring(10, 12);
}
System.out.println("String s:" + s);
System.out.println("String n:" + n);}}

Categories

Resources