A bit confused on my if loop not running? - java

I'm pretty new to programming and new to this site, so bear with me if this explanation is clunky.
I'm teaching myself java programming, and currently I'm just writing up a general little code to practice the use of classes and methods. It's a simple code just asking for name and age and if one has a pet to just practice.
I have an if loop for when asked if the person has a pet, if they say yes, it should do one thing, no another, and for anything else it should say more or less 'hey, i didn't understand that', and move on.
However when I ask 'do you have a pet', it doesn't give me a chance to even input information before going right to the 'else' section of my loop, and I'm not sure why.
I'm very new to programming so I'm not sure what to do or try. I know I'm missing something silly, but i don't know what.
package practice;
import java.util.Scanner;
class Person {
String name;
int age;
void sayInfo() {
System.out.println("Hey, my name is " + name + " and I'm " + age + " years old!");
}
}
class Pet {
String name;
String type;
int age;
}
public class Methods {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
Person person1 = new Person();
String answer2;
do {
System.out.println("Please state your name:");
person1.name = input.nextLine();
System.out.println("Please state your age:");
person1.age = input.nextInt();
System.out.println("Do you have a pet?");
String answer = input.nextLine();
if (answer.equals("yes") || answer.equals("Yes")) {
Pet pet1 = new Pet();
System.out.println("What kind of pet?");
pet1.type = input.nextLine();
System.out.println("What is their name?");
pet1.name = input.nextLine();
System.out.println("How old are they?");
pet1.age = input.nextInt();
System.out.println(
"okay, so your name is " + person1.name + ", you're " + person1.age + "years old, and");
System.out.println(
"You have a " + pet1.type + " named " + pet1.name + " who is " + pet1.age + "years old.");
}
else if (answer.equals("no") || answer.equals("No")) {
System.out.println("okay, so your name is " + person1.name + ", you're " + person1.age
+ "years old, and you have no pet.");
}
else {
System.out.println("Sorry, I didn't understand your input there.");
}
System.out.println("Is your information correct?");
answer2 = input.nextLine();
} while (answer2.equals("no") || answer2.equals("No"));
System.out.println("Thank you for your information and time.");
}
}
When I run the program, it'll ask for name and age just fine, but when it gets to 'do you have a pet', it just doesn't let me input and goes right to the else part of the loop, "Sorry, I didn't understand your input there", but the rest of the program, asking if the information is correct and rerunning if not seems to work fine, it's just that one part that has me stumped.

It's because nextInt() only returns the int, but does not advance the scanner to the next line, so when you call nextLine() afterwards, it returns the empty string following the number, but does not return the answer to the questions (yes/no).
Try this:
System.out.println("Please state your name:");
person1.name = input.nextLine();
System.out.println("Please state your age:");
person1.age = input.nextInt();
input.nextLine(); // Advance to the next line
System.out.println("Do you have a pet?");
String answer = input.nextLine();
or use input.next() instead of .nextLine() when reading the lines.

Related

Else if not working correctly when scanning file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
import java.io.FileReader;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class Coursework2 {
public static void main(String[] args)
throws FileNotFoundException { {
Scanner reader = new Scanner(new FileReader("seats.txt"));
Scanner scan = new Scanner (System.in);
double defaultdiscount = 17.5, discount = 16.97;
boolean random = true;
while (random) {
System.out.println("Please enter your Surname:");
String name = scan.nextLine();
System.out.println("Good morning, Manager " + name + " Would you like to apply a specific discount rate?");
String decision = scan.nextLine();
if (decision.equalsIgnoreCase("yes") || decision.equalsIgnoreCase("y")) {
System.out.println("That's great, Mananger " + name + ".");
System.out.println("How much discount would you like? (1-100)");
break;
} else if (decision.equalsIgnoreCase("no") || decision.equalsIgnoreCase("n")) {
System.out.println("Alright, " + name + " Here's all the seats without discounts:");
//break;
}
System.out.println("Invalid Input, please try again. Restarting.");
}
discount = scan.nextDouble();
defaultdiscount = discount;
while (reader.hasNext()) {
String table = reader.next();
double price = reader.nextDouble();
int bookings = reader.nextInt();
double newdiscount = (((price/100.00*discount)*bookings));
double newincome = (price*bookings-(((price/100.00*discount)*bookings)));
System.out.printf("Seat type: %s, Price: £%.2f, Bookings: %d %n",table, price, bookings );
System.out.printf("Discount: £%.2f, Income: £%.2f %n", newdiscount, newincome);
String decision;
do {
System.out.printf("Seat type: %s, Price: £%.2f, Bookings: %d %n",table, price, bookings );
//decision = scan.nextLine();
decision = scan.next();
}
while (decision.equalsIgnoreCase("No"));
System.out.printf("Seat type: %s, Price: £%.2f, Bookings: %d %n",table, price, bookings );
}
reader.close();
scan.close();
}
}
}
I understand that the code runs sequentially, but when it comes to trying to run the read files through the else if (No), it can't go above the while reader or inside the else if or it won't see the info from the text file, and when outside, it can't see the variables. I'm just a bit confused. It feels like something might be in the wrong place and I can't wrap my head around it.
I've given this a go, using the correct comparisons, and declaring the string inside of the while. But I'm still getting some errors. I'm thinking maybe setting the string to "null" isn't the correct way of resetting, since I've already declared it has a scan.nextLine previously?
Try doing the if statement like this
while(random){
if (decision.equalsIgnoreCase("yes") || decision.equalsIgnoreCase("y")) {
System.out.println("That's great, Mananger " + name + ".");
System.out.println("How much discount would you like? (1-100)");
random = false;
}
else if (decision.equalsIgnoreCase("no") || decision.equalsIgnoreCase("n")) {
System.out.println("Alright, " + name + " Here's all the seats without discounts:");
random = false;
}
else
System.out.println("Invalid Input, please try again. Restarting.");
}
You will not loop it if you never change "random" boolean to false. Also, try not using break in this case.
Also, try creating the variable "name" and "decision" outside the loop, as good practice. You should also rename "random" to something like "isBadAnswer"

