Calculator tip why is it not compiling [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
import java.util.Scanner;
public class Hw4Part4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Ask for the diners’ satisfaction level using these ratings: 1 = Totally
// satisfied, 2 = Satisfied,
// 3 = Dissatisfied.
System.out.println("Satisfacion leve: ");
int satisfactionNumber = sc.nextInt();
// Ask for the bill subtotal (not including the tip)
System.out.println("What is the bill subtotal: ");
double subtotal = sc.nextInt();
// Report the satisfaction level and bill total.
System.out.println("The satisfaction level is: " +
satisfactionLevel(satisfactionNumber));
System.out.println("The bill total is: " +
getBillTotal(tipPercentage, subtotal));
}
public static String satisfactionLevel(int satisfactionNumber) {
String satisfactionL = "";
if (satisfactionNumber == 1) {
satisfactionL = "Totally-satisfied";
}
if (satisfactionNumber == 2) {
satisfactionL = "Satisfied";
}
if (satisfactionNumber == 3) {
satisfactionL = "Dissatisfied";
}
return satisfactionL;
}
// This method takes the satisfaction number and returns the percentage of tip
// to be
// calculated based on the number.
// This method will return a value of 0.20, 0.15, or 0.10
public static double getPercentage(int satisfactionNumber) {
double getPercentage = 0;
if (satisfactionNumber == 1) {
getPercentage = 0.20;
}
if (satisfactionNumber == 2) {
getPercentage = 0.15;
}
if (satisfactionNumber == 3) {
getPercentage = 0.10;
}
return getPercentage;
}
public static double getBillTotal(double tipPercentage, double subtotal) {
double totalWithTip =
(subtotal + (getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
}
Error where it says getPercentage(satisfactionNumber)*subtotal..... says SatisfactionNumber cannot be resolved to a variable
And in the Main method there is a error on
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal)); I believe it is the related to the last error.

In getBillTotal, satisfactionNumber is undefined, it has meaning within the context of the method. In order to use it, you would need to define the variable within the context of the method either as a parameter or as a local variable...
In your main method, You have the same problem with tipPercentage, it's undefined...

