So it's my first time trying to do a loop and I've come across something that I'm not experienced enough to explain... My program compiles fine, but after I enter my third number (variable "a", see code below) it just skips a line and does nothing. It just lets me type whatever I want for as long as I want, like so:
Enter a value for x0:
3
Enter a value for x1:
98
Enter a value for a:
10.3
sj
jd
d
j
wiw
mv
hello
why isn't this working...
sdf
j
That was from my Terminal window after compiling this program:
public class RootFinder {
public static final double EPSILON = 0.00001;
public static double function(double x) {
return (Math.log(x + 1) + x);
}
public static double searchValue(double x0, double x1, double a) {
double x = 0;
boolean valid = (function(x0)<a) && (a<function(x1));
if (!valid) {
x = -1;
}
else if ( (x0 <= -1)||(x1 <= -1) ) {
x = -1;
}
else {
x = (x0 + x1)/2;
}
while (!(function(x)==a)||(Math.abs(function(x) - a) <= EPSILON)) {
if ( (function(x0)<function(x)) && (function(x)<a) ) {
x0 = x;
} else if ((a<function(x)) && (function(x)<function(x1))) {
x1 = x;
}
}
return x;
}
public static void main(String[] args) {
java.util.Scanner reader = new java.util.Scanner(System.in);
System.out.println("Enter a value for x0:");
double x0 = reader.nextDouble();
System.out.println("Enter a value for x1:");
double x1 = reader.nextDouble();
System.out.println("Enter a value for a:");
double a = reader.nextDouble();
double x = searchValue(x0, x1, a);
if (x == -1) {
System.out.println("No such value exists, try again…");
} else {
System.out.println("The root of the equation is " + function(x));
}
}
}
Did I somehow manage to write an infinite loop? I thought I was being careful... Before I inserted the loop, the program compiled fine and the main method managed to print the appropriate message, so I'm pretty sure it's the loop that is the problem.
Thanks in advance!