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

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

Related

How to calculate sum from user input inside while loop

I got two classes, this one and other called DailyExpenses that's full of getters and setters + constructors etc..
My problem is that I want to get the sum value of all daily expenses user inputs inside the while loop and print the sum after the program is closed, and I don't know how to do it.
Here is my code:
import java.util.Scanner;
import java.util.ArrayList;
public class DailyExpensesMain {
public static void main(String[] args) {
ArrayList<DailyExpenses> expenses = new ArrayList<DailyExpenses>();
Scanner sc = new Scanner(System.in);
boolean isRunning = true;
System.out.println("Enter the date for which you want to record the expenses : ");
String date = sc.nextLine();
while(isRunning) {
System.out.println("Enter category: (quit to exit)");
String category = sc.nextLine();
if(category.equalsIgnoreCase("quit")) {
break;
}
System.out.println("Enter price: ");
double price = sc.nextDouble();
sc.nextLine();
System.out.println("Enter details: ");
String detail = sc.nextLine();
DailyExpenses newExpense = new DailyExpenses(date, category, price, detail);
expenses.add(newExpense);
}
sc.close();
for(DailyExpenses u: newExpense) {
System.out.println("Date: " + u.getDate() + " Category: " + u.getExpenseCategory() + " Price: " + u.getExpensePrice() +
" Detail: " + u.getExpenseDetail());
}
}
}
I still clueless on the situation

How to check for and use input from a different methood

I am making a game and a the end of the game I want it to call the user by the name that they put in,, this is the code I have.
private static final Scanner console = new Scanner(System.in);
public static void main(String[] args) {// follow the prompts.//
System.out.println("Hello user! what is your name? ");
String Name = console.nextLine();
System.out.println("Really? " + Name + " is too weird to be a real name.");
confirmation();
Mascot();
System.out.println("Thank you for playing the demo");
console.close();
}
public static void confirmation() {
System.out.print("is that REALLY your name? (type Y/N) ");
String yN = console.nextLine();
String a = yN;
if (a.toLowerCase().contains("y")) {
System.out.println("I still dont belive you, so you will have to answer 3 riddles before you can continue to the game");
} else {
calledIt();
}
}
public static void calledIt() {
System.out.println("I knew it!");
System.out.print("whats your real name? ");
String realName = console.nextLine();
System.out.println(
"" + realName + " sounds like a real name, but you lied the first time so you will need to answer riddles 3 to continue to the game");
}
public static boolean Mascot() {
System.out.println("what Is our school mascot?");
String b = console.nextLine();
if (b.toLowerCase().contains("tiger")) {
System.out.println("Good, next riddle.");
System.out.println("What runs around the whole yard without moving?");
String c = console.nextLine();
if (c.toLowerCase().contains("fence")) {
System.out.println("Good, next riddle.");
System.out.println("What goes on four feet in the morning, two feet at noon, and three feet in the evening? ");
String d = console.nextLine();
if (d.toLowerCase().contains("man")) {
System.out.println("You, have sucsefully passed the third riddle");
return true;
} else {
System.out.println("You have failed");
return false;
}
} else {
System.out.println("You have failed");
return false;
}
} else {
System.out.println("You have failed");
return false;
}
}
I want for it to at the end print * user's name*, you have successfully passed the third riddle.
but it needs to be able to weather the first name was kept, or if this sequence was used.
public static void calledIt() {
System.out.println("I knew it!");
System.out.print("whats your real name? ");
String realName = console.nextLine();
System.out.println(
"" + realName + " sounds like a real name, but you lied the first time so you will need to answer riddles 3 to continue to the game");
}
and if it has been activated it needs to use the new name.
Change return type of calledIt() to String and return realName from this method
Change return type of confirmation() to String. Initialize a String (String name = null). In the else part, assign the value returned from calledIt() to this string (String name = calledIt()). Return name.
In main, if the value returned from confirmation() is not null, update Name with this new value.
Pass the Name as input to Mascot method. For this, you have to update the Mascot method to accept a String as input.
You can pass the variable into confirmation() and calledIt() like this
public static void main(String[] args) {// follow the prompts.//
System.out.println("Hello user! what is your name? ");
String Name = console.nextLine();
System.out.println("Really? " + Name + " is too weird to be a real name.");
confirmation(Name);
Mascot();
System.out.println("Thank you for playing the demo");
console.close();
}
public static void confirmation(String name) {
System.out.print("is that REALLY your name? (type Y/N) ");
String yN = console.nextLine();
String a = yN;
if (a.toLowerCase().contains("y")) {
System.out.println("I still dont belive you, so you will have to answer 3 riddles before you can continue to the game");
} else {
calledIt(name);
}
}
public static void calledIt(String realName){
System.out.println("I knew it!");
System.out.print("whats your real name? ");
System.out.println(
"" + realName + " sounds like a real name, but you lied the first time so you will need to answer riddles 3 to continue to the game");
}
You could do the following change:
public static void main(String[] args) { // follow the prompts.//
System.out.println("Hello user! What is your name? ");
String name = console.nextLine();
System.out.println("Really? " + name + " is too weird to be a real name.");
System.out.print("Is that REALLY your name? (type Y/N) ");
String yN = console.nextLine();
String a = yN;
if (a.toLowerCase().contains("y")) {
System.out.println("I still don't believe you, so you will have to answer 3 riddles before you can continue to the game");
} else {
System.out.println("I knew it!");
System.out.print("Whats your real name? ");
name = console.nextLine();
System.out.println(
"" + name + " sounds like a real one, but you lied the first time so you will need to answer riddles 3 to continue to the game");
}
mascot(name);
System.out.println("Thank you for playing the demo");
console.close();
}
public static boolean mascot(String name) {
System.out.println("what Is our school mascot?");
String b = console.nextLine();
if (b.toLowerCase().contains("tiger")) {
System.out.println("Good, next riddle.");
System.out.println("What runs around the whole yard without moving?");
String c = console.nextLine();
if (c.toLowerCase().contains("fence")) {
System.out.println("Good, next riddle.");
System.out.println("What goes on four feet in the morning, two feet at noon, and three feet in the evening? ");
String d = console.nextLine();
if (d.toLowerCase().contains("man")) {
System.out.println(name + ", you have successfully passed the third riddle");
return true;
} else {
System.out.println("You have failed");
return false;
}
} else {
System.out.println("You have failed");
return false;
}
} else {
System.out.println("You have failed");
return false;
}
}

