Syntax errors in pizza order program - java

Can anybody help me with this?
simple pizza order program
I tried to run it in commandpromt and there are a lot of error
I have tried to change the double into int.. but the result is still error
<pre>
public class PizzaOrder
{
public static final String PIZZA_SMALL = "S";
public static final String PIZZA_MEDIUM = "M";
public static final String PIZZA_LARGE = "L";
public static final String PIZZA_COLLOSAL = "C";
public static final double SMALL_DIAMETER = 9;
public static final double MEIDUM_DIAMETER = 13;
public static final double LARGE_DIAMETER = 17;
public static final double COLOSSAL_DIAMETER = 26;
public static final double PRICE_SMALL = 8;
public static final double PRICE_MEDIUM = 11;
public static final double PRICE_LARGE = 15;
public static final double PRICE_COLOSSAL = 21;
public static final double PRICE_TAX = 0.095;
public static final double PRICE_TOPPING = 0.99;
public static final int MAX_TOPPINGS = 8;
public static final int MIN_TOPPINGS = 0;
/**
* Pizza Order
*
* #param args command-line arguments
*/
public static int getDiameter(String pizzaName)
{
if (pizzaName.equals(PIZZA_SMALL))
{
return SMALL_DIAMETER;
}
else if (pizzaName.equals(PIZZA_MEIDUM))
{
return MEDIUM_DIAMETER;
}`enter code here`
else if (pizzaName.equals(PIZZA_LARGE))
{
return LARGE_DIAMETER;
}
else
{
return COLOSSAL_DIAMETER;
}
}
public static int getBasePrice(String pizzaName)
{
if (pizzaName.equals(PIZZA_SMALL))
{
return PRICE_SMALL;
}
else if (pizzaName.equals(PIZZA_MEIDUM))
{
return PRICE_MEDIUM;
}
else if (pizzaName.equals(PIZZA_LARGE))
{
return PRICE_LARGE;
}
else
{
return PRICE_COLOSSAL;
}
}
there are error about the scanner too idk why
there are 13-20 errors and mostly because of the variables PIZZA_SMALL, etc
some errors say "incompetible types" and the other says "cannot find symbol"
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter The Size of Pizza you"
+ "want: (S/M/L/C)");
String option = keyboard.nextLine().trim().substring(0,
1).toUppercase();
double pizzaPrice;
double pizzaSize;
if(option.equals(PIZZA_SMALL))
{
pizzaPrice = SMALL_DIAMETER;
pizzaSize = SMALL_DIAMETER;
}
else if (option.equals(PIZZA_MEIDUM))
{
pizzaPrice = PRICE_MEDIUM;
pizzaSize = MEDIUM_DIAMETER;
}
else if (option.equals(PIZZA_LARGE))
{
pizzaPrice = PRICE_LARGE;
pizzaSize = LARGE_DIAMETER;
}
else
{
option = PIZZA_COLOSSAL;
pizzaPrice = PRICE_COLOSSAL;
pizzaSize = COLOSSAL_DIAMETER;
}
System.out.println("Pizza Size: " + option);
System.out.println("Enter The Number of Toppings" +
"you want:(0-8)");
int pizzaTopping = keyboard.nextInt();
if(pizzaTopping < MIN_TOPPINGS)
{
pizzaTopping = MIN_TOPPINGS;
}
else if(pizzaTopping > MAX_TOPPINGS)
{
pizzaTopping = MAX_TOPPINGS;
}
else
{
pizzaTopping = pizzaTopping;
}
int radius = getDiameter(option) / 2;
double squareInches = radius * radius * Math.PI;
System.out.println("Pizza Size: " + option + "( " + pizzaSize +
"inch -- " + squareInches + " square inches)" );
System.out.println("Toppings: " + pizzaTopping);
double priceWithToppings = getBasePrice(option) + pizzaTopping * 9;
System.out.println("Price: " + priceWithToppings);
double pizzaTax = priceWithToppings * PRICE_TAX;
System.out.println("Tax: "+ pizzaTax);
double totalPrice = priceWithToppings + pizzaTax;
System.out.println("Total Price: " + totalPrice);
double priceEachSquareInch = priceWithToppings / squareInches;
System.out.println("Price/sq.in.: " + priceEachSquareInch);
}
}

