I am fairly new to Java and taking a course but cannot figure out this small syntax error that I keep on getting. I have been researching and staring at the problem for a while now and just cannot figure it out. I am not asking for someone to complete the project just need help with this 1 error. Sorry if I am not posting in the right section. Below is the code....
import java.util.*;
public class SolveEqu {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
double arr[]=new double[3]; //passing array as parameter
System.out.println("Enter the three coefficients of the equation separated by spaces");
for(int i=0;i<3;i++)
arr[i]=sc.nextDouble();
double result[]=solveQuadratic(arr); // unknown
//if result is negative
if(result.length==1) {
System.out.println("The equation has no real roots");
}
//if result is = to zero
else if(result.length==2) {
System.out.println(" The equation has just one real root");
System.out.format("The root is %.2f",result[1]);
}
//if result is positive
else
{
System.out.println("The equation has two real roots");
System.out.format("The root are %.2f and %.2f",result[1],result[2]);
}
}
public static double[] solveQuadratic(double[] eqn) { // method heading from assignment
double discriminant=eqn[1]eqn[1]-(4eqn[0]eqn[2]); // discriminant of the quadratic equation
if(discriminant>0) { // discriminant is positive and has 2 real roots
double r1=(-eqn[1]+Math.sqrt(discriminant))/(2eqn[0]); // equation for square roots
double r2=(-eqn[1]-Math.sqrt(discriminant))/(2eqn[0]); //equation for square roots
double res[]= {2,r1,r2};
return res;
}
else if(discriminant==0) //equal to zero the equation has just one real root
{
double r1=(-eqn[1])/(2eqn[0]);
double res[]= {1,r1};
return res;
}
else // the equation has no real roots
{
double res[]= {0}; //unknown
return res; //unknown
}
}
}
The line that is causing me trouble and throwing errors on is the following ...
double discriminant=eqn[1]eqn[1]-(4eqn[0]eqn[2]);
It says "Invalid float literal number" and "Syntax error on taken "eqn", delete this token"
Could someone help explain what this error means?
The comment by #f1sh was the first of multiple examples of the same problem.
As pointed out, you needed a multiplication operator for eqn[1]*eqn[1].
For 4eqn[0]eqn[2], the same applies. If I remember my quadratics, you are trying to multiply there, so you need 4*eqn[0]*eqn[2]. The line should read:
double discriminant=eqn[1]*eqn[1]-(4*eqn[0]*eqn[2]);
Similarly, in your calculation for r1 and r2, 2eqn[0] should be 2*eqn[0]. That fix is needed in both places you calculate r1.
So, the basic rule is that, in java, you must specify the operator between two symbols. Unlike in math, writing them next to one another does not imply multiplication.
Related
I am new to using java and am having some issues in my java class right now and will be needing help with my specific code. I try to look at others questions on here all the time but it's never exactly what I need. Here are my directions:
Create a Java file called CompoundInterestYourLastName. Write a method called computeBalance() that computes the balance of a bank account with a given initial balance and interest rate, after a given number of years. Assume interest is compounded yearly.
Use a loop to control the iterations through the years in your method.
Your method should return a double value.
In your main method, run the following tests to verify your method is working correctly.
System.out.printf("Your total is $%.2f", computeBalance(1000, .045, 3));
// should return $1141.17
I am using eclipse and my only current error is in the comments. I also want some general tips and let me know if my logic is wrong. It probably is. :D
Here is what I have currently although I have been trying different things:
import java.util.Scanner;
import java.lang.Math;
public class CompoundInterestTidwell {
public static void main(String[] args) {
double compInt = computeBalance(1000, 0.045, 3);
System.out.printf("Your new balance is $%.2f", compInt);
}
// Getting arror for line of code below.
// Error: This method must return a result of type double
public static double computeBalance(int P, double r, int t) {
// Formula for compounding interest
// A = P(1+(r/n))^(n(t))
// The examples to check my math had rate already divided by 100 so I left out r/n.
for(int c = 0; c <= t; c++ ) {
// deleted 'n' from equation because it need to equal 1 anyways.
double compInt = Math.pow(P*(1+r), t);
if (c < t) {
c++;
return compInt;
}
}
}
}
Thanks.
Your function computeBalance doesn't guarantee to return a value, because the only return statement is in an if clause, within a loop (making it two conditions deep).
This is a thing the compiler is warning you about. Basically it scans your code and makes sure that a function declared as double will actually return a valid value of type double and so on.
If you add a return statement at the end of the body in the function (or throw an error) it should compile.
I am not exactly sure what your function does in technical terms, but I've rewritten it so it should return the same value, but should now actually compile.
public static double computeBalance(int P, double r, int t) {
// Formula for compounding interest
// A = P(1+(r/n))^(n(t))
// The examples to check my math had rate already divided by 100 so I left out r/n.
double compInt = 0; // Declare compInt outside the loop.
for(int c = 0; c <= t; c++ ) {
// deleted 'n' from equation because it need to equal 1 anyways.
compInt = Math.pow(P*(1+r), t);
if (c < t) {
c++;
break; // Break instead of return, will immediately
// go to the return statement outside the loop.
}
}
return compInt; // Moved the return statement to outside the loop so
// the function always will return a double.
}
I just started learning how to program in Java. Everything was going well so far.. That was until I came across this "bonus" question/problem our teacher gave us to solve as an additional "challenge".
Please click here to view the Question and the Sample input/output (it's an image file)
Note that I'm not allowed to use anything that wasn't taught or discussed in class. So, things like arrays, method overloading, parsing arrays to methods, parseInt, etc. gets ruled out.
Here's what I was able to come up with, so far:
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
int N; // number of lines of input
double length1, length2, length3; // the 3 lengths
double perimeter; // you get this by adding the 3 lengths
double minperimeter=0; // dummy value
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of triangles you have:");
N = input.nextInt();
System.out.println("Insert the lengths of the sides of these " +
"triangles (3 real numbers per line):");
for (int counter=0; counter<N; counter++)
{
length1 = input.nextDouble();
length2 = input.nextDouble();
length3 = input.nextDouble();
perimeter = (length1 + length2 + length3);
minperimeter = Math.min(perimeter,Math.min(perimeter,perimeter));
}
System.out.printf("The minimum perimeter is %.1f%n", minperimeter);
}
}
My 2 main problems are:
1) The program only stores and works with the 'last' input.
The ones before it get replaced with this one. [update: solved this problem]
2) How do I print the "triangle number" in the final output? [update: solved this problem, too]
So, can anyone please help me come up with a solution that requires only the very basic learnings of Java? If it helps, this is the book we're using. Currently at Chapter 4. But we did learn about Math Class (which is in Chapter 5).
Update: Thank you so much for your replies, everyone! I was able to come up with a solution that does exactly what was asked in my question.
Math.min(perimeter,perimeter) will always give you perimeter. You probably wanted to do Math.min(perimeter,minPerimeter)
Since it's a programming assignment is best if I don't give you the full solution to your second question, but your hint is, in the counter parameter of your for loop. Save that when you update minperimeter, so that you know in which iteration of the loop you found the minimum.
Also, initialise your minPerimeter to 10000 or higher. If you start at 0, Math.Min will never be lower than that.
Change your for loop as:
double minperimeter=-1;
for (int counter=0; counter<N; counter++)
{
length1 = input.nextDouble();
length2 = input.nextDouble();
length3 = input.nextDouble();
perimeter = (length1 + length2 + length3);
if(minperimeter == -1){
minperimeter = perimeter;
} else{
Math.min(perimeter,minperimeter);
}
}
You have to store the smaller perimeter in your variable perimeter.
The hint from your task tells you, that any given perimeter is smaller than 1000. Thus initiate the perimeter to 1000.
In your for-loop then you have to store the smaller perimeter:
perimeter = Math.min(perimeter, length1 + length2 + length3)
if the sum of the edges is smaller than the current perimeter, the smaller value will be stored.
Please note that according to your given task, you have to input 3 doubles within one line.
Alternative Solution
Make an ArrayList and add all perimeter to that list and then find the minimum value from that list.
List<Double> perimeter = new ArrayList<>();
for (int counter=0; counter<N; counter++)
{
length1 = input.nextDouble();
length2 = input.nextDouble();
length3 = input.nextDouble();
perimeter.add(length1 + length2 + length3);
}
System.out.printf("The minimum perimeter is %.1f%n", Collections.min(perimeter));
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 created a calculator and it works fine. I just need that when an amount is lower than the other so it will give the message "Amount A is less than amount B" instead of the calculation itself.
How can I make it return my message?
Here is my code for the calculation:
public class CalculatorModel
{ // Holds the value of the sum of the numbers
// entered in the view
private double calculationValue;
public void calculateDiscount(double number, double number1,
double number2, double number3, double number4,
double number5)
{
if (number2 == number4 && number3 > number5);
{
//calculationValue = (((number2 / number3) * ((number1)) / number - 1) * 100);
}
}
public double getCalculationValue()
{
return calculationValue;
}
}
You mean something like this? Assuming that you have double A and double B passed from somwhere.
if(A<B){
String message = "Amount "+A+" is less than amount "+B;
return message
}
You need to throw an Exception and catch the exception where you would expect to get the calculation value and display the exception message. For example:
throw new Exception("Amount A is less than amount B");
Obviously format it so that A and B are your actual values.
Observations:
Your question has nothing to do with double to String conversion, which can be done by Double.toString(d) or simply concatenating the double with a String e.g. "The number " + A + " is a double".
throwing an Exception is overkill, IMHO, no point in catching that Exception to do something with it, other than printing it out.
You probably want the user to re-enter numbers A, and B. Thus you should not terminate the execution.
You could use System.err.println("Amount A is less than amount B") in a while loop, so that user re-enters A and B, until the criterion A > B is fulfilled.
If your program has a graphical user interface (GUI), rather than command-line interface (CLI), then you need to pop a JDialog, to notify the user. THere are multiple examples on Java Trail.
I was doing a simple calculation program in java when I encountered this problem. I want to convert centimeter square to meter square. 1 cm² = 0.0001 m². When i create the program in java to do this conversion I got result in '1.0E-4' instead of '0.0001'. I don't know why it is showing in that way. may someone guide me how to do it or something that may help
Here is the code:
import java.io.*;
class First {
public static void main(String x[]) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please Enter the number");
double number = Double.parseDouble(br.readLine());
double d1 = 0.0001;
double result = number * d1;
System.out.println("Result is " + result);
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
Doubles within a certain range are printed as a base and an exponent using the scientific notation.
1.0E-4 simply means 1 * 10^(-4), or 0.0001, so the answer you're getting is correct. As suggested by Smutje, you can change the way in which doubles are printed, like this.