Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
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.
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.
Improve this question
I needed to rewrite a java program I had already completed to now include a class I would be able to test with using JUnit4. Unfortunately I can't even get to that point because I'm receiving an error. It's a really simple program where I ask the user for 3 numbers, pass those values into a function that does some calculations and should return a print statement with the value back. I made it work without the function and I'm having trouble with the syntax and fully understanding what I can and can't do with methods.
Here it is:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
System.out.println("Given ax^2 + bx^2 + c = 0");
System.out.println("Please enter 'a', 'b', and 'c' to determine if there are any roots: ");
float numA = kybd.nextFloat();
float numB = kybd.nextFloat();
float numC = kybd.nextFloat();
quadraticAnswer(numA, numB, numC);
}
public static void float quadraticAnswer (float numA, float numB, float numC){
float discriminant = ((numB*numB)-(4*numA*numC));
if (discriminant < 0){
System.out.println("The Equation has no roots!");
}
else if (discriminant ==0) {
float root = (-numB + Math.sqrt(discriminant))/(2*numA);
System.out.println("The Equation has one root: "+ root);
}
else {
float root1 = (-numB + Math.sqrt(discriminant))/(2*numA);
float root2 = (-numB - Math.sqrt(discriminant))/(2*numA);
System.out.println("The Equation has two roots: " + root1 + " and " + root2 + ".");
}
}
}
Change the invalid syntax of
public static void float quadraticAnswer
to
public static void quadraticAnswer
as you are not returning anything.
If you use an IDE like Eclipse it will quickly highlight such errors
Related
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 12 months ago.
Improve this question
New Java programmer. I have no idea of what's causing this error.
Everything compiled fine until I added the if statements.
Still learning how to debug.
import javax.swing.*;
public class VelocityTest2 {
public static void main(String[] args) {
//Chapter3 example
//
int time2, time1;
double distance1, distance2, velocity;
double velocityValue = 60.0;
String input= JOptionPane.showInputDialog("Enter time 2");
time2= Integer.parseInt(input); // Enter 4 (hrs)
input= JOptionPane.showInputDialog("Enter time 1");
time1= Integer.parseInt(input);
input= JOptionPane.showInputDialog("Enter distance 2");
distance2 = Integer.parseInt(input);
input= JOptionPane.showInputDialog("Enter distance 1");
distance1 = Integer.parseInt(input);
velocity = (distance2 - distance1)/(time2 - time1);
System.out.println();
System.out.println("the velocity is " + velocity);
if (velocity > velocityValue) {
System.out.println("the velocity is greater than 60");
}
else {
System.out.println("the velocity is less than 60");
}
}
}
}
If you formatted your code properly using an IDE, you would have noticed that you have an extra closing brace } at the end.
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 1 year ago.
Improve this question
I'm very new to programming and I've been teaching myself for almost a month now, can someone please explain to methe reason behind error in my code? It errors in the "total(moneyConv(moneySum * moneyRate));" line,
saying actual and formal argument differs in length. I've check all my parameters and it seemed fine to me. thanks a lot!
public class NewClass {
static Scanner sc = new Scanner(System.in);
public static float moneySum;
public static float moneyRate;
public static void findSum(float sum) {
moneySum = sum;
}
public static void findRate(float rate) {
moneyRate = rate;
}
public static float moneyConv(float sum, float rate) {
return sum * rate;
}
public static void total(float total) {
System.out.println(total + "Here is the total of your transaction.");
}
public static void main(String[] args) {
System.out.print("Input amount of money : ");
findSum(sc.nextFloat());
System.out.print("Input exchange rate : ");
findRate(sc.nextFloat());
total(moneyConv(moneySum * moneyRate));
}
the moneyConv() method parameters have 2 arguments: a float datatype sum and another float datatype rate. When you look at the method call:
total(moneyConv(moneySum * moneyRate));
you are actually trying to call the method moneyConv(float sum, float rate) but with one argument instead with a float datatype, as a result of the multiplication of moneySum and moneyRate. This is not valid since moneyConv accepts 2 arguments.
So, the fix would be total(moneyConv(moneySum, moneyRate));
First the nested method moneyConv(moneySum,moneyRate) will be executed and after the method total will be executed with the result of the moneyConv method.
Method parameters must be separated by commas:
total(moneyConv(moneySum, moneyRate));
moneySum * moneyRate is first evaluated and becomes a single value which is passed to moneyConv which actually requires two arguments.
It is equivalent to:
float temporary = moneySum * moneyRate;
total(moneyConv(temporary))
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I'm new to java, i do study from udemy.
My question is...at the end of learning java i will find out there are n better ways to do the same thing ? (i just want to accelerate the process of learning)
There is my code if some one can give me an example of a better way so i can understand. Thank you !!
public static void main(String[] args) {
toMillesPerHour(50);
toMillesPerHour(90);
toMillesPerHour(100);
toMillesPerHour(130);
toMillesPerHour(-20);
}
public static void toMillesPerHour(double kilomettersPerHour) {
//return round value
if(kilomettersPerHour >= 0) {
kilomettersPerHour = (int) kilomettersPerHour / 1.60934;
int roundKm = (int) kilomettersPerHour;
System.out.println("You travel with speed of: " + roundKm +" Miles");
}else {
System.out.println("Negative value detected");
}
}
You travel with speed of: 31 Miles
You travel with speed of: 55 Miles
You travel with speed of: 62 Miles
You travel with speed of: 80 Miles
Negative value detected
I assume a typical Java developer with some experience would do these things:
change the return type to double (int if you need to round the result);
throw an exception when kilomettersPerHour < 0;
print the results in the main.
For example,
public static double toMillesPerHour(double kilomettersPerHour) {
if (kilomettersPerHour < 0) {
throw new IllegalArgumentException("Negative value detected");
}
return kilomettersPerHour / 1.60934;
}
You could make the change steven35 suggest, but also in your toMilesPerHour method you shouldn't use the parameter variable to store the result of divison. Instead of that you should do something like:
int milesPerHour = (int)kilometersPerHour / 1.60934
This way you don't need to make any additional variables to round your result. Also it's bad practice to modify parameter variables.
You could just define the values in an array and iterate over them. Then every time you add a new value, you don't have to call toMillesPerHour() again.
double[] values = { 50.0, 90.0, 100.0, 130.0, -20.0 };
for (double value : values) {
toMillesPerHour(value);
}
You can use Math.round() for more accurate result.
public static void main(String[] args) {
toMillesPerHour(50);
toMillesPerHour(90);
toMillesPerHour(100);
toMillesPerHour(130);
toMillesPerHour(-20);
}
public static void toMillesPerHour(double kilomettersPerHour) {
//return round value
if(kilomettersPerHour >= 0) {
kilomettersPerHour = kilomettersPerHour / 1.60934;
int roundKm = (int) Math.round( kilomettersPerHour );
System.out.println("You travel with speed of: " + roundKm +" Miles");
}else {
System.out.println("Negative value detected");
}
}
My single biggest issue with this code is that the name toMilesPerHour(50); only tells half the story. 50 what? Don't make me look inside to figure that out.
Not convinced? Ok now I need a method that converts feet per second to miles per hour. What am I supposed to name it that won't cause confusion?
If your method was hanging off a type named KilometersPerHour this name would be fine but as is this name makes the abstraction fail. I have to look inside to know what it means.
You could use varargs. - It allows you to remove alot of code.
You do not need double.
Using parameters as local variables is not so good approach.
Have a look at:
class Printer {
public static void main(String[] args) {
toMillesPerHour(50, 90, 100, 130, -20);
}
public static void toMillesPerHour(int... kilomettersPerHour) {
Arrays.stream(kilomettersPerHour).forEach(Printer::printRound);
//return round value
}
private static void printRound(int kmPerHour) {
String message = (kmPerHour >= 0) ? calculate(kmPerHour) : "Negative value detected";
System.out.println(message);
}
private static String calculate(int kmPerHour) {
int roundKm = (int) (kmPerHour / 1.60934);
return "You travel with speed of: " + roundKm + " Miles";
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
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.
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.
Improve this question
I am creating a simple program to calculate the cost of running a car. The program works just fine but I wanted to see if I could get the final answer to 2 decimal places. I tried using the '%8.2f' thing but it said that no method could be found for println(string, double)
This is my code:
/* Program to calculate the running cost of car */
import java.util.Scanner;
public class RunningCosts {
public static void main(String[] args) {
final int TOTAL_DISTANCE = 100000;
Scanner in = new Scanner(System.in);
System.out.print("Enter the car cost: ");
double carCost = in.nextDouble();
System.out.print("Enter the service cost: ");
double serviceCost = in.nextDouble();
System.out.print("Enter the service interval: ");
double serviceInterval = in.nextDouble();
System.out.print("Enter km per litre: ");
double kmPerLitre = in.nextDouble();
System.out.print("Enter the fuel cost per litre: ");
double fuelCostPerLitre = in.nextDouble();
double serviceTotal = (TOTAL_DISTANCE/serviceInterval) * serviceCost;
System.out.println( "Service Total: " + serviceTotal); //Here
double fuelCost = (TOTAL_DISTANCE/kmPerLitre) * fuelCostPerLitre;
System.out.println( "Fuel Cost: " + fuelCost); //Here
double totalCost = carCost + fuelCost + serviceTotal;
System.out.println( "Estimated Cost: " + totalCost); //And here
}
}
The commented lines are what I would like to be formatted to 2 decimal places
Either use printf as #shmosel suggested, or use String.format:
System.out.println( "Service Total: " + String.format("%.2f", serviceTotal));
See this page for more usage examples.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
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.
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.
Improve this question
getting an error here on the second else if.... I don't understand how it's happening whatsoever as the rest of them have no errors and are stated the same way! Would appreciate any input on this.
The error states;
error: illegal start of expression
Here is the code;
/**
* #(#)Exercise4.java
*
*
* #author
* #version 1.00 2014/10/20
*/
import java.util.Scanner;
public class Exercise4 {
public static void main(String[] args) {
float unit, cost;
Scanner input = new Scanner(System.in);
System.out.print("Please Enter The Units Used: ");
unit = input.nextFloat();
if (unit <= 99)
{
cost = (unit*0.05);
}
else if (unit > 99 && unit <= 200)
{
cost = ((99*0.05) + (unit*(0.03)));
}
else if (unit > 200 && <= 300)
{
cost = (((99*0.05) + (200*0.03)) + (unit*0.02));
}
else if (unit>300)
{
cost = ((((99*0.05) + (200*0.03)) + (100*0.02)) + (unit*0.01));
}
System.out.println("\nThe Cost Of Your Mobile Phone Bill Is: EUR" + String.format("%.2f",cost));
}
}
This
else if (unit > 200 && <= 300)
should be
else if (unit > 200 && unit <= 300)
You missed unit in the test. Also, you should make cost a double if you will multiply by a double.
float unit;
double cost;
A few changes are required here:
Correct 3rd if condition.
Change float type to double (Showing loss of precision error).
Initialize cost = 0;
and then it works...