quite new to Java so trying to understand it can be difficult.
Anyways the problem, as part of a task I have to code a theatre tickets console application. I've almost finished I'm just trying to add the last part
As part of the task we have to ask the user if they want the tickets to be posted, if yes this incurs a charge which will be applied to the total charge. Currently I'm unsure of how to do this. At the moment I am currently working with If and else statements and.. Well you'll see below.
System.out.println ("Do you require the tickets to be posted?\n(£2.34 for post and packing for the entire order)\n(please enter 'Yes' on the next line if you require postage)");
String postinp = scanner.next();
if ("Yes".equals(postinp)){
System.out.println("Postage will be added to your cost" );
}
else
System.out.println("Postage will not be added to your cost");
Well I'm trying to code, if the user enters 'yes' then it adds on the postage charge to the total, but in this section of code I'm unsure how to do that.
Any help would be appreciated. Thanks!
Inside the if-statement all we need to do is add your £2.34 to the total sum being calculated by the program.
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
double total = 10.00;
System.out.println("Do you require the tickets to be posted?\n(£2.34 for post and packing for the entire order)\n(please enter 'Yes' on the next line if you require postage)");
if ("Yes".equalsIgnoreCase(input.next())) {
System.out.println("Postage will be added to your cost");
total = total + 2.34;
} else
System.out.println("Postage will not be added to your cost");
}
use scanner.nextLine() insead of scanner.next();
and use "Yes" instead of "Ye"
What I would do is change
if ("Ye".equals(postinp)) {
to
if ("yes".equals(postinp.toLowerCase())) {
That way it won't be case sensitive to what the user inputs, because otherwise they'd have to input Yes exactly.
You can add more code within the then-else blocks of an if statement
if ( "Yes".equals(postinp) )
{
this.cost += 2.34 ; // or whatever it is you need to do
System.out.println("Postage will be added to your cost" );
}
else
{
System.out.println("Postage will not be added to your cost");
}
You seem to need to resolve two things--evaluating the answer and then acting accordingly.
Try this:
String postinp = scanner.next();
if ("Yes".equalsIgnoreCase(postinp)) {
cost += postage;
System.out.println("Postage will be added to your cost" );
}
else {
System.out.println("Postage will not be added to your cost");
}
The if block checks if the result is some form of "yes" without regard to case. Then it assumes that cost and postage variables (floats) are available and initialized from somewhere. In the "yes" case, cost is augmented by postage.
Also, since you are just learning it isn't a big deal, but at some point you might want to consider your postage to be a value consumed from a constant or from a configuration file. Maybe the initial cost can be too.
Related
I'm trying to learn JAVA and I'm working on a simple pizza order assignment running purely in text/console format.
I've made the user chose a pizza, but they need the option to add extra ingredients.
My thought was to use a for loop to show a toppings menu and then ask for a numbered input matching the ingredient they want to add.
I want them to be able to select several ingredients, why I'm doing it in a loop.
My code as of now looks like this:
for (int i = 0; ingredientInput>0; i++ ){
toppingsMenu();
ingredientInput = ingredientScan.nextInt();
ingredientScan.nextLine();
System.out.println("Type your choice here:");
}
System.out.println(ingredientInput);
Everything works great, but I'd like to add a system.out.println() telling the user, what they've chosen as:
"You've added extra cheese - Would you like to add more?"
If so, I would like to expand that sentence: "You've added extra cheese & pepperoni - Would you like to add more?"
Could you help me by pointing me in a direction that might work? I'm not into any object related part of JAVA yet, purely text-based so far.
Thanks.
Solution provided by Adeel Ahmad
ArrayList<Integer> ingredients = new ArrayList<>();
for (int i = 0; ingredientInput>0; i++ ){
toppingsMenu();
ingredientInput = ingredientScan.nextInt();
ingredientScan.nextLine();
ingredients.add(ingredientInput);
System.out.println("Type your choice here:");
}
System.out.println(ingredientInput);
Looking back it's so interesting to see which problems I struggled to solve, as now, a few months later, this seems so basic. But thanks anyway to everyone who helped :D
First off, you need to be able to store all the added ingredients in data container (e.g ArrayListor HashMap). Whenever user inputs an ingredient, just added that in your ArrayList
ArrayList<Integer> ingredients = new ArrayList<>();
for (int i = 0; ingredientInput>0; i++ ){
toppingsMenu();
ingredientInput = ingredientScan.nextInt();
ingredientScan.nextLine();
ingredients.add(ingredientInput);
System.out.println("Type your choice here:");
}
System.out.println(ingredientInput);
Once you have collected all the user selected ingredients in your ArrayList, you can then iterate over it in a loop and construct your final message.
You could use something like this
String orderedSoFar = "";
boolean done = false;
do {
// read next ingredient from user
String currentIngredient = scanner.nextLine();
// if first extra ingredient
if(orderedSoFar.equals("")){
orderedSoFar += currentIngredient;
// if not first extra ingredient
} else {
orderedSoFar += " & " + currentIngredient;
}
System.out.println("Ingredients so far " + orderedSoFar);
System.out.println("Add more extra ingredients?");
// read choice to continue or not from user
done = Boolean.valueOf(scanner.nextLine());
}while(!done);
I'm currently working on a program for an O Level project where I have chosen to make a class management system. In my method class, I have various methods which control different functions of my program, such as one which collects the name of the students or one which displays a histogram of the student's grades. However, I have discovered a flaw in one of my methods. This is the method that lists the names of the students, one by one (which are saved in an array from a method that is executed before this method) and asks for the students marks. Here, the user is able to enter any number, which is inconvenient, considering that numerical grades normally range from 0-100. I have tried the following code but I have reached a predicament. The code does in fact stop the user from entering a mark over 100, but instead of allowing the user to re-enter a correct mark, it skips over to the next student, leaving the previous student without a mark. The following is said code:
//mark input
public void markin() {
System.out.println("=====================================");
System.out.println("Please enter the mark of the students");
System.out.println("=====================================");
for (int g = 0; g != marks.length; g++) {
System.out.println(names[g]);
marks[g] = Keyboard.readInt();
while(marks[g]<0||marks[g]>100){
System.out.println("Kindly enter a number that is less than 100");
break;
}
}
}
Help would be very much appreciated and thank you in advance :)
Apologies if my English is not very good.
You almost got it - you need to read in your while-loop instead of breaking without reading. Also a do-loop would be more appropriate for not having to set an initial invalid value.
//mark input
public void markin() {
System.out.println("=====================================");
System.out.println("Please enter the mark of the students");
System.out.println("=====================================");
for (int g = 0; g != marks.length; g++) {
System.out.println(names[g]);
do {
System.out.println("Kindly enter a number that is less than 100");
marks[g] = Keyboard.readInt();
} while(marks[g]<0||marks[g]>100);
}
}
Set marks[ g ] to a number that isn't allowed before the loop, like - 1 then check the keyboard input inside of the while loop,
(and set It there every time as long as the while loop isn't stopped,
marks[g] = Keyboard.readInt();
and don't break the loop, as the loop would end anyways when the input is valid
The valid answers has to get into the array sequentially.
Use this simple trick to reset index [g] to the previous value
then you will overwrite the marks[g] value until you get a valid one:
while(marks[g]<0||marks[g]>100){
System.out.println("Kindly enter a number that is less than 100");
g--; // Resetting index to previous value
break;
}
I am currently working on a project and I have been asked to create a puzzle type game based on a 2d array. I have created the methods which all work fine, but I dont quite know how to make it so that the user can call upon the methods via user input whilst the program is running.
I'd prefer not to upload my code as this is quite a big class and I don't want other class members to find this and copy my code.
Thanks :-)
Try a simple menu loop like this:
// scanner created outside the loop because it will be used every iteration
Scanner s = new Scanner(System.in);
while(true) {
System.out.print("Please choose an option: ");
// read some input and trim the trailing/ leading whitespaace
String input = s.nextLine().trim();
// check to see which move was called
if (input.equals("foo")) {
foo();
}
else if (input.equals("bar")) {
bar();
}
// break out of the menu loop
else if (input.equals("exit")) {
break;
}
// if none of the above options were called
// inform user of invalid input
else {
System.out.println("Invalid input");
}
}
// exit program
System.out.println("Goodbye!");
Just add in options as you need them
You can use GUI or console to give your command to your apllication for execution those methods.
offtop
this is quite a big class
I think you should divide one big class to some smaller classes(less them 100 lines).
The problem I seem to be having is that I am unsure on how to make the program recognize if the player is in one of the "MVP" positions (C,SS,CF) before moving forward with my program logic.
These three positions qualify for "MVP" status only if their OPS is above 800 for everyone else, it has to be 900 or above to be considered for "MVP".
Once again, I am having trouble with the "if" and "if else" statement.
Again, This IS school given problem and I don't want the answer. Only insight into what I am doing wrong. I want to learn this not have it done for me. Thank you in advance.
import java.util.Scanner;
public class baseBall {
public static void main(String[] args) {
/* A good part of a baseball player's offensive value is captured by the
statistic OPS - the sum of the player's on base percentage and slugging
percentage. An MVP candidate will typically have an OPS above 900,
however if they play a difficult defensive position (catcher, shortstop, or center field)
then they are an MVP candidate if their OPS is above 800. Write a program that will prompt the user for
a player's name, their on base percentage, slugging percentage, and defensive position and report whether the player is an MVP candidate*/
Scanner input = new Scanner(System.in);
System.out.println("Please enter players name: ");
String name = input.next();
System.out.println("Please enter On Base Percentage: ");
double Obp = input.nextDouble();
System.out.println("Please enter slugging Percentage: ");
double Slg = input.nextDouble();
System.out
.println("Please enter position (P,C,1B,2B,3B,SS,LF,CF,RF): ");
String ball = input.next();
String position;
double Ops = Obp + Slg;
if ( position.equalsIgnoreCase("ss")){
if (position.equalsIgnoreCase("cf")){
if (position.equalsIgnoreCase("c")){
System.out.println("MVP Candidate!");
else
System.out.println("NOT an MVP Candidate!);
}
}
}
}
}
Try doing it without nested IFs. Instead, try using Boolean operators like AND and OR.
As previously stated try using a paper first. Try drawing a decision tree to see what and where it might be going wrong.
Your code is checking if the player position is c AND ss AND cf. But the player will be only in one position, it can't be in all the three, so your code will always print "Not an MVP Candidate!".
To make it simple your code is checking if the position is c AND ss AND CF, instead you want to check if the position is c OR ss OR cf.
So you have to use the conditional operator OR -> ||:
if(position.equalsIgnoreCase("ss") || position.equalsIgnoreCase("cf") || position.equalsIgnoreCase("c") {
System.out.println("MVP Candidate!");
} else {
System.out.println("NOT an MVP Candidate!);
}
Your nested ifs will never be true. Think about this logically and on paper.
If position equals ss how can it equal cf and c at the same time? Always ask yourself: "does this make sense?" -- do this before committing code to screen and you'll be golden.
As a side recommendation, please get rid of those distracting // from your question text. They serve no purpose other than to annoy.
I'm having some problems with my program, i ask the user to enter the start population,daily growth in percent, and how many days they will multiply. Then calculate the end population for each day, while making sure they are constraints to the user entered data. I keep getting back the same results for each day and the constraints aren't doing their job either.
input=JOptionPane.showInputDialog("Please enter the starting number of organisms");
startPopulation=Double.parseDouble(input);
input=JOptionPane.showInputDialog("Please enter their daily population increase as a percentage");
increase=Float.parseFloat(input);
input=JOptionPane.showInputDialog("Please enter how many days they will multiply in");
daysofIncrease=Double.parseDouble(input);
for (int days=0;days<=daysofIncrease+1;days++)
{
if (startPopulation>=2 || increase >0 || daysofIncrease>=1)
{
endPopulation=(startPopulation*increase)+startPopulation;
JOptionPane.showMessageDialog(null,"This is the organisms end population: "+endPopulation+" for day: "+days);
}
else
{
input=JOptionPane.showInputDialog("Please enter the starting number of organisms");
startPopulation=Double.parseDouble(input);
input=JOptionPane.showInputDialog("Please enter their daily population increase as a percentage");
increase=Float.parseFloat(input);
input=JOptionPane.showInputDialog("Please enter how many days they will multiply in");
daysofIncrease=Double.parseDouble(input);
}
}
}
}
Your line
endPopulation=(startPopulation*increase)+startPopulation;
Will not calculate the end population correctly. You haven't used daysofIncrease at all.
I think you'll need to loop through the days. Note that I have not tested this, may need tweaking, but it should give you the idea:
double interimPopulation = startPopulation;
for (int days=1; days<=daysofIncrease; days++) {
interimPopulation *= (1.0 + (increase/100.0)); //get next day's population
}
endPopulation = interimPopulation;
I think you need to set somewhere in your loop this:
startPopulation = endPopulation;
And then you make another iteration of the loop.
Try this for example
endPopulation=(startPopulation*increase)+startPopulation;
startPopulation = endPopulation;
And if you don't want to lose the initial value of startPopulation,
just store it somewhere, before you change it (the way I suggest).