Solving mismatch exceptions only appearing in one compiler - java

This is for an online assignment. The goal is to accept two inputs (in this code, the x and y variables) multiple times and then print the largest and smallest value of each variable. Here is the code:
import java.io.*;
import static java.lang.System.*;
import java.util.Scanner;
import java.lang.Math;
class Lesson_20_Activity_One{
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner(System.in);
double x; //the latitude input
double y; //the longitude input
double n = -90; //the maximum north value
double e = -180; //the maximum east value
double s = 90; //the maximum south value
double w = 180; //the maximum west value
int escape = 1; //the value that dictates when it's time to exit the while loop
while (escape == 1) {
System.out.println("Please enter the latitude:");
x = scan.nextDouble();
System.out.println("Please enter the longitude:");
y = scan.nextDouble();
if ((x>n) && (x<=90))
n = x;
if ((x<s) && (x>=-90))
s = x;
if ((y>e) && (y<=180))
e = y;
if ((y<w) && (y>=-180))
w = y;
if ((x>90)||(x<-90)||(y>180)||(y<-180))
System.out.println("Incorrect Latitude or Longitude");
System.out.println("Would you like to enter another location?");
escape = scan.nextInt();
}
System.out.println("Farthest North: " + n);
System.out.println("Farthest South: " + s);
System.out.println("Farthest East: " + e);
System.out.println("Farthest West: " + w);
}
}
This code runs exactly as intended on my personal compiler, Eclipse. However, when running this same program on the course's online compiler, I am met with these errors:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Lesson_20_Activity.main(Main.java:322)
at Ideone.assertRegex(Main.java:85)
at Ideone.assertRegex(Main.java:76)
at Ideone.test(Main.java:40)
at Ideone.main(Main.java:29)
What can I do to solve these errors? It seems it's a problem with my Scanner, but I don't know how to fix it.

The error trace seems to indicate that the InputMismatchException is thrown when scan.nextInt() is called.
After your print System.out.println("Would you like to enter another location?");, if the user inputs anything other than an integer, scan.nextInt() will throw an exception. Even if you read the user's input as a string as suggested by someone else, the parseInt method in escape = Integer.parseInt(scan.nextLine()) will throw an error because the string may not be a valid integer.
I suggest adding try-catch block as follows around the scan.nextInt() call so that your program doesn't crash when a user inputs something other than a valid integer (like the number 8.238).
boolean inputValid = false;
System.out.println("Would you like to enter another location?");
while (!inputValid) {
try {
escape = scan.nextInt();
inputValid = true;
} catch (InputMismatchException e) {
inputValid = false;
System.out.println("Please enter a valid Integer");
}
}
This code will continue asking the user until the user enters a valid integer.

It might be because the online scanner's implementation of nextInt() is different and is causing the problems.
Perhaps trying to parse the input as a string and the as a double/int would work:
Scanner scan = new Scanner(System.in);
double x; // the latitude input
double y; // the longitude input
double n = -90; // the maximum north value
double e = -180; // the maximum east value
double s = 90; // the maximum south value
double w = 180; // the maximum west value
int escape = 1; // the value that dictates when it's time to exit the
// while loop
while (escape == 1) {
System.out.println("Please enter the latitude:");
x = Double.parseDouble(scan.nextLine());
System.out.println("Please enter the longitude:");
y = Double.parseDouble(scan.nextLine());
if ((x > n) && (x <= 90))
n = x;
if ((x < s) && (x >= -90))
s = x;
if ((y > e) && (y <= 180))
e = y;
if ((y < w) && (y >= -180))
w = y;
if ((x > 90) || (x < -90) || (y > 180) || (y < -180))
System.out.println("Incorrect Latitude or Longitude");
System.out.println("Would you like to enter another location?");
escape = Integer.parseInt(scan.nextLine());
}
System.out.println("Farthest North: " + n);
System.out.println("Farthest South: " + s);
System.out.println("Farthest East: " + e);
System.out.println("Farthest West: " + w);
Again, this depends on the online scanner's way of doing things.

Related

Correcting a formula in java

