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");
}
Related
I'm creating a small project to improve my coding skills. So the problem I'm having is that I have an enroll method, which will allow the 'Student' to enroll into available courses. I put all the courses available in the enum class called 'Courses'.
The problem I am having is how do I get multiple inputs, and for every input if it meets one of the if statements it gets to added to an arraylist called 'enroll'. Otherwise if the user does not want to enroll the user has to type 0, to which I expect the next line to be read.
I think if you were to read my code you'd have a better idea in what I'm trying to do.
I have conducted research on how to get multiple inputs and split it, but that does not seem to work for me.
public int enrolled() {
System.out.println("The following courses available are:\n" + "1." + Courses.COMPUTERSCIENCE101 + "\n" + "2." + Courses.CHEMISTRY101 + "\n" + "3." + Courses.ENGLISH101 + "\n" + "4." + Courses.HISTORY101 + "\n" + "5." + Courses.MATHEMATICS101);
Scanner CS = new Scanner(System.in);
Scanner CI = new Scanner(System.in);
Scanner EL = new Scanner(System.in);
Scanner HT = new Scanner(System.in);
Scanner MM = new Scanner(System.in);
if(CS.nextInt() == 1) {
this.enroll.add(Courses.COMPUTERSCIENCE101);
} else if (CS.nextInt() == 0) {
System.out.println("Course added and now exiting...");
}
if(CI.nextInt() == 2) {
this.enroll.add(Courses.CHEMISTRY101);
} else if (CI.nextInt() == 0) {
System.out.println("Course added and now exiting...");
}
if(EL.nextInt() == 3) {
this.enroll.add(Courses.ENGLISH101);
} else if (EL.nextInt() == 0) {
System.out.println("Course added and now exiting...");
}
if(HT.nextInt() == 4) {
this.enroll.add(Courses.HISTORY101);
} else if (HT.nextInt() == 0) {
System.out.println("Course added and now exiting...");
}
if(MM.nextInt() == 5) {
this.enroll.add(Courses.MATHEMATICS101);
} else if (MM.nextInt() == 0) {
System.out.println("Course added and now exiting...");
}
System.out.println(this.enroll.size());
return this.enroll.size();
}
So it is expected that if the user wants to pick course 1,3,5. Those courses will be added to an arraylist. and should return the length as 3. However, it's allowing the user to input more than 5 inputs, if I was to include 0 as an input (user needs to only 5 inputs, e.g (1,0,3,4,5) or something similar where the returned size of the arraylist would be 4).
Maybe you should try a different approach. You could ask the user to type the code of the courses they want to join like this:
Scanner in = new Scanner(System.in);
System.out.println("The following courses are available:");
System.out.println("Computer Science 101, Course code: CS101");
System.out.println("More courses...");
System.out.println("Type Q to end.");
String input = in.next();
while (!input.equals("Q")){
switch (input){
case "CS101":
//add course
break;
}
input = in.next();
}
You need to learn of Object Oriented Programming. This video Object-oriented Programming in 7 minutes gives an overview of some major concepts. Of course you need to learn them in depth. Anyways this is how I solved your problem. It doesn't exactly follow all you requirements because of lack of information i.e enroll method and Class Courses. This is just meant to show you what can you do.
// Create ArrayList
ArrayList<String> selectedCourses = new ArrayList<String>();
// Displays all courses available
System.out.println("The following courses available are:\n" + "1. COMPUTERSCIENCE101\n" + "2. CHEMISTRY101\n"
+ "3. ENGLISH101\n" + "4. HISTORY101\n" + "5. MATHEMATICS101\n");
// Creating scanner object
Scanner scanner = new Scanner(System.in);
// Prompting user. This is helpful otherwise the user would just keep staring at
// blank screen not knowing that program is asking for input.
System.out.print("Please enter how many courses you want to select: ");
int noOfCourses = scanner.nextInt();
scanner.nextLine();
// Looping the number of time user wants to select courses
for (int i = 0; i < noOfCourses; i++) {
// Prompting user
System.out.print("Please enter the course you want to select: ");
String course = scanner.nextLine(); // Instead of creating a new Scanner I am reusing the older one
selectedCourses.add(course); // Adding courses in arraylist
}
// Printing arraylist
System.out.println("\nCourses selected: " + selectedCourses.toString());
Output:
The following courses available are:
1. COMPUTERSCIENCE101
2. CHEMISTRY101
3. ENGLISH101
4. HISTORY101
5. MATHEMATICS101
Please enter how many courses you want to select: 3
Please enter the course you want to select: COMPUTERSCIENCE101
Please enter the course you want to select: CHEMISTRY101
Please enter the course you want to select: HISTORY101
Courses selected: [COMPUTERSCIENCE101, CHEMISTRY101, HISTORY101]
This question already has answers here:
Variable might not have been initialized error
(12 answers)
Closed 5 years ago.
Im just a beginner and anything would be helpful. So basically this program asks a question and depending on input, affects the price of tshirts. Also it asks how many tshirts wanted to be purchased also affecting the price. It keeps on running until "exit" is typed.
The problem I have is that I want the output to have the total sales and other info that was accumulated from the if/else if statements before. But when I compile it says local variable may not have been initialized. Any help would be much appreciated
import java.util.Scanner;
class ScannerTest{
public static void main (String args[]){
int b, c;
String endProgram = "exit";
String userInput;
java.util.Scanner input = new java.util.Scanner(System.in);
do{
System.out.println("\n Welcome to the SAC t-shirt sales software");
System.out.println("\n Does the student have an activity fee? Yes/No/Exit");
userInput = input.nextLine();
if (userInput.equalsIgnoreCase("yes")){
System.out.println("How many Tshirts do you want to buy?");
b = input.nextInt();
input.nextLine();
System.out.println("Cost:" + b*5 + " dollars");
}
else if(userInput.equalsIgnoreCase("no")){
System.out.println ("How many Tshirts do you want to buy?");
c = input.nextInt();
input.nextLine();
System.out.println("Cost:" + c*6 + " dollars");
}
}while (!userInput.equalsIgnoreCase(endProgram));
System.out.println ("Activity Card Sales:" + b + "Non-activity Card Sales:" + c + "Total Money Collected" + ((b*5)+(c*6)));
input.close();
}
}
just set in the begging b and c to 0 and you will have no problems.
For data structures and algorithms in java class I've been assigned to create a program that takes user input for an item's name and price and then averages the price. I have successfully done that, however, I am having a great deal of trouble on a certain specification for the program: a sentinel number (-1) that terminates the project. Here is my code, I will explain what the issue is after.
while(true){
System.out.print("Enter item " + (count + 1) + " name: "); // enter name
names[count] = in.next(); // next string becomes count index
System.out.print("Enter item " + (count + 1) + " price: "); // enter price
prices[count] = in.nextDouble(); // stores price entered as array index
if(prices[count] == -1) break; // if next price == -1 // the code i want to change.
if(names[count].equalsIgnoreCase("peas")) flag = true;
average += prices[count];
count++;
}
So, my issue is: I want to terminate the program when I enter -1 for the item name, not have to enter a "dummy" item name and then have to enter the sentinel number (-1).
Sorry for the long explanation, just trying to be thorough.
Thanks for taking the time to read this and help a programmer hopeful out.
You need to use a String for your comparison (but "-1" will do). Also, do it immediately after you get the input. Something like,
names[count] = in.next();
if (names[count].equals("-1")) {
break;
} // ...
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.
I am trying to make a quiz for an assignment in my GCSE computing course, and I need some help. This code compiles but whenever I run the code and input an answer, the answer spills over onto the answer for another question. For example, for the first question if I type the answer as "Mr Someone" when I am running the program, "Mr" becomes the answer to the first question and "Someone" becomes the answer to the second.
I'm not sure if this has anything to do with the sub-strings or what, but please help! :). If you're wondering why the value for the iScore variable is never used, it's because this is not the full code, just the first three questions, the score is printed at the end. There is not difference in the "template" for each question, just a different question and answer.
public static void main(String[] args) throws InterruptedException
{
//creates the Scanners needed
Scanner szAnswer = new Scanner(System.in);
Scanner szPlayAgain = new Scanner(System.in);
//declares the variables for the answers
String szFirstAnswer;
String szSecondAnswer;
String szThirdAnswer;
//declares a variable for the score
int iScore = 0;
//declares a variable for whether or not the user wants to keep playing
String szRestart;
//creates a do while loop, keeps going as long as the user wants to play
do {
//tells the user that only one word answers are needed
System.out.println("Only one word answers are needed!");
//first question
//Asks the question and collects the input
System.out.println("Question 1:");
System.out.print("Which Ancient Greek god was said to be the god of the sky? ");
szFirstAnswer = szAnswer.next();
//converts the answer to a format with the first letter upper case and the rest lower case
szFirstAnswer = szFirstAnswer.substring(0,1).toUpperCase() + szFirstAnswer.substring(1);
szFirstAnswer = szFirstAnswer.substring(0,1) + szFirstAnswer.substring(1).toLowerCase();
//prints out the converted response
System.out.println("You said: " + szFirstAnswer);
//if the answer was Zeus, the print out correct and add 1 to the score
if (szFirstAnswer.equals("Zeus")) {
System.out.println("Correct!");
iScore++;
}
//if the answer was not Zeus, print out a message with the correct answer
else {
System.out.println("Wrong! The correct answer was: Zeus");
}
//creates a line break
System.out.println();
//second question
//Asks the question and collects the input
System.out.println("Question 2:");
System.out.print("Which team has won the most FA Cups since the competition started? ");
szSecondAnswer = szAnswer.next();
//converts the answer to a format with the first letter upper case and the rest lower case
szSecondAnswer = szSecondAnswer.substring(0,1).toUpperCase() + szSecondAnswer.substring(1);
szSecondAnswer = szSecondAnswer.substring(0,1) + szSecondAnswer.substring(1).toLowerCase();
//prints out the converted response
System.out.println("You said: " + szSecondAnswer);
//if the answer was Arsenal, the print out correct and add 1 to the score
if (szSecondAnswer.equals("Arsenal")) {
System.out.println("Correct!");
iScore++;
}//end if
//if the answer was not Arsenal, print out a message with the correct answer
else {
System.out.println("Wrong! The correct answer was: Arsenal");
}//end else
//creates a line break
System.out.println();
//third question
//Asks the question and collects the input
System.out.println("Question 3:");
System.out.print("What is the currency of Japan? ");
szThirdAnswer = szAnswer.next();
//converts the answer to a format with the first letter upper case and the rest lower case
szThirdAnswer = szThirdAnswer.substring(0,1).toUpperCase() + szThirdAnswer.substring(1);
szThirdAnswer = szThirdAnswer.substring(0,1) + szThirdAnswer.substring(1).toLowerCase();
//prints out the converted response
System.out.println("You said: " + szThirdAnswer);
//if the answer was Yen, the print out correct and add 1 to the score
if (szThirdAnswer.equals("Yen")) {
System.out.println("Correct!");
iScore++;
}//end if
//if the answer was not Yen, print out a message with the correct answer
else {
System.out.println("Wrong! The correct answer was: Yen");
}//end else
//creates a line break
System.out.println();
}while (szRestart.equals("Y"));//end while
//prints a thank you message to the screen
System.out.println("Thanks for Playing!");
//closes the scanners
szAnswer.close();
szPlayAgain.close();
}//end main
Where you have szAnswer.next(); you should actually have szAnswer.nextLine(); I believe.
.next() gets the next word that is input, which is why it stops at the first space, where as .nextLine(); gets the whole line when you hit enter.