Program ends before scanner input object can be executed [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 7 years ago.
My program is not working as it should.
Purpose of the code: ask user name, gender, age - if age over 18, ask user if married. if user says yes, output Mr or Mrs in front of already given name.
I'm practicing nested if statements and getter/setter methods to return private variables.
I have tried: nesting the if statement that tests the gender and age status, then i tried using a switch statement instead of an if statement to test the marital status, then i tried nesting an if statement within the switch to test the gender and age. I have tried giving each of the if, else if clauses their own scanner input thinking that would just get it to function, but it did not.
I originally had the marital status as a getter/setter method, but took it out to simplify the problem.
I have looked for an answer, but it seems like the code is right, it just will not take the input!
The code I have is as follows:
package agemessage;
import java.util.Scanner;
public class AgeMessage {
public static void main(String[] args) {
info infoObject = new info(); //setter getter class to house input from user
Scanner in = new Scanner(System.in);
System.out.println("what is your name again?");
String input = in.nextLine();
infoObject.getName(input);
System.out.println("thanks, " + infoObject.setName() + " is that a boys name or a girls name?");
String gender = in.nextLine();
infoObject.getGender(gender);
System.out.println("How old are you " + infoObject.setName() + "?");
int ageInput = in.nextInt();
//infoObject.getAge(ageInput);
if (ageInput < 18) {
System.out.print("I shall just call you " + infoObject.setName() + ".");
System.exit(0);
} else if (ageInput >= 18) {
System.out.println("Are you married yet?");
}
//PROGRAM STOPS HERE -- DOES NOT EXECUTE INPUT
String status = in.nextLine();
if (status.equalsIgnoreCase("Y") && infoObject.setGender().equalsIgnoreCase("Girl")) {
System.out.println("I will have to call you Mrs. " + infoObject.setName() + ".");
} else if (status.equalsIgnoreCase("Y") && infoObject.setGender().equalsIgnoreCase("Boy")) {
System.out.println("I will have to call you Mr. " + infoObject.setName() + ".");
System.exit(0);
} else if (status.equalsIgnoreCase("N")) {
System.out.println("I will just call you " + infoObject.setName() + ".");
}
}// main end
}//class end
OUTPUT:
run:
what is your name again?
Carrie Ann Moss
thanks, Carrie Ann Moss is that a boy's name or a girls name?
girl
How old are you Carrie Ann Moss?
40
Are you married yet?
BUILD SUCCESSFUL (total time: 16 seconds)

Right now you don't have a proper setter, add one and see if it works.

Please try putting in.nextLine(); after int ageInput = in.nextInt();
In this way the scanner will not ignore the next line after Integer.
A possible duplicate would be Using scanner.nextLine()

There are a few things that need to be addressed before we solve your problem.
Code conventions. These help others read your code. Not required, but it does help.
Getters and setters: A getter gets the object. A setter sets the object. You're using them in reverse. Example below.
class Person{
int age;
public void setAge(int a){
age = a;
}
public int getAge(){
return age;
}
}
So in a program, let's say we have a Person object, called annie, who is 22 years old.
Person annie = new Person();
annie.setAge(22);
Later in the program, we want to say how old she is...
System.out.println("Annie is " + annie.getAge() +" years old.");
The getter gets the value of the age variable on the Person object called annie.
Now for the actual problem in your program, when nextInt is called, it does not parse the newline character. So what is happening is this:
int ageInput = in.nextInt();
Here, when you enter "40" and then press Enter, you're giving the program this:
"40\n"
nextInt only reads to the end of the integer, so it only reads the 40, not the newline character.
if (ageInput < 18) {
System.out.print("I shall just call you " + infoObject.setName() + ".");
System.exit(0);
} else if (ageInput >= 18) {
System.out.println("Are you married yet?");
}
This works correctly, printing out the "Are you married yet?" string.
However, it doesn't stop executing.
String status = in.nextLine();
Here's the problem. Your Scanner object, it hasn't passed beyond the previous newline character. So it immediately accepts the rest of the line, which is simply this:
"\n"
So the String status is then set to "\n".
if (status.equalsIgnoreCase("Y") && infoObject.setGender().equalsIgnoreCase("Girl")) {
System.out.println("I will have to call you Mrs. " + infoObject.setName() + ".");
} else if (status.equalsIgnoreCase("Y") && infoObject.setGender().equalsIgnoreCase("Boy")) {
System.out.println("I will have to call you Mr. " + infoObject.setName() + ".");
System.exit(0);
} else if (status.equalsIgnoreCase("N")) {
System.out.println("I will just call you " + infoObject.setName() + ".");
}
Since status is set to "\n", nothing else is printed, and the end of the main function is reached, terminating the program.
To fix this, put a in.nextLine() directly after in.nextInt(). This skips the rest of the line, allowing your program to continue into the previously skipped sections.

Related

My Exception is not working even i already created an If else statement for it

So I made an exception on another class called EmptyInputException, so basically the purpose of this is to inform the user if they enter a space in their output. Any thoughts why it's not working for me. The EmptyInputException, it's meant for the users if they accidentaly input a space instead of letters then it should print the message from the exception but in my case it's not working. When i try to input a blank answer there is no print message from the EmptyInputException
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String questions[] = {"What is the color of the sky? ", "What is 1 + 1? ",
"What is the capital of the Philippines? ", "Who is the current president of the Philippines? ",
"What is the capital of Japan? ", "What is 2 + 3? ",
"What is 9 + 1?", "What is the capital of the United States? ",
"What is 10 + 10? ", "How many hand fingers do humans have? "};
String choices[] = {"a","b","c"};
int x = 0;
int y = 0;
try {
while(x<=9) {
System.out.println("Choose a Letter: a , b , c");
System.out.println("No." + (x+1) + " " + questions[x]);
String answer = scan.next();
x++;
if(answer.equals(choices[0])) {
scan.nextLine();
} else if (answer.equals(choices[1])) {
scan.nextLine();
} else if (answer.equals(choices[2])) {
scan.nextLine();
} else if (answer.equals(" ")) {
throw new EmptyInputException();
} else {
throw new InvalidLetterException();
}
}
} catch(InvalidLetterException e) {
System.out.println(); //Spacing
System.out.println(e.getMessage());
System.out.println(); //Spacing
System.out.println("You can try again.");
System.out.println(); //Spacing
do {
System.out.println("No." + (y+1) + " " + questions[y]);
scan.next();
y++;
}while(y<=9);
} catch (EmptyInputException e) {
System.out.println(e.getMessage());
}
}
public class EmptyInputException extends Exception {
//QuizBee.java
public EmptyInputException() {
super("ERROR : Please do not enter spaces.");
}
public EmptyInputException(String message) {
super(message);
}
}
You are creating a Scanner with the default token delimiter, which its documentation states
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace.
And you are using the next() method to read in user input. That method works as follows according to its official Documentation:
Finds and returns the next complete token from this scanner. A
complete token is preceded and followed by input that matches the
delimiter pattern. This method may block while waiting for input to
scan, even if a previous invocation of hasNext() returned true.
The next() method uses the delimiter, which is whitespace in your case, to determine where an input begins and ends. That means that with whitespace as a delimiter, the next() method will and can never return a whitespace itself, because that is the used delimiter.
You could try playing around with your delimiter, but I'd rather suggest just using nextLine() to read in your input and then check if result is blank to determine the user entered nothing or just whitespaces:
String answer = scan.nextLine();
if (answer.isBlank()) {
throw new EmptyInputException();
}
From the information you gave #OH GOD SPIDERS is very likely right. To see more evidence, change
System.out.println(e.getMessage());
into
System.out.println(e.getClass().getName() + " " + e.getMessage());
or more easily
e.printStackTrace(System.out);
Once you know your code works you can still tweak the information that will be presented to the user.
The problem is in the Scanner class.
It returns tokens but not the token delimiters. And per default (you did not configure anything else) the delimiters will match any whitespace.
Thus the line
String answer = scan.next();
will not return if only linefeeds or space characters are entered, and all the rest of your handling code goes unused.
To get out of that, configure the scanner to only use carriage returns as delimiters.