Your PizzaOrder class should be as follows:
public class PizzaOrder {
public static final String PIZZA_SMALL = "S";
public static final String PIZZA_MEDIUM = "M";
public static final String PIZZA_LARGE = "L";
public static final String PIZZA_COLLOSAL = "C";
public static final double SMALL_DIAMETER = 9;
public static final double MEDIUM_DIAMETER = 13;
public static final double LARGE_DIAMETER = 17;
public static final double COLOSSAL_DIAMETER = 26;
public static final double PRICE_SMALL = 8;
public static final double PRICE_MEDIUM = 11;
public static final double PRICE_LARGE = 15;
public static final double PRICE_COLOSSAL = 21;
public static final double PRICE_TAX = 0.095;
public static final double PRICE_TOPPING = 0.99;
public static final int MAX_TOPPINGS = 8;
public static final int MIN_TOPPINGS = 0;
/**
* Pizza Order
*
* #param args
* command-line arguments
*/
public static double getDiameter(String pizzaName) {
if (pizzaName.equals(PIZZA_SMALL)) {
return SMALL_DIAMETER;
} else if (pizzaName.equals(PIZZA_MEDIUM)) {
return MEDIUM_DIAMETER;
} else if (pizzaName.equals(PIZZA_LARGE)) {
return LARGE_DIAMETER;
} else {
return COLOSSAL_DIAMETER;
}
}
public static double getBasePrice(String pizzaName) {
if (pizzaName.equals(PIZZA_SMALL)) {
return PRICE_SMALL;
} else if (pizzaName.equals(PIZZA_MEDIUM)) {
return PRICE_MEDIUM;
} else if (pizzaName.equals(PIZZA_LARGE)) {
return PRICE_LARGE;
} else {
return PRICE_COLOSSAL;
}
}
}
Notice how I corrected the return type from int to double on getDiameter and getBasePrice, as the constants you are trying to return are double. I also fixed the misspelling of "Medium" in some places.
To fix the scanner error, you must import it's package using: (Add this at the top of the file)
import java.util.Scanner;
You main method should look like this: (Again, misspelling variables and casting errors)
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter The Size of Pizza you" + "want: (S/M/L/C)");
String option = keyboard.nextLine().trim().substring(0,1).toUpperCase();
double pizzaPrice;
double pizzaSize;
if(option.equals(PIZZA_SMALL))
{
pizzaPrice = SMALL_DIAMETER;
pizzaSize = SMALL_DIAMETER;
}
else if (option.equals(PIZZA_MEDIUM))
{
pizzaPrice = PRICE_MEDIUM;
pizzaSize = MEDIUM_DIAMETER;
}
else if (option.equals(PIZZA_LARGE))
{
pizzaPrice = PRICE_LARGE;
pizzaSize = LARGE_DIAMETER;
}
else
{
option = PIZZA_COLLOSAL;
pizzaPrice = PRICE_COLOSSAL;
pizzaSize = COLOSSAL_DIAMETER;
}
System.out.println("Pizza Size: " + option);
System.out.println("Enter The Number of Toppings" +
"you want:(0-8)");
int pizzaTopping = keyboard.nextInt();
if(pizzaTopping < MIN_TOPPINGS)
{
pizzaTopping = MIN_TOPPINGS;
}
else if(pizzaTopping > MAX_TOPPINGS)
{
pizzaTopping = MAX_TOPPINGS;
}
double radius = getDiameter(option) / 2;
double squareInches = radius * radius * Math.PI;
System.out.println("Pizza Size: " + option + "( " + pizzaSize +
"inch -- " + squareInches + " square inches)" );
System.out.println("Toppings: " + pizzaTopping);
double priceWithToppings = getBasePrice(option) + pizzaTopping * 9;
System.out.println("Price: " + priceWithToppings);
double pizzaTax = priceWithToppings * PRICE_TAX;
System.out.println("Tax: "+ pizzaTax);
double totalPrice = priceWithToppings + pizzaTax;
System.out.println("Total Price: " + totalPrice);
double priceEachSquareInch = priceWithToppings / squareInches;
System.out.println("Price/sq.in.: " + priceEachSquareInch);
}
}
If you want to cast a double to an int, you need to do int something = (int)myDouble. Also pay attention when writing your variable names, as they must be exactly the same as the definition or they will throw an error. Also, if a method returns an int, but you try and return a double, it will result in an error, as the return type must be the same as what is defined in the method.

Firstly, take a good look through your code as many of your errors are typos - e.g. toUppercase(), COLLOSAL etc.
And, as per Ben's comment you are using doubles for your constants but then your methods are all integers. Java won't let you do this automatically as it results everything after the decimal point being lost as integers are whole numbers only.
When these two things are changed your code appears to work - at a quick glimpse at least.

Related

JAVA: error: unexpected type