My first assignment requires me to write a program that expresses a formula. The formula as written in the assignment :
y = 4x^3 + 8x^2 - 31x - 35 / (3x2 + 1)^1/2 + 2 * | x - 1.5 |
| means absolute value; (...)1/2 means square root
Also how should I create a code that prints how many times the formula prints out a positive or negative number or zero?
Here is how I created my assignment's program:
import java.io.*;
public class hw1 {
public static void main(String[] args) throws IOException
{
System.out.println("My name is Jibran Khan and this is the output of my first program.");
double x; double y;
PrintWriter outFile = new PrintWriter("testfile.txt");
for(x=-3.00; x <= 3.0; x = x + 0.50)
{
y=((4*(x*x*x))) + (8*(x*x))-(31*x)-35/Math.sqrt(3*x*x+1)+2* Math.abs(x-1.5);
System.out.println("X = " + x + "Y = " + y );
if (y<=0.0) System.out.println("Y is negative");
if (y>=0.0) System.out.println("Y is positive");
if (y == 0.0) System.out.println("Y is zero");
}
System.out.println();
System.out.println("My first program is complete");
outFile.close();
}
}
OK, you want to make a test on a simple math formula. You have to test the results and define how many results are positive, negative or equal to 0 ...
You have to update your tests... It result is equal to 0, your test returns positive, negative and null results.
You also have to count results. So implement counters for each type of results and increment them in the if statement.
public static void main(String[] args) throws IOException {
double x; double y;
int positive = 0;
int negative = 0;
int equalZero = 0;
PrintWriter outFile = new PrintWriter("testfile.txt");
for(x=-3.00; x <= 3.0; x = x + 0.50) {
y = Math.pow(4,3) + ... ( your formula)
System.out.println("X = " + x + "Y = " + y );
if (y < 0.0) {
System.out.println("Y is negative");
negative++;
} else if (y > 0.0) {
System.out.println("Y is positive");
positive++;
} else {
System.out.println("Y is zero");
equalZero++;
}
}
System.out.println();
System.out.println("Positive results : " + positive);
System.out.println("Negative results : " + negative);
System.out.println("Equal to zero : " + equalZero);
outFile.close();
}
Calculate the Denominator and Numerator in different variables, that will give more readability and you will be able to spot the mistakes easily.
Also, the conditions you gave for y: (y <= 0.0) and (y >= 0.0) will be true for zero so the last condition y == 0.0 is not reachable.

Reason for error: var might not have been initiazed

The user should enter the values to x and y, and if x is greater than 5 and and when y= 0 , then z should be equivalent to x+y. However, when I compile it gives me an error saying that z might not have been initialized.
import java.util.Scanner;
public class add {
public static void main(String[] args ){
Scanner input = new Scanner (System.in);
System.out.print("Enter a value for x");
int x = input.nextInt();
System.out.print("\nEnter a value for y ");
int y = input.nextInt();
int z;
if (x > 5){
if (y == 0)
z = x + y;
System.out.println("The answer is " + z);
}
else
System.out.println("The answer is only" + x);
}
}
There is an execution path where z doesn't get initialized, but you attempt to print it. If x is greater than 5, but y isn't 0, then z is not initialized, but you refer to z when printing it.
Use braces to create an inner block for your inner if statement, so z is only referenced if it's initialized:
if (x > 5){
if (y == 0) {
z = x + y;
System.out.println("The answer is " + z);
}
}
Also, proper indenting helps to identify visually what's part of a block and what's not.
Your 'if' statement is misleading:
if (y == 0)
z = x + y;
What if y != 0? In that case, z is not initialized.
The next line
System.out.println("The answer is " + z);
doesn't apply to the y==0 statement, as you don't have braces {}.
You probably meant to write something like:
if (x > 5) {
if (y == 0) {
z = x + y;
System.out.println("The answer is " + z);
}
}
Note the "{" after the if statement.
As you are not using braces for if condition, your z will not initialized.
To solve such kind problems always keep in mind that if you are calculating something with integer variable do initialize them with some value (here, 0 is the best).
Then you can access that variable anywhere in the code without any initialization error.
To rid of this problem, you have two ways
One way:
just simply initialize your z variable like:
int z=0;
Second way:
Try to put braces for if condition like:
if (y == 0){
z = x + y;
System.out.println("The answer is " + z);
}
You need to assure the compiler that z will get a value no matter what.
You may want to assign it a default value when declaring it.
Something along these lines:
int z = 0; // just an example
int z has no value, try the code at the bottom then give it a 0 or input.nextInt();
int z = 0;
or
int z = input.nextInt();