Why are my while loops not working and ignoring code?

So, what I am trying to do is get my while loops to do different things based on different key words. What I want is that when I type yes, I want it to exit the program, when I type no, for it to print a new song, and if there is a spelling error, for a message to pop up and allow the user to re enter yes or no to print the same song. I have 4 or 5 songs that I want to print out based on these three commands. In my last while loop. I want it to repeat the song every time the user types continue, and for it to end when the user types yes. I want the same thing to happen where it prompts the user to type again if there is a spelling error. This worked before, and now it does not. When I make a spelling error, it prompts me to enter again but will not print out the song in that loop. It will send me to the last while loop, ignoring all code in between. That last loop will only recognize spelling errors and yes, not continue, even though it did before.
Here is one song loop and my last loop:
import java.io.*;
import java.util.*;
public class FullNurseryRhymes
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String aBCs, neverEnds, frogs, frogs2, monkeys, hdd, hdd2;
NurseryRhymes rhymes = new NurseryRhymes();
{
System.out.println("Is the baby asleep? yes\\no");
frogs=input.next();
int byeFrog = 2;
for(int i = 3; i >= 1; i--)
{
if (frogs.equalsIgnoreCase("no"))
{
System.out.print(i + " " + rhymes.getFrogs());
System.out.println(" " + byeFrog + " " + rhymes.getFrogs2());
byeFrog -= 1;
}
else if (frogs.equalsIgnoreCase("yes"))
{
System.out.println("The baby is asleep");
System.exit(0);
}
while(!frogs.equalsIgnoreCase("no"))
{
System.out.println("Non requested input, please retry.");
System.out.println("\nIs the baby asleep? continue\\yes");
frogs = input.next();
if(frogs.equalsIgnoreCase("no"))
{
System.out.print(i + " " + rhymes.getFrogs());
System.out.println(" " + byeFrog + " " + rhymes.getFrogs2());
byeFrog -= 1;
}
else if (frogs.equalsIgnoreCase("yes"))
{
System.out.println("The baby is asleep");
System.exit(0);
}
}
}
}
//last loop
{
System.out.println("Is the baby asleep? continue\\yes");
neverEnds = input.next();
while(neverEnds.equalsIgnoreCase("continue"))
{
System.out.println(rhymes.getNeverEnds());
System.out.println("Is the baby asleep? continue\\yes");
neverEnds = input.next();
}
if(neverEnds.equalsIgnoreCase("yes"))
{
System.out.println("The baby is asleep");
System.exit(0);
}
while(!neverEnds.equalsIgnoreCase("continue")||!neverEnds.equalsIgnoreCase("yes"))
{
System.out.println("Non requested input, please retry");
System.out.println("\nIs the baby asleep? continue\\yes");
neverEnds = input.next();
while (neverEnds.equalsIgnoreCase("continue"))
{
System.out.println(rhymes.getNeverEnds());
System.out.println("Is the baby asleep? continue\\yes");
neverEnds = input.next();
if(neverEnds.equalsIgnoreCase("yes"))
{
System.out.println("The baby is asleep");
System.exit(0);
}
}
if (neverEnds.equalsIgnoreCase("yes"))
{
System.out.println("The baby is asleep");
System.exit(0);
}
}
}
Based on the comments, it sounds like there is too much (potentially) relevant code for us to plough through.
There are three ways you could proceed with this.
You could learn how to use the debugger in your IDE. Use breakpoints and single stepping, and figure out where your mistakes are.
You could comment out parts of the code to track down where the problems are. That may also help you to create an MCVE
You could simplify the code by refactoring common / repetitious code into methods. For instance the "last loop" section is incredibly repetitious.
On the last point, it might actually be less work to throw this code away and start again ... after figuring out what common code can be implemented as methods.
Your question is a bit long. We don't need a story, just an explanation of your problem and a BIT of code, not your whole class. Try putting your while loop on the outside. Have a string outside the while loop called babySleep that starts as "no". Then, while(babySleep.equals("no") execute your code. Then at the end, check if the baby is a sleep, if he is, move on, if not, the while loop will re-execute. Also, instead of .equals try .equalsIgnoreCase so the user can type in "Yes" or "yES" etc.