A bit confused on my if loop not running?

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.

Strings - setting it globally

Okay so i created this program which is unfinished that allows you to insert a students name and test score into a string. But my probably is, im trying to use if statements so that the user is able to type in a number and choose what they wish to do.
Im trying to have it so after the user has inserted the name and test score, they can choose to have the name and test score printed out, or they can quit or insert another name but i cant because the string is not set globally.
does anyone know how to do this? Thank You,
package week14;
import java.util.Scanner;
public class Task4 {
private static Scanner input;
private static Scanner input2;
public static void main (String [] args){
input2 = new Scanner (System.in);
System.out.println("Student Mark Program");
System.out.println("\nHere are your options:");
System.out.println("\n1. Insert Student name and mark");
System.out.println("2. Quit");
int choice = input2.nextInt();
System.out.println();
if (choice == 1){
opt1();
}
else if (choice == 2){
quit();
}
}
public static void opt1(){
input = new Scanner(System.in);
String firstname;
String surname;
int score1;
System.out.print("Enter the students first name: ");
firstname = input.next();
System.out.print("Enter the students surname: ");
surname = input.next();
String full_name;
full_name = firstname + " " + surname;
System.out.println("Please enter students score: ");
score1 = input.nextInt();
System.out.println("Name : " + full_name);
System.out.println("Score: " + score1);
System.out.println();
System.out.println("\nHere are your options:");
System.out.println("\n1. Insert Another Student name");
System.out.println("2. Get student name");
System.out.println("3. Get student name and mark");
System.out.println("4. Quit");
int choice = input.nextInt();
System.out.println();
if (choice == 1){
opt6();
}
else if (choice == 2){
opt2();
}
else if (choice == 3){
opt3();
}
System.out.println();
input.close();
}
public static void opt2(){
System.out.println("Name : " + full_name);
}
public static void opt3(){
}
public static void opt4(){
}
public static void opt5 (){
}
public static void opt6 (){
}
public static void quit(){
System.out.println("You have quit the program");
System.exit(0);
}
}
Put this static String full_name; under where you declare private static Scanner input2; in your class. Not necessarily good programming practice to use global variables, but for your purposes it will likely get the job done.
Well, I would initialize a new global variable set your full_name to and return it as an accessor method.
public static String getName()
{
return (nameOfString);
}
Also, I see that you want to make an other command to change your name and you could do that with a settor method.
public static void setName(String newName)
{
originalString = newName;
}