My while loop in java doesn't work and only completes it one time

It will only go through one time so it will end with "Would you like to make another request?(y/n)"
and when I input "y" it stops there and won't do the loop.
package Chaterp5PPReynaGuerra;
import java.util.*;
public class MeetingRequest
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
final int CAPACITY=30;
String name;
int people;
int morePeople;
String answer="y";
int fewerPeople;
System.out.println("--------Meeting Request System"+
"--------");
System.out.println("\nWelcome to the Meeting Request System."+
" May I know your name?");
name=scan.nextLine();
while(answer.equalsIgnoreCase("y"))
{
System.out.println("Hello, "+name+", how many people"+
" will be attending the meeting?");
people=scan.nextInt();
morePeople = CAPACITY - people;
if(people < CAPACITY)
System.out.println("You can invite "+morePeople+
" more people to the meeting.");
else if(people > CAPACITY) {
fewerPeople= people - CAPACITY;
System.out.println("Sorry, the room is not "+
"big enough to seat that many people. You have to "+
"exclude "+fewerPeople+" from the meeting.");
}
System.out.println();
System.out.println("Would you like to make another"+
" request?(y /n)");
// gets rid of \n in the input stream
scan.next();
answer=scan.nextLine();
}
}
}
Replace
people=scan.nextInt();
with
people = Integer.parseInt(scan.nextLine());
Check Scanner is skipping nextLine() after using next() or nextFoo()? to learn more about it.
Given below is the corrected program:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
final int CAPACITY = 30;
String name;
int people = 0;
int morePeople;
String answer = "y";
int fewerPeople;
boolean valid;
System.out.println("--------Meeting Request System" + "--------");
System.out.println("\nWelcome to the Meeting Request System." + " May I know your name?");
name = scan.nextLine();
do {
do {
valid = true;
System.out.println("Hello, " + name + ", how many people" + " will be attending the meeting?");
try {
people = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
System.out.println("Invalid entry. Pleaase try again.");
valid = false;
}
} while (!valid);
morePeople = CAPACITY - people;
if (people < CAPACITY)
System.out.println("You can invite " + morePeople + " more people to the meeting.");
else if (people > CAPACITY) {
fewerPeople = people - CAPACITY;
System.out.println("Sorry, the room is not " + "big enough to seat that many people. You have to "
+ "exclude " + fewerPeople + " from the meeting.");
}
System.out.println();
System.out.println("Would you like to make another" + " request?(y /n)");
answer = scan.nextLine();
} while (answer.equalsIgnoreCase("y"));
}
}
A sample run:
--------Meeting Request System--------
Welcome to the Meeting Request System. May I know your name?
abc
Hello, abc, how many people will be attending the meeting?
x
Invalid entry. Pleaase try again.
Hello, abc, how many people will be attending the meeting?
10.4
Invalid entry. Pleaase try again.
Hello, abc, how many people will be attending the meeting?
4
You can invite 26 more people to the meeting.
Would you like to make another request?(y /n)
y
Hello, abc, how many people will be attending the meeting?
5
You can invite 25 more people to the meeting.
Would you like to make another request?(y /n)
n
Some other important points:
As you can see, a do...while loop is more appropriate instead of while loop in this case.
You should always check for the NumberFormatException whenever you parse a text (e.g. Scanner::nextLine()) to integer.
Using next() will only return what comes before the delimiter (defaults to whitespace). nextLine() automatically moves the scanner down after returning the current line.
To get rid of the \n use scan.nextLine
// gets rid of \n in the input stream
scan.nextLine();
answer=scan.nextLine();
Hope this help.