Java scanner input if statement [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This line does not work: input=scan.nextLine();
You should give the program the input for the while loop, but it ignores completely this line. I don't know the problem and I am just a beginner. Could you help?
import java.util.*;
public class Fantasy2
{
public static void main ( String[] args )
{
String name;
String input="y";
int strength;
int health;
int luck;
int stats;
Scanner scan = new Scanner(System.in);
System.out.println("Welcome!");
System.out.println("Please enter the name of your character:");
name=scan.nextLine();
while(input.equals("y"))
{
System.out.println("Strength (1-10):");
strength=scan.nextInt();
System.out.println("Health (1-10):");
health=scan.nextInt();
System.out.println("Luck (1-10):");
luck=scan.nextInt();
stats=strength+health+luck;
if(stats>15)
{
System.out.println("You gave your character too much points! Do you want to change that?");
input=scan.nextLine();
}
else
{
System.out.println(name + " has these stats now: Strength:" + strength + ", Health: " + health + ", Luck: " + luck);
input="n";
}
}
System.out.println("Congratulation! You created successful your character!");
}
}
Sorry the statement posted below does not help your original problem but is another problem the line input = scan.nextLine(); works for me fine.
When using Scanner you must call another scan.nextLine(); after you scan.nextInt(); to get the line feed that the method scan.nextInt(); does not get
do this
System.out.println("Strength (1-10):");
strength=scan.nextInt();
System.out.println("Health (1-10):");
health=scan.nextInt();
System.out.println("Luck (1-10):");
luck=scan.nextInt();
stats=strength+health+luck;
scan.nextLine(); <--------- added code
You have to consume the extra new line that nextInt does not consume. Your options are to call another newLine after the last call to nextInt or better yet, read the integer input through nextLine and parse it:
private int readInteger()
{
int option = 0;
try
{
option = Integer.parseInt(input.nextLine());
}
catch (NumberFormatException e)
{
e.printStackTrace();
}
return option;
}
...
System.out.println("Strength (1-10):");
strength = readInteger();
System.out.println("Health (1-10):");
health = readInteger();
System.out.println("Luck (1-10):");
luck = readInteger();
With the Scanner
Scanner scan = new Scanner(System.in);
and the methods ( read API for detail)
next() - would read next characters until it found space ( or the delimiter used. by default space) and return String.
nextInt() - would read next characters until it found space ( or the delimiter used. by default space) and convert it into int and return.
Note** if you give input as 'xyz' you will get exception and your program would terminate.
if you give 5 7 for answer (Strength (1-10):) as per your program it would read 5 as strength and 7 as health. and will ask for luck.
nextLine() would read all characters until the end of line found ( while you enter in keyboard).
So the ideal implementation to avoid issues .
You can use nextLine and convert into int if not say as error and ask to enter correct value.
System.out.println("Strength (1-10):");
String str=scan.nextLine();
while (!isNumeric(str)){
System.out.println("Enter Valid Number Strength (1-10):");
str=scan.nextLine();
}
strength = Integer.parseInt(str);
public static boolean isNumeric(String str)
{
return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.
}
For example , when you call luck=scan.nextInt(); users enters 6 and enter key . 6 will capture by nextInt() and the enter key would capture by input=scan.nextLine(); .
So in order to get next input you have to ask scan.nextLIne() again like
luck=scan.nextInt();
scan.nextLIne();
Try to use this code instead of your while cycle:
boolean flag=true;
while(flag)
{
System.out.println("Strength (1-10):");
int strength=Integer.parseInt(scan.nextLine());
System.out.println("Health (1-10):");
int health=Integer.parseInt(scan.nextLine());
System.out.println("Luck (1-10):");
int luck=Integer.parseInt(scan.nextLine());
int stats=strength+health+luck;
if(stats>15)
{
System.out.println("You gave your character too much points! Do you want to change that?");
input=scan.nextLine();
}
else
{
System.out.println("has these stats now: Strength:" + strength + ", Health: " + health + ", Luck: " + luck);
input="n";
}
if(input.equals("n"))
flag = false;
}
System.out.println("Congratulation! You created successful your character!");
I don't know if this is a better way of doing it but give it a try.
Hope this helps.

User input value code to validate

In my CIS 220 Java Application 2 class, we have just went over the use of objects and classes with constructors and such. The whole goal of this assignment is to utilize a class and its methods to get the user employee data. I feel I've more or less finished the whole thing, but there is one last part. The data must be validated, as explained in this screenshot link http://puu.sh/7vzeI.jpg
I would assume employee ID needs to be 9 characters long as a string. The pay rate and hours worked must be doubles. Sadly I have no idea what sort of code I need in order to validate it in the class. I figured it was a while loop but it didn't seem to work.
Here is the main java method:
public class Project3 {
static Scanner console = new Scanner (System.in);
public static void main(String[] args) {
Employee worker1 = new Employee();
worker1.getEmployeeName();
worker1.getEmployeeNum();
worker1.getPayRate();
worker1.getEmployeeHours();
System.out.println("Employee Name: " + worker1.printEmployeeName());
System.out.println("Employee ID: " + worker1.printEmployeeNum());
System.out.println("Pay Rate: $" + worker1.printPayRate());
System.out.println("Hours Worked: " + worker1.printHoursWorked());
worker1.getNetPay();
}
}
These are the methods in a class titled "Employee" which are used by main:
public String getEmployeeName()
{
System.out.println("Please enter the employee's name: ");
employeeName = console.nextLine();
return employeeName;
}
// Method that prompts the user to enter their hours worked, then returns it as the reference
public double getEmployeeHours()
{
System.out.println("Enter the number of hours worked(a numeric value between 0.0 and 100.0): ");
hoursWorked = console.nextDouble();
return hoursWorked;
}
// Method that prompts the user to enter their employee ID, then returns it as the reference
public String getEmployeeNum ()
{
System.out.println("Please enter the employee's ID: ");
employeeNum = console.nextLine();
return employeeNum;
}
// Method that prompts the user to enter their pay rate, then returns it as the reference
public double getPayRate()
{
System.out.println("Please enter the employee's pay rate (a numeric value): ");
payRate = console.nextDouble();
return payRate;
}
Please forgive me if the format of this question is hideous, as I am still quite new to stack overflow.
I think you may not be clear on the concept of return methods. There is no point in making a return method if you are not going to use the returned value at any point. For example
public String getEmployeeName()
{
System.out.println("Please enter the employee's name: ");
employeeName = console.nextLine();
return employeeName;
}
// in the other class
worker1.getEmployeeName();
You never assign the String "worker1.getEmployeeName()" to anything so making this a return statement is useless. What I would do is that I would remove the getter methods aka "worker1.printEmployeeName()" and do this instead:
String name = worker1.printEmployeeName();
System.out.println("Employee Name: " + name);
Then in the method "printEmployeeName()" I would add my checks to see if the input was valid or not. like so:
(I don't think the name could have an invalid input except for maybe if it was null, so I will use the number instead.)
Okay so to validate the information I would do this:
public String getEmployeeNum ()
{
while(true)
{
System.out.println("Please enter the employee's ID: ");
try{
employeeNum = console.nextInt(); //this should be getting an integer not the line
}catch(Exception e){
employeeNum = 0;
}
if(String.valueOf(employeeNum).length() == 9)
return String.valueOf(employeeNum); // this will break you out of your loop and return the value
else{
System.out.println("Invalid input...");
continue;
}
}
}
Now I'll try an explain the code above
Because we are using "console.nextInt();" in order to check if what the user enters is not a string, a double or anything else that is not a integer I used a try catch statement. If you are unfamiliar with how the try catch works, it basically checks if there is an error with the code in the " try{ } " part and if there is do what is in the "catch(Exception e) { } " block. I could go in to more detail on it but that explains it enough for now. So if there is a problem with the input or we find an "error" with it we set the employeeNum to "0" (You'll see why in the next part).
Then we move on to the if statement "if(String.valueOf(employeeNum).length() == 9)" basically this will turn our input into a String so we can check the length (Remember if there is an error with the input the employeeNum will be "0" with the length of "1")
If the input is valid (9 numbers long) we then return it "return employeeNum;"
If it is not valid (Not long enough or too long) we tell the user that there was an error, and we restart the process.
I hope this helps some or at least gives you an idea on what to do next!
If you want to read and learn some more:
Try Catch : http://docs.oracle.com/javase/tutorial/essential/exceptions/try.html
Edit: (A Hint)
When you check if the values are doubles for the pay rate and hours use something like this:
try {
hoursWorked = console.nextDouble();
}catch(Exception e){
hoursWorked = -1.0;
}
if(hoursWorked > 0.0)
return hoursWorked;
// the end should be the same as the other example :)

How do I output this information that I have stored?

I have written this code so far, it is part of an assignment, but I am stuck and am not sure how to do part 2. I have completed part 1. Any suggestions on where to go from here?
Thanks!
Part 1.
Prompts the user for the following information and stores the input in appropriate variables:
Whether the user is left-handed
Whether the user's father was at least 5 ft 10 inches tall
The user's age in months
The age in months of a sibling or friend of the user
The user's GPA
The displacement in liters of the user's car engine
Part 1. Code
import java.io.*;
import java.util.*;
import java.util.Scanner;
public class InformationStationFinal{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
String s1 = "yes";
String s2 = "no";
System.out.print("Are you left handed? Enter yes or no:");
String leftHand = input.next();
System.out.println("true");
System.out.print("Is your father at least 5ft 10 inches? Enter yes or no:");
String tall = input.next();
System.out.println("true ");
System.out.print("Enter your age in months: ");
int age = input.nextInt();
System.out.println(" ");
System.out.print("Enter the age of a sibling or friend in months: ");
int ageTwo = input.nextInt();
System.out.println(" ");
System.out.print("Enter your GPA as decimal, such as 3.58: ");
double gpa = input.nextDouble();
System.out.println(" ");
System.out.print("Enter displacement in liters of your cars engine:");
int liter = input.nextInt();
System.out.println(" ");
System.out.println("Are you left handed? " + " " + leftHand);
System.out.println("Is your father at least 5ft 10in? " + " " + tall);
System.out.println("Are you left handed or is your father at least 5ft 10?" + " " +
((leftHand.equals(s1)) || (tall.equals(s1))));
System.out.println("Are you left handed And is your father at least 5ft 10?" + " " +
((leftHand.equals(s1)) && (tall.equals(s1))));
System.out.println("Are your answers for left handed & father's height the same" + " " +
(leftHand.equals(tall)));
}
}
Part 2.
Prints out the following information, using either JOptionPane.showMessageDialog() or System.out.println() for the output:
Whether the user is left-handed
Whether the user's father was at least 5 ft 10 inches tall
Whether at least one of the values from a and b are true (true if either or both are true)
Whether a and b are both true (false if at least one is false)
Whether the truth values of a and b are the same (true if both a and b are true or if both a and b are false)
Whether the user is older than his/her sibling/friend (as far as we can tell from the ages in months)
Whether the user's age in months is within 12 months of the age of his/her sibling or friend. You may want to use Math.abs() for this.
Whether the user's GPA is at least equal to the displacement of his/her car engine. For this item, use an else statement to print out some appropriate message if the condition is false.
Could someone please help me complete the second part of this question? Thank you.
Sounds like you have a bunch of conditions to check. The nice thing about booleans, they lend themselves well to "if" statements . . .
Look into:
if(someCondition)
{
// Do Something
}
else
{
// Do Something Else
}
At this point, you could use a single String to gather the results for later printing in a JOptionPane.showMessageDialog(). I won't code it all for you, but here's an example:
String result = "";
if(leftHand.equalsIgnoreCase("yes")) {
result += "You are left handed.\n";
} else {
// Other stuff
}
// ...
JOptionPane.showMessageDialog(null, result);
EDIT: If you're not interested in using JOptionPane, then you can use a single System.out.println() to print the entire string out as well. You just have to remember, when you're adding your answers to the String, you need a newline character.
For those questions you will need some conditional statements, i.e.:
if(leftHand.equals("yes")){
System.out.println("User is left-handed");
} else {
System.out.println("User is right-handed");
}

Categories