I need to restructure this class without the use of instance variables

So I'm doing a TUI and this was my first iteration.
package bulb.classes;
import java.util.Scanner;
import java.util.ArrayList;
public class RoomTUI {
private ArrayList<Room> rooms;
Scanner scan = new Scanner (System.in);
private int userNumber;
private String userAnswer;
public void run() {
rooms = new ArrayList<Room>();
introduction();
userNumber = 0;
options();
while(userNumber < 5) {
if(userNumber == 1) {
newRoom();
}
if(userNumber == 2) {
addBulbToRoom();
}
if(userNumber == 3) {
clickAllBulbsInRoom();
}
if(userNumber == 4) {
printDescriptionOfBulbs();
}
}
System.out.println("Goodbye");
}
public int getUserInt(String aString) {
System.out.println(aString);
userAnswer = scan.nextLine();
userNumber = Integer.parseInt(userAnswer);
return userNumber;
}
public void displayRooms() {
System.out.println("Possible rooms to choose from.");
String tempString = "";
int roomIndex = 0;
for (int i = 0; i < rooms.size(); i++) {
tempString = tempString + "Room " + roomIndex++ + ": " + rooms.get(i).getDescription() + "\n";
}
System.out.println(tempString);
}
public void introduction() {
System.out.println("Welcome! With this program you can make rooms and design and place the light bulbs for each room you create.");
}
public void options() {
System.out.println("1 : Create a new Room");
System.out.println("2 : Add a bulb to an existing room");
System.out.println("3 : Click all of the bulbs in a particular room");
System.out.println("4 : Display a description of all bulbs in a particular room");
System.out.println("5 : Quit");
getUserInt("What would you like to do?");
}
public void newRoom() {
System.out.println("Please enter a name for your room");
String name = scan.nextLine();
Room aRoom = new Room(name);
rooms.add(aRoom);
System.out.println("You have added the " + name + ".");
options();
}
public void addBulbToRoom() {
displayRooms();
System.out.println("Which room do you want the bulb in?");
String choice = scan.nextLine();
int choiceNumber = Integer.parseInt(choice);
System.out.println("Please enter the blub's color.");
String color = scan.nextLine();
System.out.println("Please enter the blub's increment amount.");
String incrementS = scan.nextLine();
int incrementI = Integer.parseInt(incrementS);
ThreeWayBulb aBulb = new ThreeWayBulb(color, incrementI);
rooms.get(choiceNumber).addBulb(aBulb);
System.out.println("A " + color + " bulb with and increment of " + incrementI + " was added.");
options();
}
public void clickAllBulbsInRoom() {
displayRooms();
System.out.println("Which room do you want the bulbs clicked?");
String choice = scan.nextLine();
int choiceNumber = Integer.parseInt(choice);
rooms.get(choiceNumber).clickAllBulbs();
System.out.println("The bulbs in " + rooms.get(choiceNumber).getDescription() + " have been clicked.");
options();
}
public void printDescriptionOfBulbs() {
displayRooms();
System.out.println("Please enter a room number.");
String choice = scan.nextLine();
int choiceNumber = Integer.parseInt(choice);
System.out.println(rooms.get(choiceNumber).getDescription() + " with " + rooms.get(choiceNumber).returnSize() + " bulbs: " + "\n" + rooms.get(choiceNumber).toString());
options();
}
}
My instructor wants me to do this without instance variables He said if a method needs the ArrayList that I should make it a parameter and have no instance variables in my TUI. I can't for the life of me figure out how to do that. Also, making it static work fly either. Thanks for any help you can give.
He wants you to declare the ArrayList from a central location (such as the main thread) and then pass it as an argument to the functions that use it. This way if you were to take methods and put them in different classes then it wouldn't break because they're not dependent on this class.
For example if we take your newRoom class:
public void newRoom(List<Room> roomList) {
System.out.println("Please enter a name for your room");
String name = scan.nextLine();
Room aRoom = new Room(name);
roomList.add(aRoom);
System.out.println("You have added the " + name + ".");
options();
}
EDIT: The easiest way to achieve this is to probably move the declaration of rooms to within your run method. Now for each location in the code that reports "unknown variable rooms" you can modify the function to take an ArrayList as a parameter.
Well, eliminating userNumber and userAnswer as members is trivial; their usage is very localized.
For the list, just pass it around after creating it in your main loop.
The scanner is used multiple places; it could also be passed around, I suppose.

Categories

Resources