Java 'if' and 'if else' statements not printing out

I am new to Java and have recently started coding within the last week. I have tried to build some basic things and did the following:
import java.util.Scanner;
public class App {
public static void main(String[] args){
// creating scanner object
Scanner userSex = new Scanner(System.in);
System.out.println("Enter your sex (male or female): ");
String sex = userSex.nextLine();
System.out.println("Thank you, you entered " + sex );
// new scanner
Scanner userAge = new Scanner (System.in);
System.out.println("Are you a child or adult: ");
String age = userAge.nextLine();
System.out.println("You are a " + sex + " " + age);
if (userAge.equals("child")) {
System.out.println("children");
} else if (userAge.equals("adult")) {
System.out.println("adults");
}
}
}
Unfortunately however, only the top of the code runs. The below code doesn't run and doesn't print anything out even when I enter "child" or "adult".
if (userAge.equals("child")) {
System.out.println("children");
} else if (userAge.equals("adult")) {
System.out.println("adults");
}
instead of
if(userAge.equals("child")) {
System.out.println("children");
}
else if(userAge.equals("adult")) {
System.out.println("adults");
}
do this
if(age.equals("child")) {
System.out.println("children");
}
else if(age.equals("adult")) {
System.out.println("adults");
}
The one thing that was already mentioned is that you only need one scanner object. It's unnecessary to create one for each string entered. The main problem is that you are testing if userAge equals "child" or "adult", but userAge is the scanner object. I think you meant to write age.equals("child"), as age is the actual String entered.
The following works:
import java.util.Scanner;
public class App {
public static void main(String[] args){
//creating scanner object
Scanner in = new Scanner(System.in);
System.out.println("Enter your sex (male or female): ");
String sex = in.next();
System.out.println("Thank you, you entered " + sex );
//new scanner
System.out.println("Are you a child or adult: ");
String age = in.next();
System.out.println("You are a " + sex + " " + age);
if(age.equals("child")) {
System.out.println("children");
}
else if(age.equals("adult")) {
System.out.println("adults");
}
}
}
Rather than creating two separate scanners you just use one and call the next()method. I also change the condition from if(userAge... to if(age...
There is no need to create two scanner object .Just create one scanner object.
You can also use BufferedReader instead of Scanner.In your code you use userAge.equals("child") .but this is not right since you store the value returned by scanner in age , use age to compare in if-else codition like age.equals("child")
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your sex (male or female): ");
String sex = scanner.nextLine();
System.out.println("Thank you, you entered " + sex );
System.out.println("Are you a child or adult: ");
String age = scanner.nextLine();
System.out.println("You are a " + sex + " " + age);
if (age.equals("child")) {
System.out.println("children");
} else if (age.equals("adult")) {
System.out.println("adults");
}
Reference Link:https://docs.oracle.com/javase/tutorial/essential/io/scanning.html

strange outputs by programs, too stupid to solve :c

so I have exercise from a college to finish and I believe I am close to it but yet so far. I am not asking for a specific answer, I would love to know how to "overwrite a variable?" (not sure if thats a right name for that kind of action).
Here is the question : http://pastebin.com/riDYS39D
The problem which I have is that, I don't know exactly how to overwrite data in variable which was created in if statement.
and the code, any help is always welcome
import java.util.Scanner;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double grossPaid, allowance1, allowance2, totalTaxPaid, netPay, grossAfterAllowance;
double taxSaved;
final double GROSSRATIO;
String idNumber, name, address, strln;
char maritalStatus;
allowance1 = 25000;
allowance2 = 20000;
GROSSRATIO = 500000;
taxSaved = 0.00;
/* trash
grossAfterAllowance = grossPaid - allowanceGiven;
totalTaxPaid = grossAfterAllowance - netPay;
*/
System.out.println("Enter your employee identification number: ");
idNumber = input.nextLine();
System.out.println("Enter your name: ");
name = input.nextLine();
System.out.println("Enter your address: ");
address = input.nextLine();
System.out.println("Enter your marital status: ");
strln = input.next();
maritalStatus = strln.charAt(0);
if (maritalStatus == 'S')
taxSaved = 0.20;
if (maritalStatus == 'M')
taxSaved = 0.23;
System.out.println("Enter your gross payment: ");
grossPaid = input.nextDouble();
if (grossPaid < GROSSRATIO)
netPay = (grossPaid - allowance1) * taxSaved;
if (grossPaid >= GROSSRATIO)
netPay = (grossPaid - allowance2) * taxSaved;
System.out.println(maritalStatus);
netPay = (grossPaid * maritalStatus);
System.out.println("Name: " + name);
System.out.println("ID: " + idNumber);
System.out.println("Address: " + address);
System.out.println("Marital Status: " + strln);
System.out.println("Gross Payment: " + grossPaid);
System.out.println("Net pay: " + netPay);
}
}
Considering your first input variable idNumber, this is how you overwrite a variable:
String idNumber = "";
System.out.println("Enter your employee identification number: ");
idNumber = input.nextLine();
System.out.println("ID Number: " + idNumber);
System.out.println("Enter your updated employee identification number: ");
idNumber = input.nextLine();
System.out.println("Updated ID Number: " + idNumber);
You said "any help is always welcome" so here is my analysis of your code.
It is general practice to declare your variables as close to their usage as possible, most often that means when first assigned, e.g.:
String address = input.nextLine();
Marital status is supposed to be lowercase 's' or 'm'. You should use nextLine() and validate it, e.g.
char maritalStatus;
do {
System.out.println("Enter your marital status (s/m):");
String line = input.nextLine();
maritalStatus = (line.length() == 1 ? line.charAt(0) : '?');
} while (maritalStatus != 's' && maritalStatus != 'm');
Your GROSSRATIO is supposed to be 50000, not 500000.
You are inconsistent about use of constants.
GROSSRATIO is uppercase and final. Perfect!
allowance1 and allowance2 are lowercase and not final.
0.20 and 0.23 are not named constants.
maritalStatus is a char, so this line compiles, but is definitely not what you want, and is the cause of your "strange outputs". Just remove the line:
netPay = (grossPaid * maritalStatus);
You are also printing maritalStatus by itself without label. Remove it.
You have two if statements for assigning netPay that are opposites, but compiler doesn't see that, so netPay is not definitely assigned. Just change second if statement to else.
totalTaxPaid and grossAfterAllowance are not used. Remove them.
The calculation of netPay actually calculates totalTax.
You are not printing all required output.

