I am having trouble with my code, when I compile the code it says "cannot find symbol." - debugging

public class Percentage
{
public static void main(String args[])
{
int tenPercentOff;
int price = 100;
double price2 = 100.00;
tenPercentOff (price);
tenPercentOff (price2);
}
public static void tenpercentOff(int p)
{
double newPrice = p * .90;
System.out.println("Ten percent off");
System.out.println("New price is " + newPrice);
}
public static void tenPercentOf(double p)
{
double newPrice = p * .90;
System.out.println("Ten percent off");
System.out.println("New price is " + newPrice);
}
}

method tenPercentOff is undefined, as a side note this is really bad, you should name your methods/variables more consistently (thus avoiding this kind of problems)

Your calling method's wrong
tenPercentOff (price);
should be
tenpercentOff (price);
and
tenPercentOff (price2);
should be
tenPercentOf(price2)
And you should really work on java naming conventions another point is use a IDE,which saves you alot of time

That is because you are callind different function.
Java is case sensitive language. So tenPercentOff() and tenpercentOff() are two different function in java.

This should work for you:
public class Percentage
{
public static void main(String args[])
{
int tenPercentOff;
int price = 100;
double price2 = 100.00;
tenPercentOff (price);
tenPercentOf (price2);
}
public static void tenPercentOff(int p)
{
double newPrice = p * .90;
System.out.println("Ten percent off");
System.out.println("New price is " + newPrice);
}
public static void tenPercentOf(double p)
{
double newPrice = p * .90;
System.out.println("Ten percent off");
System.out.println("New price is " + newPrice);
}
}
Java is case sensitive So tenPercentOff and tenpercentOff is not same
Second method call was having wrong method name (tenPercentOff -> tenPercentOf)

Java is case sensitive, your method with int has a small p for percent and your method with double argument is a single f in Of

Related

How to add a number to a class name within a for loop?

I have a number of pizzas. that number is defined by the user. the for loop will run for that length of time. each time the for loop runs I want a new class for that pizza to be made. in order to do this (as far as I know) the names need to be different. I want the default name to be "pizza" and then for each reiteration of the for loop I want it to tack on a number to pizza. i.e "pizza1" "pizza2"
using System;
namespace PizzaCalculator
{
public class Pizza
{
public double size{get;set;}
public double price{get;set;}
public double squarInch;
public double pricePerInch;
public double radius;
public double radius2;
public string brand{get;set;}
public void calculate()
{
radius = (size/2);
radius2 = Math.Pow(radius, 2);
squarInch = radius2*3.14159;
pricePerInch = Math.Round((price/squarInch),2);
}
}
class Program
{
static void Main(string[] args)
{
double pizzaNum;
Console.WriteLine("How many pizza's do you want to compair?");
pizzaNum = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < pizzaNum; i++)
{
Console.Write("\nPlease enter the brand of the pizza: ");
Pizza pizza = new Pizza() {brand = Console.ReadLine()};
}
Console.ReadKey();
}
}
}
I've tried to attach [i] to the end of "pizza" but I don't really know for sure how to go about doing this.
You can use a List<Pizza>to store your pizzas.
List<Pizza> pizzas = new List<Pizza>();
for (int i = 0; i < pizzaNum; i++)
{
Console.Write("\nPlease enter the brand of the pizza: ");
Pizza pizza = new Pizza() {brand = Console.ReadLine()};
pizzas.Add(pizza);
}
To read the data, you can use a foreach loop:
foreach(Pizza pizza in pizzas)
{
Console.WriteLine(pizza.brand);
}
Or to access a specific pizza, you can use the indexer:
Console.WriteLine(pizzas[0].brand);

How would I split the contents of an array with a whitespace?