dividing a number into other significant digits

The title is quite confusing, as i am not aware what to title this question. Anyway I have java programming homework that requires a number to be divide into the correct amount of change. I am not getting any message when using the program, i can input the number, then nothing happens.
Thanks
-Jordan
double input; // The input
double l = 0; // Toonies (2.00 dollars)
double t = 0; // loonies (1.00 dollars)
double q = 0; // quarters (0.25 dollars)
double d = 0; // dimes (0.10 dollars)
double n = 0; // nickels (0.05 dollars)
double p = 0; // pennies (0.01 dollars)
System.out.println("Hello, this application will tell you how much"
+ "change you have, based on your input.");
System.out.println("Please enter a real integer");
input = TextIO.getDouble(); // Retrieves the next double entered
while (input > 2) {
t++;
} // Closes of toonie statement
while (input > 1) {
l++;
} // Closes of loonie statement
while (input > 0.25) {
q++;
} // Closes of quarter statement
while (input > 0.1) {
d++;
} // Closes of dime statement
while (input > 0.05) {
n++;
} // Closes of nickel statement
while (input > 0.01) {
p++;
} // Closes of penny statement
System.out.println("You have " // Prints a message saying how many of each coin you have
+ t + "toonies, "
+ l + "loonie(s), "
+ q + "quarter(s), "
+ d + "toonie(s), "
+ n + "toonies(s), "
+ p + "pennies(s), ");
In each of those while loops, you also need to be subtracting the amount from the input. Since you are not, it probably is going into an infinite loop on one of those. For example:
while (input > 2) {
t++;
input -= 2;
}
You are not decrementing the input so you get stuck in an infinite loop in the first while for which the initial condition is true:
You should decrement the input amount in your loops:
while (input > 2) {
t++;
input -=2;
}
The variable 'input' is never reduced, so once one of the while loops is entered, there's no way to exit it, and it will continue until you stop the program by some other means.
I suggest you do you calculations in cents. This way you can use a long. Instead of using a loop, you can just use integer division. This will be faster, shorter and more accurate.

Want to loop but variable is not initialized