public abstract class Character{
public enum Type{ ROGUE, PALADIN, JACKIE_CHEN, SKELETON, GOBLIN, WIZARD}
private String name;
private int hitPoints;
private int strength;
private Weapon weapon;
//other attributes
//methods
public Character(Type characterType){
switch(characterType){
case ROGUE:
//set the attributes for a Rogue
name = "Rogue";
// TODO: set other attributes
hitPoints = 55;
strength = 8;
Weapon rogue = new Weapon("Short Sword", 1, 4);
break;
case PALADIN:
//set the attributes for a Rogue
name = "Paladin";
// TODO: set other attributes
hitPoints = 35;
strength = 14;
Weapon paladin = new Weapon("Long Sword",3,7);
break;
case JACKIE_CHEN:
name = "Jackie Chen";
hitPoints =45;
strength = 10;
Weapon jackie = new Weapon("Jump Kick",2, 6);
break;
case SKELETON:
name = "Skeleton";
hitPoints = 25;
strength = 3;
Weapon skeleton = new Weapon("Short Sword" ,1, 4);
break;
case GOBLIN:
name = "Goblin";
hitPoints = 25;
strength = 4;
Weapon goblin = new Weapon("Axe",2,6);
break;
case WIZARD:
name = "Wizard";
hitPoints = 40;
strength = 8;
Weapon wizard = new Weapon("Fire Blast", 4, 10);
break;
}
}
public String getName(){
return name;
}
public int getHitPoints(){
return hitPoints;
}
public int getStrength(){
return strength;
}
public void setStrength(int _strength){
this.strength =_strength;
}
public void setWeapon(Weapon _weapon){
this.weapon = _weapon;
}
public void attack(){
}
public void increaseHitPoints(){
}
public void decreaseHitPoints(){
}
/*public boolean isDefeated(){
}*/
}
import java.util.Scanner;
import java.util.Random;
public class Player extends Character{
// attributes for the plauer class
// initilizes the fields
private int coins;
private Potion[] inventory;
Random randomNums = new Random();
Scanner keyboard = new Scanner(System.in);
//methods
public Player(Type playerType){
super(playerType);
coins = 0;
inventory = new Potion[5];
}
public void increaseStrength(int strengthIncrease){
enemy.getHitPoints() -= playerATK;
}
public int getCoins(){
return coins;
}
public void increaseCoins(int coins){
}
public void decreaseCoins(int coins){
}
public void addToInventory(String a, Type potion){
}
public void removeFromInventory(int index){
}
public void displayInventory(){
}
/*public int getNumOpenSlots(){
return numOpenSlots;
}*/
public void battleMinion(Enemy enemy){
Enemy goblin = new Enemy(Character.Type.GOBLIN);
int playerDamage =0, playerATK =0, enemyATK =0, enemyDamage =0;
if (enemy.getName() == "Goblin" && getName()=="Rogue"){
for (int i = 1; i <= goblin.getNumGoblins(); i++)
{
System.out.printf("***%s vs %s %d***\n", getName(), enemy.getName(), i);
while(enemy.getHitPoints() > 0 && getHitPoints() > 0)
{
playerDamage = randomNums.nextInt(Weapon.SHORT_SWORD_MAX - Weapon.SHORT_SWORD_MIN + 1) + Weapon.SHORT_SWORD_MIN;
playerATK = getStrength() + playerDamage;
enemy.getHitPoints() -= playerATK;
System.out.printf("%s attacks with ATK = %d + %d = %d\n", getName(), getStrength(), playerDamage, playerATK);
System.out.printf("%s HP is now %d - %d = %d\n\n", enemy.getName(), enemy.getHitPoints() + playerATK, playerATK, enemy.getHitPoints());
if (enemy.getHitPoints() <= 0)
break;
enemyDamage = randomNums.nextInt(Weapon.AXE_MAX - Weapon.AXE_MIN + 1) + Weapon.AXE_MAX;
enemyATK = enemy.getStrength() + enemyDamage;
getHitPoints() -= enemyATK;
System.out.printf("%s attacks with ATK = %d + %d = %d\n", getName(), enemy.getStrength(), enemyDamage, enemyATK);
System.out.printf("%s HP is now %d - %d = %d\n\n", getName(), getHitPoints() + enemyATK, enemyATK, getHitPoints());
} // end of while loop
if (getHitPoints() > 0){
System.out.printf("%s defeated %s %d!\n\n", getName(), enemy.getName(), i);
coins = randomNums.nextInt((50 - 30) + 1) + 30;
System.out.println(getName() + " gains " + coins + " gold coins!\n");
//player[4] += coins;
}
else
{
System.out.printf("--%s is defeated in battle!--\n\nGAME OVER\n", getName());
System.exit(0);
}
if(i <= goblin.getNumGoblins() - 1){
System.out.println("Press enter to continue...");
keyboard.nextLine();
}
}
}
Error is as follows
./Player.java:59: error: unexpected type
enemy.getHitPoints() -= playerATK;
^
required: variable
found: value
./Player.java:68: error: unexpected type
getHitPoints() -= enemyATK;
I know this is wrong, but what is the reason behind this? Also I have
public void increaseHitPoints(){
}
public void decreaseHitPoints(){
}
these two class in my character class, I don't how to code to make this work.
getHitPoints() is a method that returns a value. You can't assign anything to that expression, and the -= operator performs both subtraction and assignment.
Instead of
getHitPoints() -= playerATK;
write
setHitPoints (getHitPoints() - playerATK);
or
decreaseHitPointsBy (playerATK); // this approach would require a corresponding
// increaseHitPointsBy (value) method

Having trouble reseting game to previous round JAVA

I made a program which asks the user for their pet name and assigns it states of mind for 5 rounds. If the pet gets too angry it is put down.
What I am having trouble with is allowing the user to restart to an earlier stage at the game before the pet died.
Compiling the code would help illustrate the issue.
Any help would be appreciated.
import java.util.Random;
import java.util.Scanner;
class dinoo {
public static void main(String[] p) {
Pet p1 = new Pet();
Pet p2 = new Pet();
Scanner scanner = new Scanner(System.in);
String petname;
String species;
String angerlevel;
int thirst;
int hunger;
int irritability;
explain();
petname = askpetname();
species = askpetspecies();
int howmanyrounds = 5;
for (int i = 0; i < howmanyrounds; i++) {
int number = i + 1;
String num = Integer.toString(number);
print("Round " + number);
String[] emotionalstate = newarray(5);
thirst = thirstlevel(p1);
hunger = hungerlevel(p1);
irritability = irritabilitylevel(p1);
angerlevel = anger(hunger, thirst, irritability);
p1 = setpetname(p1, petname);
p1 = setspecies(p1, species);
p1 = setthirst(p1, thirst);
p1 = setanger(p1, angerlevel);
p1 = sethunger(p1, hunger);
p1 = setangervalue(p1, irritability);
print(petname + "'s thirst level is " + thirst + " , hunger level is " + hunger + ", irritability level is " + irritability + " and therefore emotional state is " + angerlevel);
if (angerlevel.equals("DANGEROUS")) {
print(petname + " is looking " + angerlevel + ", get out now! we will have to put " + petname + " down.");
boolean continueEnd = petdead();
if (continueEnd == false) {
System.exit(0);
} else {
emotionalstate = wheretogo(emotionalstate[]);
}
} else if (angerlevel.equals("Serene")) {
print("He looks " + angerlevel + ". Seems in a good mood.");
} else if (angerlevel.equals("Grouchy")) {
print("You should give him a treat to cheer him up.");
}
whatdoyouwant(p1);
print("Your pets emotion is now " + anger(getthirst(p1), gethungervalue(p1), getirritabilityvalue(p1)));
emotionalstate[i] = anger(getthirst(p1), gethungervalue(p1), getirritabilityvalue(p1));
print("Emotional state " + emotionalstate[i] + " has been saved!");
}
System.exit(0);
}
public static String[] wheretogo(String[] a) {
Scanner scanner = new scanner;
print("which level would you like to return to?");
int number = scanner.nextInt();
String level = a[number];
return a;
}
public static boolean petdead() {
Scanner scanner = new Scanner(System.in);
print("Your pet has been killed. Would you like to continue? (True or False)");
boolean yesorno = scanner.nextBoolean();
return yesorno;
}
public static int inputint(String message) {
Scanner scanner = new Scanner(System.in);
System.out.println(message);
int answer = scanner.nextInt();
return answer;
}
public static String[] newarray(int arraylength) {
String[] emotionalstate = new String[arraylength];
return emotionalstate;
}
//takes input from user to cheerup/feed/sing to the animal to lower values stored in setter/getter
public static Pet whatdoyouwant(Pet p1) {
Scanner scanner = new Scanner(System.in);
print("what would you like to do to the pet? (treat/water/sing)");
String ans = scanner.nextLine();
Random ran = new Random();
int reduction = ran.nextInt(6);
if (ans.equalsIgnoreCase("treat")) {
int hunger = gethungervalue(p1) - reduction;
if (hunger < 0) {
hunger = 0;
}
p1 = sethunger(p1, hunger);
print("Your pets hunger has been reduced to:");
printint(gethungervalue(p1));
} else if (ans.equals("sing")) {
int irrit = getirritabilityvalue(p1) - reduction;
if (irrit < 0) {
irrit = 0;
}
p1 = setirritability(p1, irrit);
print("Your pets irritability hs been reduced to:");
printint(getirritabilityvalue(p1));
} else if (ans.equals("water")) {
int thirst = getthirst(p1) - reduction;
if (thirst < 0) {
thirst = 0;
}
p1 = setthirst(p1, thirst);
print("Your pets thirst is has been reduced to:");
printint(getthirst(p1));
} else {
print("That action seems to agitate your pet, try something else before your pet becomes dangerous!");
}
return p1;
}
//GETTER METHOD
public static String getpetname(Pet p) {
return p.name;
}
public static String getspecies(Pet p) {
return p.species;
}
public static String getanger(Pet p) {
return p.anger;
}
public static int getthirst(Pet p) {
return p.thirst;
}
public static int gethungervalue(Pet p) {
return p.hunger;
}
public static int getangervalue(Pet p) {
return p.angervalue;
}
public static int getirritabilityvalue(Pet p) {
return p.irritability;
}
//SETTER METHOD
public static Pet setangervalue(Pet p, int whatsangervalue) {
p.angervalue = whatsangervalue;
return p;
}
public static Pet setpetname(Pet p, String name) {
p.name = name;
return p;
}
public static Pet setspecies(Pet p, String petspecies) {
p.species = petspecies;
return p;
}
public static Pet setanger(Pet p, String howangry) {
p.anger = howangry;
return p;
}
public static Pet sethunger(Pet p, int howhungry) {
p.hunger = howhungry;
return p;
}
public static Pet setthirst(Pet p, int howthirsty) {
p.thirst = howthirsty;
return p;
}
public static Pet setirritability(Pet p, int howirritable) {
p.irritability = howirritable;
return p;
}
//Method printing out statement to explain functionality of program
public static void explain() {
print("The following program demonstrates use of user input by asking for pet name.");
return;
}
//Method to ask the pet name
public static String askpetname() {
Scanner scanner = new Scanner(System.in);
print("Name your dinosaur pet!");
String petname = scanner.nextLine();
return petname;
}
//Method to ask the pet species
public static String askpetspecies() {
Scanner scanner = new Scanner(System.in);
print("What species is your pet?");
String petspecies = scanner.nextLine();
return petspecies;
}
//Randomly allocates thirst value 0-10
public static int thirstlevel(Pet p1) {
Random ran = new Random();
int thirst = ran.nextInt(11);
setthirst(p1, thirst);
return thirst;
}
//Randomly Allocates hunger value 0-10
public static int hungerlevel(Pet p1) {
Random ran = new Random();
int hunger = ran.nextInt(11);
sethunger(p1, hunger);
return hunger;
}
//randomly generates a irratibilty value
public static int irritabilitylevel(Pet p1) {
Random ran = new Random();
int irritable = ran.nextInt(11);
setirritability(p1, irritable);
return irritable;
}
//Method calculates the anger value based on the thirst/hunger/irritability average
public static String anger(int thirst, int hunger, int irritability) {
int angerscore = (thirst + hunger + irritability) / 3;
String temper;
temper = Integer.toString(angerscore);
if (angerscore <= 1) {
temper = "Serene";
} else if (angerscore <= 3) {
temper = "Grouchy";
} else if (5 < angerscore) {
temper = "DANGEROUS";
}
return temper;
}
//HELPER PRINT METHOD
public static String print(String message) {
System.out.println(message);
return message;
}
public static int printint(int message) {
System.out.println(message);
return message;
}
}//END class dinoo
class Pet {
String name;
String species;
int thirst;
int hunger;
String anger;
int irritability;
int angervalue;
} //END class pet
First of all you should look at the compile errors in your code before submitting a question here.
Please read the links provided in the comments to learn how to submit a proper question.
I tried to compile your code and it had the following errors:
java2.java:51: error: '.class' expected
emotionalstate = wheretogo(emotionalstate[]);
^
java2.java:75: error: '(' or '[' expected
Scanner scanner = new scanner;
That means in line 51, you're passing emotionalstate[] , which is emotional state array, whereas emotionalstate itself is an array, so you're passing an array of an array.
So just change it to emotionalstate = wheretogo(emotionalstate)
And in line 75, your initialization of Scanner object is wrong, change it to Scanner scanner = new Scanner();

quadratics methods in java displaying complex roots

everyone so I'm writting a program that solves quadratics (one doubled root and two doubled roots this seems to work but somehow I can't get it to solve complex roots? any help.
import javax.swing.JOptionPane;
public class QuadMethods {
static double a=0;
static double b=0;
static double c=0;
public static void main(String[] args) {
getUserInput(); // gets values into a, b, and c
double disc = getTheDiscriminant(a,b,c);
if (disc ==0) {
displayDoubledRealRoot(a,b,c);
//} else if (disc < 0) {
//displayComplexConjugates();
} else if (disc > 0) {
displayUnequalRealRoots(a,b,c);
//} else {
//System.out.println("Help! Arithmetic has failed!");
//
}
}
public static void displayUnequalRealRoots(double a, double b, double c) {
double disc = getTheDiscriminant(a,b,c);
double r1 = (-b+Math.sqrt(disc)/ (2*a));
double r2 = (-b-Math.sqrt(disc)/ (2*a));
String s = "two roots " + r1 + " and " + r2;
JOptionPane.showMessageDialog(null, s);
}
public static void displayDoubledRealRoot(double a, double b, double c) {
String s = "One doubled root = " + (-b/(2*a));
JOptionPane.showMessageDialog(null, s);
}
public static double getTheDiscriminant(double a, double b, double c) {
return b*b - 4*a*c;
}
public static void getUserInput() {
JOptionPane.showMessageDialog(null, "Getting coeffecients for ax^2+bx+c=0");
a = getANumber("a");
b = getANumber("b");
c = getANumber("c");
}
public static double getANumber(String p) {
boolean iDontHaveANumberYet = true;
double r = 0;
do {
try {
String aStr = JOptionPane.showInputDialog("Enter \"" + p + "\"");
r = Double.parseDouble(aStr);
iDontHaveANumberYet = false;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Hey, I can't deal with that. Must enter legal number.");
}
} while (iDontHaveANumberYet);
return r;
}
}
The solution:
import javax.swing.JOptionPane;
public class QuadMethods {
static double a=0;
static double b=0;
static double c=0;
public static void main(String[] args) {
getUserInput(); // gets values into a, b, and c
double disc = getTheDiscriminant(a,b,c);
if (disc ==0) {
displayDoubledRealRoot(a,b,c);
} else if (disc > 0) {
displayUnequalRealRoots(a,b,c);
} else {
// New method
displayComplexRoots(a,b,c);
}
}
public static void displayUnequalRealRoots(double a, double b, double c) {
double disc = getTheDiscriminant(a,b,c);
double r1 = (-b+Math.sqrt(disc)/ (2*a));
double r2 = (-b-Math.sqrt(disc)/ (2*a));
String s = "two roots " + r1 + " and " + r2;
JOptionPane.showMessageDialog(null, s);
}
public static void displayDoubledRealRoot(double a, double b, double c) {
String s = "One doubled root = " + (-b/(2*a));
JOptionPane.showMessageDialog(null, s);
}
public static double getTheDiscriminant(double a, double b, double c) {
return b*b - 4*a*c;
}
// New method
public static void displayComplexRoots(double a, double b, double c) {
double disc = 4 * a * c - b * b;
double dobleA = 2 * a;
String s = "two roots (" + (-b/dobleA) + "+" + (Math.sqrt(disc)/dobleA) + "i) and ("+ (-b/dobleA) + "" + (-Math.sqrt(disc)/dobleA) + "i)";
JOptionPane.showMessageDialog(null, s);
}
public static void getUserInput() {
JOptionPane.showMessageDialog(null, "Getting coeffecients for ax^2+bx+c=0");
a = getANumber("a");
b = getANumber("b");
c = getANumber("c");
}
public static double getANumber(String p) {
boolean iDontHaveANumberYet = true;
double r = 0;
do {
try {
String aStr = JOptionPane.showInputDialog("Enter \"" + p + "\"");
r = Double.parseDouble(aStr);
iDontHaveANumberYet = false;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Hey, I can't deal with that. Must enter legal number.");
}
} while (iDontHaveANumberYet);
return r;
}
}
General solution with complex numbers:
public class Complex {
double r;
double i = 0;
public Complex(double real, double imaginary) {
this.r = real;
this.i = imaginary;
}
public Complex(double real) {
this.r = real;
}
public Complex add(Complex c){
return new Complex(r+c.r, i+c.i);
}
public Complex cross(Complex c){
return new Complex(r*c.r - i*c.i, i*c.r + r*c.i);
}
public double getR() {
return r;
}
public double getI() {
return i;
}
#Override
public String toString() {
String result = Double.toString(r);
if (i < 0) {
result += " - " + ((i != -1)?Double.toString(-i):"") + "i";
} else if (i > 0) {
result += " + " + ((i != 1)?Double.toString(i):"") + "i";
}
return result;
}
public Complex[] squareRoot(){
double r2 = r * r;
double i2 = i * i;
double rR = Math.sqrt((r+Math.sqrt(r2+i2))/2);
double rI = Math.sqrt((-r+Math.sqrt(r2+i2))/2);
return new Complex[]{new Complex(rR, rI),new Complex(-rR, rI)};
}
public static Complex[] quadraticsRoot(double a, double b, double c) {
Complex[] result = new Complex(b*b - 4*a*c).squareRoot();
Complex bNegative = new Complex(-b);
Complex divisor = new Complex(1.0d / (2 * a));
for (int j = 0; j < result.length; j++) {
result[j] = bNegative.add(result[j]).cross(divisor);
}
return result;
}
public static void main(String[] args) {
Complex[] sol = quadraticsRoot(1,-10,34);
System.out.println(sol[0]);
System.out.println(sol[1]);
}
}

user input still stored after exceeding array length

Can someone see why the user can enter more than 27 apple, blueberry, or peanut pies? Even after declaring a final int for the max number of each type of pie.
The object here is to continually prompt the user for type of pie until the user wants to quit. Each time one of the valid inputs is entered it is stored in it's own array. After the user has indicated they are finished, calculations are done and a message is printed.
import javax.swing.JOptionPane;
public class CalcPieProfit {
public static void main(String[] args) {
final int MAX_PER_TYPE = 27;
int appleTotal = 0;
int blueberryTotal = 0;
int peanutTotal = 0;
String typeOfPie = getPieType();
while (!typeOfPie.equalsIgnoreCase("q")) {
if (typeOfPie.equalsIgnoreCase("apple")) {
String[] appleArray = fillApple(typeOfPie, MAX_PER_TYPE);
appleTotal++;
}
else if (typeOfPie.equalsIgnoreCase("blueberry")) {
String[] blueberryArray = fillBlueberry(typeOfPie, MAX_PER_TYPE);
blueberryTotal++;
}
else if (typeOfPie.equalsIgnoreCase("peanut")) {
String[] peanutArray = fillPeanut(typeOfPie, MAX_PER_TYPE);
peanutTotal++;
}
typeOfPie = getPieType();
}
if (typeOfPie.equalsIgnoreCase("q")) {
int totalPies = calcTotalPies(appleTotal, blueberryTotal, peanutTotal);
double profit = calcProfit(appleTotal, blueberryTotal, peanutTotal);
printReport(totalPies, appleTotal, blueberryTotal, peanutTotal, profit);
}
}
public static String getPieType() {
String pieType;
do {
try {
pieType = JOptionPane.showInputDialog("Enter a pie type:");
}
catch (NumberFormatException e) {
pieType = "";
}
if (!pieType.equalsIgnoreCase("apple") && !pieType.equalsIgnoreCase("blueberry") &&
!pieType.equalsIgnoreCase("peanut") && !pieType.equalsIgnoreCase("q")) {
JOptionPane.showMessageDialog(null, "Enter 'apple', 'blueberry', 'peanut', or 'q' only.");
}
} while (!pieType.equalsIgnoreCase("apple") && !pieType.equalsIgnoreCase("blueberry") &&
!pieType.equalsIgnoreCase("peanut") && !pieType.equalsIgnoreCase("q"));
return pieType;
}
public static String[] fillApple(String typeOfPie, int MAX_PER_TYPE) {
String[] appleArray = new String[MAX_PER_TYPE];
for (int i = 0; i < appleArray.length; i++) {
appleArray[i] = typeOfPie;
}
return appleArray;
}
public static String[] fillBlueberry(String typeOfPie, int MAX_PER_TYPE) {
String[] blueberryArray = new String[MAX_PER_TYPE];
for (int i = 0; i < blueberryArray.length; i++) {
blueberryArray[i] = typeOfPie;
}
return blueberryArray;
}
public static String[] fillPeanut(String typeOfPie, int MAX_PER_TYPE) {
String[] peanutArray = new String[MAX_PER_TYPE];
for (int i = 0; i < peanutArray.length; i++) {
peanutArray[i] = typeOfPie;
}
return peanutArray;
}
public static int calcTotalPies(int appleTotal, int blueberryTotal, int peanutTotal) {
int total = appleTotal + blueberryTotal + peanutTotal;
return total;
}
public static double calcProfit (int appleTotal, int blueberryTotal, int peanutTotal) {
final double APPLE_PROFIT = 5.94;
final double BLUEBERRY_PROFIT = 5.89;
final double PEANUT_PROFIT = 6.95;
double profit = (APPLE_PROFIT * appleTotal) + (BLUEBERRY_PROFIT * blueberryTotal) +
(PEANUT_PROFIT * peanutTotal);
return profit;
}
public static void printReport(int totalPies, int appleTotal, int blueberryTotal, int peanutTotal, double profit) {
if (totalPies > 0) {
JOptionPane.showMessageDialog(null,
"Pie Report\n\n" +
"Total pies: " + totalPies +
"\nTotal of apple pie: " + appleTotal +
"\nTotal of blueberry pie: " + blueberryTotal +
"\nTotal of peanut butter pie: " + peanutTotal +
"\nTotal profit: $" + String.format("%.2f", profit));
}
else {
JOptionPane.showMessageDialog(null, "Enjoy your day off.");
}
}
}
You are not really using the String[]s appleArray, blueberryArray and peanutArray - they are created in their respective method but not used anywhere else. For calculating the profits, you are (rightfully) only the total variables.
Instead of
if (typeOfPie.equalsIgnoreCase("apple")) {
String[] appleArray = fillApple(typeOfPie, MAX_PER_TYPE);
appleTotal++;
}
you should do something like
if (typeOfPie.equalsIgnoreCase("apple")) {
if (appleTotal >= MAX_PER_TYPE) {
JOptionPane.showMessageDialog(null, "Too many apples.");
} else {
appleTotal++;
}
}
(and the same for other pie types).
You're redeclaring the pie arrays each time you go to add them.
public static String[] fillApple(String typeOfPie, int MAX_PER_TYPE) {
String[] appleArray = new String[MAX_PER_TYPE];
for (int i = 0; i < appleArray.length; i++) {
appleArray[i] = typeOfPie;
}
return appleArray;
}
Each time you call this method, a new "appleArray" is generated. If you want it to persist between calls to this method, declare the appleArray as private static outside of the loop, and reference that instead.

Boolean if statement

public class Health
{
boolean dependency;
String insuranceOwner = "";
static final int basicHealthFee = 250;
static final int healthDiscount = 20;
public Health(boolean dependent, String insurance)
{
dependency = dependent;
insuranceOwner = insurance;
}
public double computeCost()
{
double healthFee;
if (dependency == true)
{
healthFee = basicHealthFee - (basicHealthFee * (healthDiscount/100.0));
}
else
{
healthFee = basicHealthFee;
}
return healthFee;
}
}
Health h34 = new Health(true, "Jim");
System.out.println("discount price: " + h34.computeCost());
When I enter in true as a parameter to the constructor, my computeCost method still runs the block as if dependency were to == false. Is there any reason why?
You're falling victim to integer division. 20/100 == 0, and anything multiplied by that is 0. To get around that, change your static final int declarations to doubles.
static final double basicHealthFee = 250D;
static final double healthDiscount = 20D;
That D defines a double literal.
You need to define basicHealthFee and healthDiscount as double. Since you've defined them as integers you have the equation: healthFee = basicHealthFee - (basicHealthFee * (healthDiscount/100)); which becomes basicHealthFee - ( basicHealthFee * (20/100)) which becomes basicHealthFee - (basicHealthFee * 0) -> basicHealthFee - 0.
The if statement taking its value from your constructor is correct.
Your problem is not related to boolean. It is due to the division of integers. Please change the program as follows.
static final double healthDiscount = 20d;
static final double basicHealthFee = 250d;
package com.stackoverflow.test;
public class Health {
boolean dependency;
String insuranceOwner = "";
static final double basicHealthFee = 250d;
static final double healthDiscount = 20d;
public Health(boolean dependent, String insurance) {
dependency = dependent;
insuranceOwner = insurance;
}
public double computeCost() {
double healthFee;
if (dependency == true) {
healthFee = basicHealthFee
- (basicHealthFee * (healthDiscount / 100.0d));
} else {
healthFee = basicHealthFee;
}
return healthFee;
}
public static void main(String args[]) {
Health h34 = new Health(true, "Jim");
System.out.println("discount price: " + h34.computeCost());
}
}

Categories

Resources