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.
Related
I need to ask the user for a number of dice to roll, (at least 1) and then loop if necessary to return a positive integer. Simple question, but I'm new to Java and don't understand how to do this using a while loop and bringing my variable back into scope.
Here's what I have so far, as anyone can see my variable 'numOfDice' is never pulled back into scope, as I need it later in my program to establish a variable array length.
while (true) {
System.out.println("Hello! How many dice would you like to roll");
int numOfDice = scan.nextInt();
if (numOfDice<=0) {
System.out.println("Please enter a positive integer and try again");
}else {
break;
}
}
So as you can see my variable is never pulled back into scope, and I've tried initializing it before the while loop, with no luck. I've also tried
System.out.println("Hello! How many dice would you like to roll");
int numOfDice = scan.nextInt();
while (true) {
if (numOfDice<=0) {
System.out.println("Please enter a positive integer and try again");
}else {
break;
}
}
But this results in an infinite loop if a negative number is an input, as my if will repeat forever.
Anyways, I'm very new to Java (my 6th week learning) and any veteran help would be much appreciated. I'm willing to learn new ways to create these loops or tricks to pull variables back into scope (if possible).
Solved. Thanks to tgdavies telling me to split the declaration and assignment I was able to finish this problem. Here's the solution for anyone who stumbles upon this.
System.out.println("Hello! How many dice would you like to roll");
int numOfDice;
numOfDice = scan.nextInt();
while (true) {
if (numOfDice <= 0) {
System.out.println("Please enter a positive integer and try again");
numOfDice = scan.nextInt();
} else {
break;
}
}
This is very simple.
First you have to declare your variable outside the loop.
int numOfDice = -1;
Then you need to think of a way to update the state of your variable numOfDice inside the loop. Hence,
numOfDice = sc.nextInt();
Should be inside your loop. Now, the state of your variable numOfDice is updated. After that we can check if the value is a negative or not, and reiterate the loop accordingly.
Hence, the overall code will look like this.
int numOfDice = -1; //Declaration - value is negative because the while loop has to be executed at least once.
Scanner sc = new Scanner(System.in);
while(numOfDice<=0){ // checks if the variable is negative or positive, loop continues if the value is negative
System.out.println("Hello! How many dice would you like to roll");
numOfDice = sc.nextInt(); //updates the state of the variable
if (numOfDice<=0) {
// this line will be printed only if the value is negative.
System.out.println("Please enter a positive integer and try again");
}
}
Hope this answer is helpful.
Refer this article to understand more about while loops in java.
Let me start by showing my solution first...
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Let's start rolling some dice");
while (true) {
System.out.println("Hello! How many dice would you like to roll");
int numOfDice = scan.nextInt();
if (numOfDice < 0) {
System.err.println("Please enter a positive integer and try again");
} else if (numOfDice == 0) {
System.out.println("Goodbye!");
break;
}
}
scan.close();
}
As you can see, it is not much of a variation, but it has clear boundaries. For example, you can't have a negative number of dice rolled. So checking for the number of dice to be less than zero (negative) is an error and an appropriate message is shown when that condition is reached.
The second thing you see is a clear case for ending the "forever" loop. And that is when zero is passed through the Scanner object. Not much of an explanation required. Pass zero and simply break out of the loop.
The rest, if a positive integer is passed, keep rolling the dice!
Output sample
Let's start rolling some dice
Hello! How many dice would you like to roll
2
Hello! How many dice would you like to roll
3
Hello! How many dice would you like to roll
9
Hello! How many dice would you like to roll
-3
Please enter a positive integer and try again
Hello! How many dice would you like to roll
-2
Please enter a positive integer and try again
Hello! How many dice would you like to roll
1
Hello! How many dice would you like to roll
3
Hello! How many dice would you like to roll
0
Goodbye!
...to return a positive integer
Sorry for the dramatic heading, but I miss this from the OPs question the first time I read it. The code above keeps rolling until the user enters zero. Let's modify this so that it returns a positive integer.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Let's start rolling some dice");
while (true) {
System.out.println("Hello! How many dice would you like to roll");
int numOfDice = scan.nextInt();
if (numOfDice < 0) {
System.err.println("Please enter a positive integer and try again");
} else if (numOfDice == 0) {
System.out.println("Goodbye!");
break;
} else {
// Add some code here (i.e. a Random generation of dice values 1-6)
System.out.println("You rolled a " + diceRollValue);
break;
}
}
scan.close();
}
Variable Scope
Since the OP seems to struggle with issues related to scope, I will expand on this answer to focus on scope. Good coding practices call for minimizing the scope of variables. This means (in theory):
No global variables, period!
Local variables should be declared at the lowest possible block.
Variables shall be declared as close to the point of usage as possible.
Of course, in practice, global variables are often necessary. But what no developer should do is declare global variables by default. Instead, all variables shall be declared at the lowest levels of the code, and then "bubbled up" as needed and stop "bubbling" them up when the desired accessibility is reached. Let's look at an example from this code.
The variable numOfDice is declared inside the while loop. This is the lowest level where this variable can be declared. Since the variable is used at the top of the loop, it is OK to declare it and assign a value in the same line. The question is, should this variable be declared outside the loop? The answer is yes, for a very specific reason.
Creating a "forever" loop while(true){...} may not be a good idea. IN FACT, it can be argued that putting the break condition there might be a better coding practice than to include the break condition inside the loop. So, for this reason (and improving readability of the code as well), we might be better off setting the the variable outside the loop to a value, and then prompt the user to enter the number of rolls inside the loop like this:
System.out.println("Let's start rolling some dice");
int numOfDice = -1;
while (numOfDice != 0) {
System.out.println("Hello! How many dice would you like to roll");
int numOfDice = scan.nextInt();
...
}
Setting the value to -1 allows the instruction pointer to enter the loop because the evaluation of numOfDice returns true. Once inside the loop, it will continue to iterate until the evaluation returns false; and this is when the user enters 0. In the original code, negative values prompt an error message. Negative and positive values continue the "game". This is perfectly fine. As to the improved readability, when you see while (numOfDice != 0) the intent is clear; much better than to "hide" the break condition inside the loop. If the loop contain a lot of lines of code, the break condition is harder to find. So, in the end, this is a better solution.
An alternative is to use a do...while loop. This is the preferred structure when the intent is for the loop to run at least once. This is possible because the break condition is evaluated at the end of the loop rather than at the beginning in a conventional while loop. The equivalent do...while loop is as follows:
System.out.println("Let's start rolling some dice");
int numOfDice = 0; // initialize to the break condition value (just in case)
do {
System.out.println("Hello! How many dice would you like to roll");
int numOfDice = scan.nextInt();
...
} while (numOfDice != 0);
The last thing with regards to scope. I mentioned before that variables should be declared as close to the point of usage as possible. This means that instead of this
public void myMethod() {
int myVariable = 0
.
.
.
.
.
myVariable = someCodeThatSetsValue();
.
.
}
You should do this instead to follow best practices
public void myMethod() {
.
.
.
.
.
.
int myVariable = someCodeThatSetsValue();
.
.
}
I have a project for my computer science class and we're making battleship. Part of the program is that we have make sure that the piece the player puts down does not go off of the board.
I've made a method to check to see whether it goes off the board:
private static boolean test(String s, int row, int column,int spaces)
{
if(s.equals("right")&&column+5<=10)
{
return true;
}
if(s.equals("up")&&row-spaces>=0)
{
return true;
}
if(s.equals("left")&&column-spaces>=0)
{
return true;
}
if(s.equals("Down")&&row+spaces<=10)
{
return true;
}
return false;
}
But once I've gotten it to print out an error message, I'm not sure how to make it so that the program can re-recieve the new position for the piece, without putting an if statement in and if statement in an if statement (and on and on), because you need to check the new position to make sure it doesn't go off of the board.
Here is the part where I get the position of the playing piece (although I don't think you need it)
Scanner sonic= new Scanner(System.in);
System.out.println("Please input the row where you want the aircraft carrier (5 spaces) to begin: ");
int beginrow = sonic.nextInt();
System.out.println("Please input the column where you want the aircraft carrier (5 spaces) to begin: ");
int begincolumn = sonic.nextInt();
System.out.print("Please input what direction (up, down, left, right) \nyou want your battle ship to face, making sure it doesn't go off of the board.");
String direction = sonic.next();
And here's one of the if statements that I use to check/place the pieces
if(direction.equals("left")&&test("left",beginrow,begincolumn,5))
{
for(int i = beginrow; i>beginrow-5; i--)
{
battleship[begincolumn-1][i-1] = ('a');
}
}
else if(!test("left",beginrow,begincolumn,5))
{
System.out.println(" ");
System.out.println("*****ERROR: your piece goes off the board, please re-enter your position and direction*****");
}
This may be a duplicate, but I didn't know how to reword my search to find what I wanted. (So if anyone could direct me to the right article, that'd be nice as well)
What you should do is split your code appropriately into methods and call that methods repeatedly until your program is satisfied with the outcome.
For example:
create a method startGame() which has the job call methods getting user input until satisfied
make a method to request the user to input all the different ships and other required data
That might look something like
public void startGame() {
// do some setup
while(!requestShipInput()) { // request ship data until the data is valid
System.out.println(" ");
System.out.println("*****ERROR: your piece goes off the board, please re-enter your position and direction*****");
}
// do some more ship setup
// get the actual playing started
}
public boolean requestShipInput() {
Scanner sonic= new Scanner(System.in);
System.out.println("Please input the row where you want the aircraft carrier (5 spaces) to begin: ");
int beginrow = sonic.nextInt();
System.out.println("Please input the column where you want the aircraft carrier (5 spaces) to begin: ");
int begincolumn = sonic.nextInt();
System.out.print("Please input what direction (up, down, left, right) \nyou want your battle ship to face, making sure it doesn't go off of the board.");
String direction = sonic.next();
if(direction.equals("left")&&test("left",beginrow,begincolumn,5)) {
for(int i = beginrow; i>beginrow-5; i--) {
battleship[begincolumn-1][i-1] = ('a');
}
return true; // valid ship data
}
return false; // invalid ship data
}
As a first step, separate input validation from taking the action based on that input - you already have the validation logic in a separate function, so this is easy. Then figure out what needs to be done in case of invalid input - in your case, you need to ask for new input until you get a valid position:
do {
System.out.println("Please input the row where you want the aircraft carrier (5 spaces) to begin: ");
beginrow = sonic.nextInt();
System.out.println("Please input the column where you want the aircraft carrier (5 spaces) to begin: ");
begincolumn = sonic.nextInt();
System.out.print("Please input what direction (up, down, left, right) \nyou want your battle ship to face, making sure it doesn't go off of the board.");
direction = sonic.next();
} while (!test(direction, beginrow, begincolumn, 5))
After that, you know you've got a valid position.
My next step would probably be to group the information required to describe a ship on the board (i.e. beginrow,begincolumn,direction, probably also size) in a separate Object - possibly named Ship.
I think you could pretty naturally use recursion here:
public void getInput() {
// scanner code to get input
if (!test("left",beginrow,begincolumn,5)) { // test failed
getInput()
return
}
// test succeeded, continue
}
You already have something to the limits of you board? If you execute the check first, you don't need to execute a cascade of if-else
if(!test(direction,beginrow,begincolumn,size))
{
System.out.println(" ");
System.out.println("*****ERROR: your piece goes off the board, please re-enter your position and direction*****");
} else {
// check for collision with already placed ships
}
Keep in mind that there is a chance to combine up/down and left/right. The calculation rules are nearly the same and you only have to decide if you have to look to the one or the other direction.
Sorry for such a basic level question guys. But I'm starter in programming. Not a computers guy. So kindly help me.
In this code when I give input 1000000000, 1000000000, 999999999 the answer should be 4. But my answer is 1. I expect the if statement to execute but it is not executing here.
if you take m*n as a room and "a" as the side as a square tile. Then I want to count MINIMUM no. of tiles required to fill the floor of room. tiles may cover a bit more area but should not leave the room empty. this is my objective. It's working with inputs like 6,6,4 or 15,20,13 etc.
Now its working guys. I had posted the correct code with those minor changes below.
import java.util.Scanner;
public class TheatreSquare {
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
float m=input.nextFloat();
float n=input.nextFloat();
float a=input.nextFloat();
long i=(int)(m/a);
long j=(int)(n/a);
if((a*a*i*j)<m*n){
if(a*i<m){
//to check weather it is entering if()
System.out.println("true");
i+=1;
}
if(a*j<n){
System.out.println("false");
//to check weather it is entering if()
j+=1;
}
}
System.out.println((double)(i*j));
}
}
Your floats are overflowing when you multiply them. Defining m, n and a as doubles will solve the issue:
double m = input.nextDouble();
double n = input.nextDouble();
double a = input.nextDouble();
The int conversion loses precision.
Here in this case, a*a*i*j is equal to m*n Hence the if loop will not execute. Also a*i is equal to m and a*j is equal to n.
Hence i isi and j is 1, so i*j is 1.
You need to allow it to go if it is equal too.
Replace
if((a*a*i*j)<m*n){
if(a*i<m){
//to check weather it is entering if()
System.out.println("true");
i+=1;
}
if(a*j<n){
System.out.println("false");
//to check weather it is entering if()
j+=1;
}
}
with
if((a*a*i*j) <= m*n){
System.out.println("Entered if block");
if(a*i <= m){
//to check weather it is entering if()
System.out.println("true");
i+=1;
}
if(a*j <= n ){
System.out.println("false");
//to check weather it is entering if()
j+=1;
}
System.out.println("i is:"+ i +"j is:"+j);
}
thankyou #Mureinik, #Uma Lakshmi Kanth, #Diego Martinoia for helping to solve this. All your answers contributed to solve my question. this is working now. as #Mureinik said my floats are overflowing( though I dont know the meaning). I used Double instead of float and that's it. its working. :-)
import java.util.Scanner;
public class TheatreSquare {
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
double m=input.nextDouble();
double n=input.nextDouble();
double a=input.nextDouble();
long i=(long)(m/a);
long j=(long)(n/a);
if((a*a*i*j) <m*n){
if(a*i < m){
//to check weather it is entering if()
i+=1;
}
if(a*j < n ){
//to check weather it is entering if()
j+=1;
}
}
System.out.println((long)(i*j));
}
}
The reason for your behavior is that you are reading numbers as floats. Floats have limited precision, so your m n and a are the same value (at runtime). Reading them as long (and getting rid of all the decimal stuff) should help. But, as mentioned in the comment, we don't know what you wanted to achieve!
--- EDIT DUE TO NEW INFO ---
You have to cover an area of m times n square meters. You have an unit of computation of 1 tile, i.e. a times a square meters (both assumed to be decimal).
Assuming you can cut your tile with good-enough precision, your result will be:
Math.ceiling((m*n) / (a*a));
i.e., either your area is an exact multiple of your tiles (and you can always cut them in rectangles to match the shape of the room), or you'll have some "spare" space to fill in, thus you will need 1 more tile, a part of which you'll use to cover the remaining space, and a part of which you'll throw away.
I'm sorry the code is so long, I just need to know what I'm missing to initialize all my decisions. The compiler is complaining about my variable not being initialized. Thank you.
import javax.swing.JOptionPane;
public class SemesterProject
{
public static void main(String[] args)
{
String SemesterProject =
"Hello and welcome to Juans adventure story! Your choices throughout this story will bring your doom or your salvation!\n"+
"No one has been able to complete this story and lived to tell the tale, but maybe you will be the first one!.\n"+
"Our story begins in the small town of Badow. Many people in the town spread rumors of brave adventurers that\n"+
"go on the quest to solve the mysterious riddles of the abandond castle at the top of the hill.\n"+
"No one really knows who or what lies at the heart of the castle. Legend says that monsters guards the\n"+
"the many riches once owned by the family that died there, so many years ago.\n"+
"The Castle is full of dizzing turns and hidden corridors and dangerous monsters. Many adventureres \n"+
"have gone insane because of how they lose their way or go get stuck. It is the hardes quest known to man.\n"+
"The quest for you is to go to the castle, solve the riddles and claim the riches.\n"+
"The world will little note, nor long remember what we say here, but it can never forget what they did here.\n"+
"Be careful. Watch your back and always mark your trail because you never know what you will find next.\n"+
"If for some crazy reason you end up successful in this task, you will not only get the riches in the castle but\n"+
"you will also be crowned the king of the town of Badow. If you die, you lose.\n"+
"The last thing you have to do is input some of your personal information so that we keep you in our records.\n";
JOptionPane.showMessageDialog(null,SemesterProject);
String name = JOptionPane.showInputDialog(null,"Please give us your first name.");
String age = JOptionPane.showInputDialog(null,"Please give us your age.");
String weight = JOptionPane.showInputDialog(null,"Please give us your weight.");
String haircolor = JOptionPane.showInputDialog(null,"Please give us your hair color.");
String GPA = JOptionPane.showInputDialog(null,"Please give us your GPA.");
String favoritecolor = JOptionPane.showInputDialog(null,"Please give us your favorite color.");
String decision1,decision2,decision3,decision4,decision5,decision6;
decision1 = JOptionPane.showInputDialog("Brave adventurer, welcome to the entrance of the abandoned castle of town Badow. At this moment\n"+
"You have a choice right now to give up and take a walk of shame back to the village, and to safety\n"+
"Or you can decide to go in and test your unique set of skills on the various challenges of the adventure\n"+
"ahead of you. Enter the number of your choice.You can either 1. Enter the castle 2. Stay behind.");
if (decision1.equals("1"))
{
decision2 = JOptionPane.showInputDialog
("You find yourself at the entrance of the castle with a choice to go down a dark hall\n"+
"or to the closest room on the right side. Be vary wary the darkness can make you lose your mind and go insane and remember\n"+
"to keep track of were you are. 1. Into the room 2. Down the hall.");
}
else
{
JOptionPane.showMessageDialog(null,"You go back to your boring life in the town, you wont be remembered by anything and you\n"+
"lost your chance at getting the riches that lie deep in the castle. You lose.");
}
if (decision2.equals("1"))
{
decision3 = JOptionPane.showInputDialog
("You step into the room and find some medication and a lantern with some oil.\n"+
"you also find a sword. You can choose now to go back to the dark hallway or to go down a hidden trap door in the room. It could be\n"+
"a shortcut or it could lead somewhere dangerous. 1. Back down the hall 2. Take your chances with the trapdoor.");
}
else
{
JOptionPane.showMessageDialog(null,"you should have looked in the room, you quickly lose your way and the darkness\n"+
"makes you crazy.");
}
if (decision3.equals("1"))
{
decision4 = JOptionPane.showInputDialog
("You are back in the hall slowly hearing the echoing sound of your footsteps\n"+
"you head downstairs into what seems to be another hallway but this one full of barred rooms, kind of like a dungeon. There is\n"+
"a skeleton body on the ground which seems to be of another failure by an adventurer in the castle. You reach the end of the hall\n"+
"and there is two ways to go left or right. 1. Left 2. Right.");
}
else
{
JOptionPane.showMessageDialog(null,"You squeeze through the trapdoor and fall down to the ground where you find youself lost and disoriented\n"+
"You dont know where you are and start to panic, you start becoming insane and die.");
}
if (decision4.equals("1"))
{
decision5 = JOptionPane.showInputDialog
("You go left and hear a door open behind you, you panic and start to run\n"+
"you run intro different halls to try and escape but you trip. You just remembered that you have a sword with you and can now\n"+
"choose what to do 1. Take out sword and fight enemy 2. Get up and keep running.");
}
else
{
JOptionPane.showInputDialog(null,"You go right and get locked in behind you. You realize that there isnt anwhere to go\n"+
"and get lost in the darkest part of the castle and die alone.");
}
if (decision5.equals("1"))
{
decision6 = JOptionPane.showInputDialog
("You were able to fight of the armored enemy. But something tells you that that isnt the last of them. You continue on down the\n"+"hall and see from the distance to what seems to be your first prize. It cant be that easy.");
}
}
}
Define the decision variables as null. Instead of:
String decision1,decision2,decision3,decision4,decision5,decision6;
Define the variables as:
String decision1 = null;
String decision2 = null;
String decision3 = null;
String decision4 = null;
String decision5 = null;
String decision6 = null;
decision2 is only being set if decision1 is equal to 1. I think you want to put the if statements for the other decisions inside of each other like below:
if (decision1.equals("1"))
{
decision2 = JOptionPane.showInputDialog
("You find yourself at the entrance of the castle with a choice to go down a dark hall\n"+
"or to the closest room on the right side. Be vary wary the darkness can make you lose your mind and go insane and remember\n"+
"to keep track of were you are. 1. Into the room 2. Down the hall.");
if (decision2.equals("1"))
{
decision3 = JOptionPane.showInputDialog
("You step into the room and find some medication and a lantern with some oil.\n"+
"you also find a sword. You can choose now to go back to the dark hallway or to go down a hidden trap door in the room. It could be\n"+
"a shortcut or it could lead somewhere dangerous. 1. Back down the hall 2. Take your chances with the trapdoor.");
}
else
{
JOptionPane.showMessageDialog(null,"you should have looked in the room, you quickly lose your way and the darkness\n"+
"makes you crazy.");
}
}
else
{
JOptionPane.showMessageDialog(null,"You go back to your boring life in the town, you wont be remembered by anything and you\n"+
"lost your chance at getting the riches that lie deep in the castle. You lose.");
}
You must initialize your String variables (decision1, decision2,...) as:
String decision1 = null, decision2 = null, decision3 = null, decision4 = null, decision5 = null, decision6 = null;
Note that you don't get a compile error for decision1 because in the line
decision1 = JOptionPane.showInputDialog(...);
it is being initialized.
Also, your program's logic is bad. If decision1 is not 1, then you will just show a message, but the program will continue to check the next condition:
if (decision2.equals("1"))
where you will get a NullPointerException because you are comparing null with 1.
JOptionPane variable might not have been initialized
So keep in mind one thing that whenever you get such kind of error messages try to see that your variables are properly declared.
See when you try to use int variable it can give you error message if that variable is used in some computation. So try to initialize the variables like:
int a=0;
You can do the same thing with string variables also like:
String a=null;
Returning to answer
In your code you have just declared the variables , but the fact is that you have to actually initialize them.
Replace
String decision1,decision2,decision3,decision4,decision5,decision6;
By
String decision1=null,decision2=null,decision3=null,decision4=null,decision5=null,decision6=null;
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.