0
I have an assignment which asks for everything I have in the code below. That all works fine - I just need to calculate any monthly hours over 160 hours to be paid at 1.5 times the normal hourly rate. My math seems sound and calculates fine:
((hours - 160) * overtime) + (160 * hourlyRate)
But I dont know if I'm putting this if statement in the right method or if it even should be an if statement. My increase/decreasePay methods are working prior to this and they need to stay. I removed some things so it's easier to read.
HourlyWorker Class:
public class HourlyWorker extends Employee
{
private int hours;
private double hourlyRate;
private double monthlyPay;
private double overtime = (1.5 * hourlyRate);
public HourlyWorker(String last, String first, String ID, double rate)
{
super(last, first, ID);
hourlyRate = rate;
}
public void setHours(int hours)
{
this.hours = hours;
}
public int getHours()
{
return hours;
}
public void setHourlyRate(double rate)
{
this.hourlyRate = rate;
}
public double getHourlyRate()
{
return hourlyRate;
}
public double getMonthlyPay()
{
if (hours > 160)
{
monthlyPay = ((hours - 160) * overtime) + (160 * hourlyRate);
}
else
{
monthlyPay = hourlyRate * hours;
}
return monthlyPay;
}
public void increasePay(double percentage)
{
hourlyRate *= 1 + percentage / 100;
}
public void decreasePay(double percentage)
{
hourlyRate *= 1 - percentage / 100;
}
}
What I'm testing with:
public class TestEmployee2
{
public static void main(String[] args)
{
Employee [] staff = new Employee[3];
HourlyWorker hw1 = new HourlyWorker("Bee", "Busy", "BB1265", 10);
hw1.setHours(200);
staff[0] = hw1;
System.out.println(staff[0].getMonthlyPay());
staff[0].increasePay(10);
System.out.println(staff[0].getMonthlyPay());
}
}
Output is:
1600 (initial monthly rate, with 40 overtime hours and 160 regular hours)
1760 (10% increase to the monthlyPay)
Should be:
2006
2206.6
String.split() will do the trick.
go over the list of artists you have a split each row to artist/genre.
for (String artist : artists) {
String[] split = artist.split(" ");
// add some data validation to avoid ArrayIndexOutOfBounds
String name = split[0];
String genre = split[1];
}
You can use Files.readAllLines(myPath) to read from File.
If you are familiar with Streams from Java 8 you can use Streams on read Lines from File.
Using .stream() and collecting them in a format you want. Either as list or joining them to a single String.

Method error. Method cannot be applied to given types. Required: Double, Found: No arguments