My problem starts at the first do-while loop. I want it to ask "Please enter an angle between 0 an 90: " and if the user does input a number between 0 and 90, they have to input the amount of gun powder. Their inputs will go through the physics calculations and if their outcome is not "It's a hit!" then I want them to go back and input the angle and gunpowder again. But the thing is at the
while (distance - distance2 != 0 || distance - distance2 != 1 || distance2 - distance != 1); System.out.println("It's a hit!");
The error says: variable distance2 might not have been initialized.
import java.util.*;
import java.text.*;
public class BombsAway {
private static double ZERO_THOUSAND = 1000;
private static double KG_TO_VELOCITY = 50;
private static double GRAVITY = -9.81;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
DecimalFormat threeDec = new DecimalFormat("#.##");
Random gen = new Random();
BombsAway distanceAn = new BombsAway();
boolean invalidInput = true;
double distance, distance2;
System.out.println("Please enter a positive integer seed value: ");
while(invalidInput) {
try {
int seedValue = Integer.valueOf(input.nextLine());
if (seedValue <= 0) {
System.out.println("Please enter a positive integer seed value:"
+ " ");
}
else {
distance = gen.nextDouble() * ZERO_THOUSAND;
System.out.println("That target is " + threeDec.format(distance)
+ "m away.");
do {
System.out.println("Please enter an angle between 0 and 90 " +
"degrees: ");
while (invalidInput) {
try {
double angle = Double.valueOf(input.nextLine());
if (angle < 0 || angle > 90) {
System.out.println("Please enter an angle between " +
"0 and 90 degrees: ");
}
else {
System.out.println("Please enter the amount of " +
"gunpowder in kilograms: ");
try {
double gunpowder =
Double.valueOf(input.nextLine());
//physics part
double initialV = gunpowder * KG_TO_VELOCITY;
double vX = initialV * Math.cos(angle);
double vY = initialV * Math.sin(angle);
double airBorn = (-vY - vY) / GRAVITY;
distance2 = (vX * airBorn);
if (distance > distance2) {
double finalDist = distance - distance2;
System.out.println("It's " +
threeDec.format(finalDist) + "m short.");
}
else if (distance < distance2) {
double finalDist = distance2 - distance;
System.out.println("It's " +
threeDec.format(finalDist) + "m long.");
}
}
catch(NumberFormatException e) {
System.out.println("Please enter the amount of " +
"gunpowder in kilograms: ");
}
}
}
catch(NumberFormatException e) {
System.out.println("Please enter an angle between " +
"0 and 90 degrees: ");
}
}
}while (distance - distance2 != 0 || distance - distance2 != 1
|| distance2 - distance != 1);
System.out.println("It's a hit!");
}
}
catch(NumberFormatException e) {
System.out.println("Please enter a positive integer seed value: ");
}
}
}
}
In your code - distance2 is initialized inside one of the conditional blocks (in else block inside while loop) there may be cases when your while or else condition will not be fulfilled and in that case distance2 is left un-initialized and Local variables cannot be used without initialization so simply initialize that distance2 with any meaningful or required default value as:
double distance2 = 0.0; or with some specific value that your code logic works on
The distance2 variable is initialized in a try/catch block. It's possible an exception could be thrown, and land the flow of control in the catch block before distance2 is initialized. After the catch block, distance2 is used in a calculation at the end of the while loop, so yes: it might not be initialized at this line:
while (distance - distance2 == 0 || distance - distance2 == 1
|| distance2 - distance == 1)
if a NumberFormatException was thrown when you are reading the gunpowder or angle values from input. There is also an if condition (bounds check on angle) that could leave distance2 unset.

asks the user for an angle in degrees between 0 and 180

My program accepts any number that I input even 1 million >.<
but I only wanted to ask the user to input an angle in degrees between 0 to 180 and outputs
the sine, cosine and tangent of that angle
here is my program :
import java.util.Scanner;
import java.text.DecimalFormat;
public class Mathematics
{
public static void main(String args[])
{
System.out.println("Enter an Angle ");
Scanner data = new Scanner(System.in);
int x;
x=data.nextInt();
double sinx = Math.sin( Math.toRadians(x) );
double cosx = Math.cos( Math.toRadians(x) );
double tanx = Math.tan( Math.toRadians(x) );
DecimalFormat format = new DecimalFormat("0.##");
System.out.println("Sine of a circle is " + format.format(sinx));
System.out.println("cosine of a circle is " + format.format(cosx));
System.out.println("tangent of a circle is " + format.format(tanx));
}
}
Put this code after x=data.nextInt();
if( x < 0 || x > 180 )
{
throw new Exception("You have entered an invalid value");
}
This will cause your program to crash if the user inputs a number outside the range [0, 180].
If you wish to allow the user to try again, you would need to put the program into a loop, like so:
do
{
System.out.print("Enter a value in [0, 180]: ");
x = data.nextInt();
} while(x < 0 || x > 180);
This loop will continue until the user enters the desired values.
Instead of
x = data.nextInt();
write
do {
x = data.nextInt();
if (x < 0 || x > 180) {
System.out.println("Please enter number between 0-180");
}
} while (x < 0 || x > 180);
Put the question in a loop. When the user enters a value that is outside your range, print an error message and request a different value. When the entered value is OK, then you can exit the loop. It is better to use a function to make things more readable:
public static int askForInt(String question, String error, int min, int max) {
while (true) {
System.out.print(question + " (an integer between " + min + " and " + max + "): ");
int read = new Scanner(System.in).nextInt();
if (read >= min && read <= max) {
return read;
} else {
System.out.println(error + " " + in + " is not a valid input. Try again.");
}
}
}
Call like this: x = askForInt("The angle", "Invalid angle", 0, 180);

Categories