How to Declare and read values into integer variables?

I'm really new to java and i'm taking an introductory class to computer science. I need to know how to Prompt the user to user for two values, declare and define 2 variables to store the integers, and then be able to read the values in, and finally print the values out. But im pretty lost and i dont even know how to start i spent a whole day trying.. I really need some help/guidance. I need to do that for integers, decimal numbers and strings. Can someone help me?
this is what ive tried
import java.util.Scanner;
class VariableExample
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter an integer value");
int a = scan.nextInt();
int b = scan.nextInt();
System.out.println("Please enter an integer value");
double c = scan.nextDouble();
double d = scan.nextDouble();
System.out.println("Please enter an integer value");
string e = scan.next();
string f = scan.next();
System.out.println("Your integer is: " + intValue + ", your real number is: "
+ decimalValue + " and your string is: " + textValue);
}
i told you... im really new
You forgot to declare entry point i.e. main() method, String S should be capital and in System.out.println() you used wrong variables:
class VariableExample {
public static void main(String... args) { // Entry point..
Scanner scan = new Scanner(System.in);
System.out.println("Please enter an integer value");
int a = scan.nextInt();
int b = scan.nextInt();
System.out.println("Please enter an integer value");
double c = scan.nextDouble();
double d = scan.nextDouble();
System.out.println("Please enter an integer value");
String e = scan.next(); // String S should be capital..
String f = scan.next();
System.out.println("Your integer is: " + a + " " + b + ", your real number is: " + c + " " + d
+ " and your string is: " + e + " " + f); // here you used wrong variables
}
}
If still your problem not clear then let me know where you actually stuck.
There are a couple of issues.
(1) You need to declare an "entry" point for your program. In Java, you must create a method with the exact signature:
public static void main(String args) {
// Your code here
}
(2) The "string" type in Java is capitalized.
(3) You are referencing variables that have been neither declared nor defined:
System.out.println("Your integer is: " + intValue + ", your real number is: "
+ decimalValue + " and your string is: " + textValue);
In this case, you've never told Java what the value of intValue, etc is. It seems like you want to use the variables you have declared and defined like:
System.out.println("Your integer is: " + a + ", your real number is: "
+ c + " and your string is: " + e);
(4) It looks like you're reading in two sets of variables for each prompt. Based on your prompt "Please enter an...", you really are expecting one input.
Altogether, I think your code should look like this:
class VariableExample {
public static void main(String args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter an integer value: ");
int a = scan.nextInt();
System.out.println("Please enter a double value: ");
double c = scan.nextDouble();
System.out.println("Please enter a string: ");
String e = scan.next();
System.out.println("Your integer is: " + a + ", your real number is: "
+ c + " and your string is: " + e);
}
}

Categories

Resources