Your close. You will need to pass in satisfactionNumber into getBillTotal by adding another parameter. Otherwise it don't know what you are taking about when you say satisfactionNumber. It can't directly see the variables in other functions.
public static double getBillTotal(double tipPercentage, double subtotal, int satisfactionNumber) {
double totalWithTip = (subtotal + (getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
Then in your main method call pass it in.
public static void main(String[] args) {
....
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal, satisfactionNumber));
}
And actually you don't need tipPercentage, in fact it's not even defined in main. Since it can be found by satisfactionNumber you could do this.
public static void main(String[] args) {
....
System.out.println("The bill total is: " + getBillTotal(subtotal, satisfactionNumber));
}
...
public static double getBillTotal(double subtotal, int satisfactionNumber) {
double totalWithTip = (subtotal + (getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
OR you could pass in the tipPercentage by calculating it first.
public static void main(String[] args) {
....
double tipPercentage = getPercentage(satisfactionNumber);
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal));
}
...
public static double getBillTotal(double tipPercentage, double subtotal) {
double totalWithTip = (subtotal + (tipPercentage * subtotal));
return totalWithTip;
}
Any of these last two would be okay.

Related

How do I call these methods? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
I'm new to Java, and I'm trying to call the private methods I've set up earlier, but with no success. It's a simple program that generates random numbers and display messages. Anyone wants to lend a hand?
Sorry if the code is bad, I've only been learning this for less than month.
import java.util.Random;
import java.util.Scanner;
public class project2 {
private static int rollDie() {
int num_random2 = (int) (Math.random() * 6) + 1;
System.out.println("Die 2: " + num_random2);
return num_random2;
}
private static int rollDie2() {
int num_random = (int) (Math.random() * 6) + 1;
System.out.println("Die 1: " + num_random);
return num_random;
}
private static void printDice(int num_random, int num_random2) {
total = num_random + num_random2;
System.out.println("Total: " + total);
}
int total = num_random + num_random2;
private static void printSpecialMessage(int total) {
String message1 = "Snake Eyes";
String message2 = "Box cars";
if (total = 12) {
System.out.println(message2);
} else if (total = 2) {
System.out.println(message1);
} else {
break;
}
}
public static void main(String[] args) {
System.out.println("Welcome to my app!");
System.out.println();
System.out.println("Dice Roller");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
do {
rollDie();
rollDie2();
printDice();
printSpecialMessage();
System.out.print("Roll Again? (y/n): ");
choice = sc.next();
System.out.println();
}
while (choice.equalsIgnoreCase("y"));
}
}
I keep getting these errors:
The method printDice(int, int) in the type project2 is not applicable for the arguments ()
The method printSpecialMessage(int) in the type project2 is not applicable for the arguments ()
at project2.main(project2.java:51)
At this point I'm about to just give up. Hopefully someone can help me out!
Few errors in your code I found.
if (total = 12) should be replaced with if (total == 12).
Make sure you always use two equals in if condition. One = is for assignment and two = for condition check.
printDice() -> The signature is not matching. Pass two values to this function.
total should be declared as static.
printSpecialMessage -> The signature is not matching. Pass one values to this function.
I suggest you start with writing simple code and then gradually go ahead with writing complex codes.
Your code does not compile. The following code does. Compare it with your code.
import java.util.Scanner;
public class Project2 {
private static int rollDie() {
int num_random2 = (int) (Math.random() * 6) + 1;
System.out.println("Die 2: " + num_random2);
return num_random2;
}
private static int rollDie2() {
int num_random = (int) (Math.random() * 6) + 1;
System.out.println("Die 1: " + num_random);
return num_random;
}
private static void printDice(int num_random, int num_random2) {
int total = num_random + num_random2;
total = num_random + num_random2;
System.out.println("Total: " + total);
}
private static void printSpecialMessage(int total) {
String message1 = "Snake Eyes";
String message2 = "Box cars";
if (total == 12) {
System.out.println(message2);
}
else if (total == 2) {
System.out.println(message1);
}
}
public static void main(String[] args) {
System.out.println("Welcome to my app!");
System.out.println();
System.out.println("Dice Roller");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
do {
int one = rollDie();
int two = rollDie2();
printDice(one, two);
printSpecialMessage(one + two);
System.out.print("Roll Again? (y/n): ");
choice = sc.next();
System.out.println();
} while (choice.equalsIgnoreCase("y"));
}
}
The things I changed (in no particular order).
Method printSpecialMessage requires an argument. You call that method from method main without an argument. Hence the following [compiler] error.
The method printSpecialMessage(int) in the type Project2 is not applicable for the arguments ()
Similarly for method printDice. That method requires two arguments but you call it with no arguments, which gives the following [compiler] error.
The method printDice(int, int) in the type Project2 is not applicable for the arguments ()
You need to save the value returned from method rollDie in a variable. You also need to save the value returned from method rollDie2 in another variable. Then you call method printDice with those two variables as arguments. In the code above I named the variables one and two.
break is not used in if statements. See method printSpecialMessage.
When comparing integers, use == (double equals sign). Again see method printSpecialMessage.
The following line of code is not inside the body of a method. It belongs in method printDice.
int total = num_random + num_random2;
Here is a sample run of the above code.
Welcome to my app!
Dice Roller
Die 2: 5
Die 1: 3
Total: 8
Roll Again? (y/n): y
Die 2: 6
Die 1: 3
Total: 9
Roll Again? (y/n): n

It didn't show any error, but the compiler just keep loading or show [object object] [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I was tring to make a leagth converter which can convert foot to other units which are micrometer, millimeter......
when I try to run it, it just keep loading and sometimes will show [Object Object]....(I dont know wheather [Object Object] is an error
import java.util.Scanner;
public class Converter{
public static void calculateMicro(double number){
double answer = 304796.293632 * number;
System.out.print ("The answer is: " + answer );
}
public static void calculateMilli(double number){
double answer = 304.8 * number;
System.out.print ("The answer is: " + answer );
}
public static void calculateCenti(double number){
double answer = 30.48 * number;
System.out.print ("The answer is: " + answer );
}
public static void calculateMeter(double number){
double answer = 0.3048 * number;
System.out.print ("The answer is: " + answer );
}
public static void calculateKilo(double number){
double answer = 0.0003048 * number;
System.out.print ("The answer is: " + answer );
}
public static void main (String args[]) {
Scanner sc = new Scanner(System.in);
double number = sc.nextDouble();
int x = 1;
int option = sc.nextInt();
while(x==1){
System.out.println("1.micrometer 2.millimeter 3.centimeter 4.meter 5. kilometer");
if(option==1){
calculateMicro(number);
}
else if(option==2){
calculateMilli(number);
}
else if(option==3){
calculateCenti(number);
}
else if(option==4){
calculateMeter(number);
}
else if(option==5){
calculateKilo(number);
}
}
You are made an infinit loop by
int x = 1;
while(x==1){
//code...
}
You should
Ask the user for the option
Ask the user if he want try another time (change the x to 0 or 1 )
while(x==1){
System.out.println("1.micrometer 2.millimeter 3.centimeter 4.meter 5. kilometer");
x = sc.nextInt();
//code to convert....
System.out.println("do you wanna try again 1 for Yes or 0 for No");
x = sc.nextInt();
}
and i think if you have multiple choice you should try Switch not if else if else ....
switch(option) {
case 1:
calculateMicro(number);
break;
case 2:
calculateMilli(number);
break;
//cases
// default:
}

Variables arent updating accordingly [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
When I attempt to take in the users input and update the "Dexterity" variable, it only reflects in the following few lines of code. When I attempt to run the same command again, it doesn't reflect the previous input. For some reason It is not updating the variable accordingly.
public class SetAttributes {
public String userInput;
double Dexterity;
double Strength;
double Intelligence;
double Stamina;
double SkillPoints = 50;
public SetAttributes() {
this.SetDex(0);
this.SetStr(0);
this.SetInt(0);
this.SetSta(0);
this.SetSkillPoints(50);
}
public double GetSP(){
return SkillPoints;
}
public double GetDex() {
return Dexterity;
}
public void SetDex(double dexterity) {
this.Dexterity = dexterity;
}
public double GetStr(){
return Strength;
}
public double GetInt(){
return Intelligence;
}
public double GetSta(){
return Stamina;
}
public void SetStr(double strength){
this.Strength = strength;
}
public void SetInt(double intelligence){
this.Intelligence = intelligence;
}
public void SetSta(double stamina){
this.Stamina = stamina;
}
public void SetSkillPoints(double skillPoints) {this.SkillPoints = skillPoints;};
}
import java.util.Scanner;
public final class PointSpender {
public static void Spend() {
SetAttributes A = new SetAttributes();
System.out.println("Your current stats are ");
System.out.println("Strength " + A.Strength);
System.out.println("Stamina " + A.Stamina);
System.out.println("Intelligence " + A.Intelligence);
System.out.println("Dexterity " + A.Dexterity);
System.out.println("Please select the attribute you want to increase. You have " + A.SkillPoints + " available.");
Scanner Input = new Scanner(System.in);
A.userInput = Input.nextLine().toLowerCase();
if(A.userInput.charAt(0) == 'd'){
System.out.println("Dexterity");
System.out.println("Your Dexterity is " + A.Dexterity);
System.out.println("How many points in Dexterity?");
double Amount = Double.parseDouble(Input.nextLine());
A.SetDex(A.GetDex() + Amount);
// A.setDex(A.Dexterity + Amount);
System.out.println("You have put " + Amount + " into Dexterity" );
System.out.println("Your new dexterity is " + A.Dexterity);
}
}
}
Type "+" to spend your available skillpoints.
Type "Logout" to Log Out.
+
Your current stats are
Strength 0.0
Stamina 0.0
Intelligence 0.0
Dexterity 0.0
Please select the attribute you want to increase. You have 50.0 available.
d
Dexterity
Your Dexterity is 0.0
How many points in Dexterity?
45
You have put 45.0 into Dexterity
Your new dexterity is 45.0
+
Your current stats are
Strength 0.0
Stamina 0.0
Intelligence 0.0
Dexterity 0.0
Every time you invoke the static method "spend" you are creating a new instance of SetAttributes then you are blocking for user input. But before the block when the new instance is created all attributes of the new instance are set to 0.
This happens in your zero argument constructor, right here :
public SetAttributes() {
this.SetDex(0);
this.SetStr(0);
this.SetInt(0);
this.SetSta(0);
this.SetSkillPoints(50);
}

Receiving Infinity Value

I'm trying to make a unit conversion program but I keep receiving value as infinity. I'm not sure where I need to fix since it's not giving me errors. I only tested oz to ml to make sure I'm doing it correctly but I'm receiving infinity as the answer.
UnitConverter.java:
public class UnitConverter {
final double oz_TO_ml = 29.5735;
final double gal_TO_g = 3.78541;
final double lb_TO_kg = 0.453592;
final double inc_TO_mm = 25.4;//Inc is inches
final double ft_TO_cm = 30.48;
final double mi_TO_km = 1.60934;
double factor;
public UnitConverter(String unit) {
if (unit.equals("oz")) {
factor = oz_TO_ml;
} else if (unit.equals("gal")) {
factor = gal_TO_g;
} else if (unit.equals("lb")) {
factor = lb_TO_kg;
}
}
public double toOz(double amount) {
return (amount * factor);
}
public double fromOz(double amount) {
return (amount / factor);
}
public double toMl(double amount) {
return (amount * factor);
}
public double fromMl(double amount) {
return (amount / factor);
}
}
Calculator.java:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Convert from: ");
String fromUnit = in.nextLine();
System.out.print("Convert to: ");
String toUnit = in.nextLine();
UnitConverter from = new UnitConverter(fromUnit);
UnitConverter to = new UnitConverter(toUnit);
System.out.print("Value ");
double val = in.nextDouble();
double oz = from.toOz(val);
double converted = to.fromOz(oz);
System.out.println(val + " " + fromUnit + " = " + converted + " " + toUnit);
}
}
Sample input:
Convert from: oz
Convert to: ml
Value 12
Output:
12.0 oz = Infinity ml
Initialize the factor varible with one. A java with default give 0 to primitive double,
class UnitConvertor {
final double oz_TO_ml = 29.5735;
final double gal_TO_g = 3.78541;
final double lb_TO_kg = 0.453592;
final double inc_TO_mm = 25.4;//Inc is inches
final double ft_TO_cm = 30.48;
final double mi_TO_km = 1.60934;
double factor=1;//initialize with 1
But I am still not sure that what is the check you are using if the user input is 'ml'.
public UnitConverter(String unit)
{
if (unit.equals("oz"))
{
factor = oz_TO_ml;
} else if (unit.equals("gal"))
{
factor = gal_TO_g;
} else if (unit.equals("lb"))
{ factor = lb_TO_kg;
}
}
If you pass "ml" the factor will be zero
Your design currently needs two of these but you really only need one as "oz" has everything it needs to do the conversion.
Ignore the the toUnit in your line input code and just use fromUnit
Edit : I'll show you an alternative way to do things, it just supports one convert to show the rough design. Note the method calls are now static because you will only ever need one instance of them
UnitConverter.java
public class UnitConverter
{
private static final double oz_TO_ml = 29.5735;
public static double convert(String fromType, String toType,double amount) throws IllegalArgumentException
{
if (fromType.equals("oz") && toType.equals("ml"))
{
return (amount * oz_TO_ml);
}
else
{
throw new IllegalArgumentException("The combination of converting " + fromType + " to " + toType + " is not supported");
}
}
}
Calculator.java:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Convert from: ");
String fromUnit = in.nextLine();
System.out.print("Convert to: ");
String toUnit = in.nextLine();
System.out.print("Value ");
double val = in.nextDouble();
System.out.println(val + " " + fromUnit + " = " + UnitConverter.convert(fromUnit,toUnit,val) + " " + toUnit);
}
}
Your UnitConverter class constructor only knows about 3 units: oz, gal, and lb. If you instantiate it with one of those, it will correctly assign the factor and be able to convert units, as seen below:
public UnitConverter(String unit) {
if (unit.equals("oz")) {
factor = oz_TO_ml;
} else if (unit.equals("gal")) {
factor = gal_TO_g;
} else if (unit.equals("lb")) {
factor = lb_TO_kg;
}
}
However, in your Calculator class, you have this line:
UnitConverter from = new UnitConverter(fromUnit);
UnitConverter to = new UnitConverter(toUnit);
If you run your program with your sample input, from is oz and to is ml. But if you instantiate UnitConverter with the unit ml, what does factor get set to? According to your constructor, it is never set, and so it retains its default value of 0.0.
Later, you call this line:
double converted = to.fromOz(oz);
This runs the fromOz method
public double fromOz(double amount) {
return (amount / factor);
}
Which divides by the factor, which is 0.0. This is the source of your Infinity output.
As the other answer says, you don't need to have two UnitConverter objects to perform this calculation. The factor is correct to convert between ounces and millilitres, so this Calculator code is sufficient.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Convert from: ");
String fromUnit = in.nextLine();
UnitConverter from = new UnitConverter(fromUnit);
System.out.print("Value ");
double val = in.nextDouble();
double result = from.toMl(val);
System.out.println(val + " " + fromUnit + " = " + result + " ml.");
}
}
If you wanted to keep your current calculator code, you would need to add a condition in your UnitConverter constructor for a scalefactor for ml (1.0). However, I think this approach is flawed because what happens, for example, when you try to convert between oz and inches? The conversion makes no sense but your architecture would not prevent it.

(JAVA) I need help creating a class with getters and setters, creating a class with an array and then calling upon the other class. [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
This is my objective--
you have to create 2 classes:
1. Student class
Attributes
Create a Student class with 3 attributes(instance variables), including
◦ name (String)
◦ midterm (double)
◦ finalExam (double)
Methods
Define setters/getters for each attributes. Therefore, you have to create 3 setters and 3 getters in total.
In the setters of midterm and finalExam, you have to check whether the given grade is valid. The grade has to be between 0-100. If it is invalid, print out an error message “The grade is invalid!”
Define a method, getFinalGrade, which calculates the final grade according to the following grading scheme. After the computation, return the result of final grade.
◦ Grading:
▪ Midterm: 40%
▪ Final exam: 60%
Define a method, showGrades, which outputs the details of attributes. The grades should be displayed as a number with two decimal places only. (See the example)
◦ Output example: “Name: Tom, Midterm: 90.00, Final Exam: 80.00, Final Grade: 82.00”
GradeCalculator class
Create a GradeCalculator class and put everything (Step 1 to Step 4) in the main method.
Step 1: create a Student array, called studentArray, whose length is 5.
Step 2: create 5 Student objects by using loop. Ask the user to input name, midterm, final exam one at a time (prompt the user) and store these in corresponding attributes by calling the appropriate setters. After all values are set, store the newly-created Student object to studentArray.
Step 3: loop studentArray to print out the details of each student by calling showGrades.
Step 4: calculate the average final grade of these 5 student and print it out on the screen. The grades should be displayed as a number with two decimal places only.
Here is the code I have written thus far:
public class Student {
private String name;
private double midterm;
private double finalExam;
private double finalGrade;
public Student(String n, double a, double m)
{
name = n;
midterm = a;
finalExam = m;
}
public String getName()
{
return (name);
}
public double getmidterm()
{
return (midterm);
}
if (midterm < 0)
{
midterm = 0;
System.out.println("The grade is invalid! Grade will be entered as 0.");
}
if (midterm >100)
{
midterm = 100;
System.out.println("The grade is invalid! Grade will be entered as 100.");
}
else
{
System.out.println("Midterm grade recorded." + midterm);
}
public double getfinalExam()
{
return (finalExam);
}
if (finalExam < 0)
{
finalExam = 0;
System.out.println("The grade is invalid");
}
if (finalExam > 100)
{
finalExam = 100;}
System.out.println("The grade is invalid! Grade will be entered as 100.");
}
else
{
System.out.println("Final Exam grade recorded." + finalExam);
}
public double getfinalGrade()
{
finalGrade = (midterm * .40) + (finalExam * .60);
return (finalGrade);
}
public double showGrades()
{
System.out.println("Name:" + name + "midterm:" + midterm + "Final Exam:" + finalExam);
}
public void setName(String studentName)
{
name = studentName;
}
public void setMidterm(double midtermGrade)
{
midtermGrade = midterm;
}
public void setFinal(double finalGrade)
{
finalGrade = finalExam;
}
Code:
public class GradeStudents{
Student[] students;
import java.util.Scanner;
GradeStudents(){}
public static void main(String[] args) {
String[] studentarr = new String[5];
for(double i = 0; i < 5; i++);
{ //insert what the for loop executes here}
}
}
}
Does this meet your question?
public static void main(String[] args) {
Student[] studentarr = new Student[5];
for(double i = 0; i < 5; i++);
{
studentarr[i] = new Student(params...);
}
studentarr[0].someStudentMethod();
}
Best way to go is i think is to populate some arrays with data and run the code to see if you get output or errors.
Where does the student data come from? Through userinterface input or from a text,xml or json file?
It looks like you have an If statement outside a method therefore potentially the program will throw back errors / exceptions at you.
Just a snippet of this code
public double getmidterm()
{
return (midterm);
}
// Potentially an error here
if (midterm < 0)
{
midterm = 0;
System.out.println("The grade is invalid! Grade will be entered as 0.");
}
You might want to put these if statements in a method and call this method in your test class (main method).
Also, You are defining get and set methods however they are not returning values (in this case):
public double showGrades()
{
System.out.println("Name:" + name + "midterm:" + midterm + "Final Exam:" + finalExam);
}
Here you should be returning a double not a println to the console.
If you have a toString method which gives back the student, you should be able in your loop to call student.toString() and it will display the values you want.

Categories