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.
Related
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.
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.
i'm testing sides of a triangle to see if the triangle is a equilateral or isosceles, but even when all the values are equal I still get the else output.
the code in question is at the bottom, i just included the rest for reference
public static void main(String[] args)
{
System.out.println(" Triangle Calculator \n");
Scanner inputab = new Scanner(System.in);
System.out.println("Input lenghts of sides 'a' and 'b':");
double sideA = inputab.nextDouble();
double sideB = inputab.nextDouble();
System.out.println("Input the size of Angle C in degrees:");
double angleC = inputab.nextDouble();
inputab.close();
double sideC = Math.sqrt((Math.pow(sideA, 2) +
Math.pow(sideB, 2)- 2*(sideA*sideB)*Math.cos(Math.toRadians(angleC))));
System.out.println("\n\t /\\\n\t / \\\n\t / \\\n\t/ \\");
System.out.printf(" %3.1f",sideA);
System.out.print("/ \\");
System.out.printf("%3.1f",sideB);
System.out.println("\n / \\\n / \\\n /______________\\");
System.out.printf("\t %3.1f\n", sideC);
double angleA = Math.asin(sideA*Math.sin(Math.toRadians(angleC))/sideC);
angleA = Math.toDegrees(angleA);
double angleB = 180 - angleC - angleA;
double perimeter = sideA + sideB + sideC;
double hf = 0.5 * (sideA + sideB + sideC);
double area = Math.sqrt(hf*(hf-sideA)*(hf-sideB)*(hf-sideC));
System.out.printf("\nSide a = ");
System.out.printf("%4.3f",sideA);
System.out.printf("\nSide b = ");
System.out.printf("%4.3f", sideB);
System.out.printf("\nSide c = ");
System.out.printf("%4.3f", sideC);
System.out.printf("\nAngle A(Deg) = ");
System.out.printf("%5.3f", angleA );
System.out.printf("\nAngle B(Deg) = ");
System.out.printf("%5.3f", angleB);
System.out.printf("\nAngle C(Deg) = ");
System.out.printf("%5.3f", angleC);
System.out.printf("\nPerimeter = ");
System.out.printf("%5.3f", perimeter);
System.out.printf("\nArea = ");
System.out.printf("%5.3f", area);
if (sideA == sideB && sideA == sideC)
{
System.out.println("\nThis is an Equilateral Triangle");
}
else
{
System.out.println("\nThis is not an Equilateral Triangle");
}
if ((sideA == sideB && sideB!= sideC )
||(sideA != sideB && sideC == sideA)
|| (sideC == sideB && sideC != sideA))
{
System.out.println("\nThis is an Isosceles Triangle");
}
else
{
System.out.println("\nThis is not an Isosceles Triangle");
}
Pointy is correct. I ran eclipse in debugger mode to look at the values as the program executed. I used 5 for the values of sides A and B and 60 for angleC. The result was that A and B were equal to 5.0 while side C was equal to 4.9999...
There are multiple ways you could go about fixing this, but you seem capable, especially now that you know what the issue is.
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);
How can I implement this into code I am taking a user input of three separate floats that must add to one (ie .333333,.333333,.333333) those numbers are the probability of a number (-1,0,1) being picked at random.
if( new Random().nextDouble() <= 0.333334){array[i]=randomNumber(-1,0,1)?
Or something along those lines?
The likelihood that three floats will add to exactly 1.0 is very low, because many (most) real numbers cannot be represented exactly as floats. The best you could do is enter two numbers and calculate the third, which would guarantee that they would add up to 1.0.
public static void main(String[] args) {
double[] probs = readProbabilities();
double random = new Random().nextDouble();
int randomNumber;
if (random <= probs[0]) {
randomNumber = -1;
} else if (random <= (probs[0] + probs[1])) {
randomNumber = 0;
} else {
randomNumber = 1;
}
System.out.println("Random Number is " + randomNumber);
}
public static double[] readProbabilities() {
Scanner sc = new Scanner(System.in);
double first, second, third;
System.out.print("Please insert 1st probability: ");
first = sc.nextDouble();
while (first < 0.0 || first > 1.0) {
System.out.print("Must be between 0.0 and 1.0, try again: ");
first = sc.nextDouble();
}
System.out.print("Please insert 2nd probability: ");
second = sc.nextDouble();
while (second < 0.0 || (first + second) > 1.0 ) {
System.out.print("Must be between 0.0 and " + (1.0 - first) + ":");
second = sc.nextDouble();
}
third = 1.0 - (first + second);
System.out.println("3rd Possibility is " + third);
return new double[] {first, second, third};
}
Questions?