I have an assigment that requires me to read data off a .txt containing gravity levels and then calculate your weight on each planet using methods. There seems to be an issue in the first method with type values? I canno tell. Any advice would be much appreciated.
/**
* Description for 7.04 Weight project
*
`* #author (Your Name)
* #version (The Date)
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class Weight
{
// write static methods here
// Note: formula for finding weight on a planet: Earth weight divided by Gravity constant times surface gravity
public static void getGravity(double [] gravity)throws IOException
{
File fileName = new File("gravity.txt");
Scanner inFile = new Scanner(fileName);
int i = 0;
while(inFile.hasNext())
{
gravity[i] = inFile.nextDouble();
}
}
public static void printResults(String[] name, double gravity[] ,double[] weight)
{
for (int i = 0; i <=8; i++)
{
System.out.printf(" %-7s %3.1f %7s", name[i], gravity[i] , weight[i]);
}
}
public static double[] calcWeight(double [] gravity)
{
double myWeight = 100.0;
int i = 0;
for (i = 0; i <= 8; i++)
{
gravity[i] = gravity[i] * myWeight;
}
return gravity;
}
public static void main(String[] args)throws IOException
{
// Extension idea... instead of hard codeing the weight, you may propt the user for input.
double earthWeight = 100.0; // initalize Earth weight to 100 lbs.
String[] names = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"};
double[] gravity = getGravity(); // static method you write
double[] weight = calcWeight(earthWeight, gravity); // static method you write
printResults(names, gravity, weight); // static method you write
} //end main
}//end class
Here's your problem:
calcWeight(earthWeight, gravity); //passes two parameters
public static double[] calcWeight(double [] gravity) //takes one paramter
The method call does not match the method definition.

JAVA : parse int method while using it in JTextField not working

I made a simple code to calculate BMI but it shows error in the line with the parseInt method can anyone help (a bit new to java :P)
public BmiF(){
super("BMI Calculator");
setLayout(new FlowLayout());
t1 = new JTextField("enter wieght in kg",10);
final int num1 =Integer.parseInt(t1.getText());
add(t1);
t2 = new JTextField("enter hieght in m",10);
final int num2 =Integer.parseInt(t2.getText());
add(t2);
t3 = new JTextField("",10);
t3.setEditable(false);
add(t3, BorderLayout.SOUTH);
b = new JButton("Claculate BMI");
add(b);
b.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event) {
int k = num1/(num2*num2);
t3.setText(String.format("Your BMI is %d",k));
}
}
);
}
}
You're trying to parse the String "enter weight in kg" as int. See java doc here for what your initialization means.
You need to parse the string in the ActionListener and add a catch exception rule.
I've gotten the bellow code to work. Another problem you have is that you need to declare the int or double in the try block of code without the final qualifier, so that you can change the variable after initialization
frame.setLayout(new FlowLayout());
textArea.setEditable(true);
textArea.setPreferredSize(new Dimension(50, 15));
button = new JButton("ok");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
String string = textArea.getText().trim();
int weight = Integer.parseInt(string);
//do stuff with weight variable
System.out.println(weight);
} catch(Exception e1) {
System.out.println("number exception");
}
}
});
frame.add(textField);
frame.add(textArea);
frame.add(button);
frame.setSize(300, 100);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

I am having a lot of trouble finding the right way to sort by price

I'm pretty sure that I have to use Collections, but I'm honestly super lost on how to implement it! My assignment needs me to
"Allow the user to view the plants sorted by price (lowest to highest), scientific name (alphabetized by genus), or common name (alphabetized by first letter of first word)."
this is my code, I don't know where to exactly put the sorting and how to write it in code :(
package plant.nursery.program;
import java.util.Scanner;
import java.util.ArrayList;
public class PlantNurseryProgram {
private double maxHeightInFt;
private String commonName;
private String scientificName;
private double price;
boolean isFragile;
public PlantNurseryProgram(String commonName,
String scientificName, double maxHeightInFt, double price,
boolean isFragile) {
this.maxHeightInFt = maxHeightInFt;
this.commonName = commonName;
this.scientificName = scientificName;
this.price = price;
this.isFragile = isFragile;
}
#Override
public String toString() {
return commonName + " (" + scientificName + ") " + "is " +
maxHeightInFt + " ft tall " + "it costs $" + price + " and "
+ "isFragile = " + isFragile;
}
public String setName(String newName){
commonName = newName;
return newName;
}
public String setSName(String newSName)
{
scientificName = newSName;
return scientificName;
}
public double setHeight(double newHeight){
maxHeightInFt = newHeight;
return maxHeightInFt;
}
public double setPrice(double newPrice){
price = newPrice;
return price;
}
public boolean setFragile(boolean newFragile){
isFragile = newFragile;
return isFragile;
}
public static void main(String[] args) {
Scanner plant = new Scanner(System.in);
boolean toContinue = true;
ArrayList<PlantNurseryProgram> plantNurseryAL = new ArrayList<>();
do
{
System.out.println("What's the name of your plant");
String commonName = plant.next();
System.out.println("What's the scientific name for your plant?");
String scientificName = plant.next();
System.out.println("How tall is your plant?");
double maxHeightInFt = plant.nextDouble();
System.out.println("What's the price of your plant?");
double price = plant.nextDouble();
System.out.println("Is the plant fragile? If yes type(true), if no "
+ "type (false)");
boolean isFragile = plant.nextBoolean();
System.out.println("Do you wish to continue?");
toContinue = plant.nextBoolean();
PlantNurseryProgram userPlant = new PlantNurseryProgram(
commonName, scientificName, maxHeightInFt, price, isFragile);
plantNurseryAL.add(userPlant);
System.out.println("Is all the information you entered correct?");
boolean corrections = plant.nextBoolean();
if(corrections == false)
{
System.out.println("What would you like to correct?"
+ " 1. Name, 2. Scientific name, 3. Height, 4. Price"
+ "5. Fragility?" );
int userChoice = plant.nextInt();
if(userChoice == 1)
{
System.out.println("Please enter the correct name");
String newName = plant.next();
userPlant.setName(newName);
System.out.println(userPlant);
}
else if(userChoice == 2)
{
System.out.println("Please enter the correct scientific name");
String newSName = plant.next();
userPlant.setSName(newSName);
System.out.println(userPlant);
}
else if(userChoice == 3)
{
System.out.println("Please enter the correct height");
double newHeight = plant.nextDouble();
userPlant.setHeight(newHeight);
System.out.println(userPlant);
}
else if(userChoice == 4)
{
System.out.println("Please enter the correct price");
double newPrice = plant.nextDouble();
userPlant.setPrice(newPrice);
System.out.println(userPlant);
}
else if(userChoice == 5)
{
System.out.println("Please enter if the plant is fragile or not");
boolean newFragile = plant.nextBoolean();
userPlant.setFragile(newFragile);
System.out.println(userPlant);
}
}
} while(toContinue == true);
for (PlantNurseryProgram plantNurseryProgram : plantNurseryAL) {
System.out.println(plantNurseryProgram);
} // end of for loop
} //end of main
} // end of class
You're posting too much here. To figure out what to do, you don't need a main method or a user interface. By the way, conventionally, setters are void methods.
You should become familiar with the available methods for collections in the java.util package. Or you can use the index and look up sort. You will see that the Collections class has two sort methods. One is for the case when the class is inherently Comparable:
public class TemperatureGauge implements Comparable<TemperatureGauge> {...}
The other is when a class may be sorted many different ways, so that there is no natural way to define a standard comparison. Then, you create a Comparator.
public class CommonNameComparator implements Comparator<PlantNurseryProgram> {
public int compare(PlantNurseryProgram left, PlantNurseryProgram right) {
// Do something with left.getCommonName() and right.getCommonName().
// It must return a negative, zero, or positive depending on whether
// left should come before, in the same place, or after right.
return /*anInteger*/;
}
}
Repeat the process for the scientific name and the price.
For extra credit, write JUnit tests for each comparator and for the sorting process.
You can use set interface of collection class.Before that first you should override the equals and hashcode method in your code with the field according to which you want to short.
After this you can create object of PlantNurseryProgram and this in one of the subclass of set interface.As per your requirement you can use Treeset class.
Reemember there are several other ways to ddo this.Using set you can not duplicate item.
If your purpose is to sort after inserting the data in data structure the use sort method provided in java collection api.
See the below link.
http://www.roseindia.net/java/jdk6/set-interface.shtml

Resources