I'm new to java and I have a question about an assignment I have. I've written a bunch of methods that are different formulas, like the duration of a storm. The assignment asks me to write two helper methods to get input from the user. One of them is called get_S_Input() and I was able to implement it correctly I think. But the one I'm stuck on is this other helper method called get_2_Invals(). It wants me to prompt the user with my parameter, and read in 2 double values. It wants me to record the values in a class global array of doubles and then exit the method, but I don't know how to do this. I want to put it in the else statement in the method below. Here is my code so far...
import java.lang.Math;
import java.util.Scanner;
public class FunFormulas {
public void sd(){
double durationOfStorm = Math.sqrt(((Math.pow(get_S_Input("Enter the diameter of storm in miles:"), 3) / 216)));
if (durationOfStorm > 0)
System.out.println("The storm will last: " + durationOfStorm);
}
public void sl(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of seconds since the lightning strike:");
double secondsSinceLightning = Double.valueOf(scanner.nextLine());
double distanceFromLightning = (1100 * secondsSinceLightning);
System.out.println(distanceFromLightning);
}
public void si(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the edge of cube in inches:");
double edgeOfCubeInInches = Double.valueOf(scanner.nextLine());
if (edgeOfCubeInInches < 0){
System.out.println("ERROR: please enter a non-negative number!!!");
}
double weightOfCube = (0.33 * (Math.pow(edgeOfCubeInInches, 3)));
System.out.println(weightOfCube);
}
public void dt(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the time in hours:");
double timeInHours = Double.valueOf(scanner.nextLine());
if (timeInHours < 0){
System.out.println("ERROR: please enter a non-negative number!!!");
}
System.out.println("Enter the rate of speed in mph:");
double rateOfSpeed = Double.valueOf(scanner.nextLine());
if (rateOfSpeed < 0){
System.out.println("ERROR: please enter a non-negative number!!!");
}
double distanceTravelled = (rateOfSpeed * timeInHours);
System.out.println(distanceTravelled);
}
public void sa(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your weight in pounds:");
double weight = Double.valueOf(scanner.nextLine());
weight = weight * 0.4536;
System.out.println("Enter your height in inches:");
double height = Double.valueOf(scanner.nextLine());
height = height * 2.54;
double BSA = ((Math.sqrt(weight * height)) / 60);
System.out.println(BSA);
}
public double get_S_Input(String promptStr){
//Scanner helper method
System.out.println(promptStr);
Scanner scanner = new Scanner(System.in);
double value = Double.valueOf(scanner.nextLine());
if (value < 0 ){
System.out.println("ERROR: please enter a non-negative number!!!");
}
return value;
}
public void get_2_Invals(String promptStr){
/*Prompt the user with the promptStr passed in as a parameter
ii. Read in the first double precision value entered by the user with the Scanner
iii. Read in the second double precision value entered by the user with the Scanner
iv. Check to make sure the values entered by the user are non-negative
a. If either number entered by the user is negative, the method should print out an
error message, and return to step i. above.
b. If the number is non-negative (that is greater than or equal to zero) the method
should record the numbers obtained from the user in a class-global array of
doubles and exit.*/
System.out.println(promptStr);
Scanner scanner = new Scanner(System.in);
double firstValue = scanner.nextInt();
double secondValue = scanner.nextInt();
if (firstValue < 0 || secondValue < 0)
System.out.println("ERROR: please enter non-negative number!");
else
}
public static void main(String [] args){
FunFormulas fun = new FunFormulas();
fun.sd();
}
}
I got a task, where I have to calculate the perimeter and area of a given object, that's determined by the user, with accompanying data - side length, radius, etc. To do this I have to do a "GUI" as my teacher said, and to do that, I have to use the Scanner.
Everytime I try to do the second scan, after the user has choosen what object we are dealing with, when it gets to the part, where the user's supposed to input their data about their object, it always crashes, with a java.util.NoSuchElementException error, according to NetBeans. I looked through it, and even copied in the working scanner, but to no avail.
Here's the full code:
package Methods2;
import java.util.Scanner;
public class Methods2 {
public static void main(String[] args) {
//initialization
int decider;
Scanner input1;
//defining
input1 = new Scanner(System.in);
System.out.println("Choose from these options to find the perimeter and area of any of these:\n1. Circle\n2. Square\n3. Rectangle");
decider = input1.nextInt();
input1.close();
//decision
if (decider == 1) {
circle();
} else if (decider == 2) {
square();
} else if (decider == 3) {
rectangle();
} else {
System.out.println("There aren't any other options, other than these three.");
}
}
public static void circle() {
//method specific initialization
int radius;
double pi;
double perimeter;
double area;
Scanner input2;
//define
pi = 3.14;
input2 = new Scanner(System.in);
System.out.println("Please type in the radius of the circle!");
radius = input2.nextInt(); //these are where my problem's lie
input2.close();
//calculate
perimeter = 2 * radius * pi;
area = radius * radius * pi;
//print
System.out.println("The perimeter of this circle is: " + perimeter);
System.out.println("The area of this circle is: " + area);
}
public static void square() {
//method specific initialization
int a;
int perimeter;
int area;
Scanner input3;
//define
input3 = new Scanner(System.in);
System.out.println("Please type in one side's length of the square!");
a = input3.nextInt(); //these are where my problem's lie
input3.close();
//calculate
perimeter = 4 * a;
area = a * a;
//print
System.out.println("The perimeter of this circle is: " + perimeter);
System.out.println("The area of this circle is: " + area);
}
public static void rectangle() {
//method specific initialization
int a;
int b;
int perimeter;
int area;
Scanner input4;
//define
input4 = new Scanner(System.in);
System.out.println("Please type in one of the sides' length of the rectangle!");
a = input4.nextInt(); //these are where my problem's lie
System.out.println("Now type the other, non-equal side, compared to the previous one!");
b = input4.nextInt(); //these are where my problem's lie
input4.close();
//calculate
perimeter = 2 * (a + b);
area = a * b;
//print
System.out.println("The perimeter of this circle is: " + perimeter);
System.out.println("The area of this circle is: " + area);
}
}
I have thought about it being multiple Scanner's, but after I realized, that variables don't carry over between methods, unless they're defined within the class, that was swiftly thrown out as a theory. Also, NetBeans didn't mark any problems with that line, so it made even less sense to me.
The reason why your code is "stopping" the scanner, is because you added input1.close();. What .close() does, is that it closes the scanner. Once a scanner is closed, you won't be able to open it again. According to your code, you use the Scanner.. even after it was closed. So to fix your problem, removed the line:
input1.close();
Here is a close up of where you should remove the line:
//initialization
int decider;
Scanner input1;
//defining
input1 = new Scanner(System.in);
System.out.println("Choose from these options to find the perimeter and area of any of these:\n1. Circle\n2. Square\n3. Rectangle");
decider = input1.nextInt();
//input1.close(); REMOVE THIS LINE
So what I trying to do is ask users to put their weight and score of exam 1 & 2 and if they input the score, use those variables to figure out current score.
However, since scores are declared by users through scanner inside of if statement, it does not let me use those variables from outside of if statement.
How can I use variable 'examOneScore' and 'examTwoScore' when I want to calculate csEx1 and csEx2.
When I try to use those it says "The local variable examOneScore may not have been initialized."
import java.util.Scanner;
public class CurrentScore
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.printf("Weight of Exam 1: ");
double weightExamOne = keyboard.nextDouble();
System.out.printf("Weight of Exam 2: ");
double weightExamTwo = keyboard.nextDouble();
System.out.printf("Do you know your score of first exam? ");
String examOne = keyboard.nextLine();
if(examOne.equalsIgnoreCase("yes") || examOne.equalsIgnoreCase("y"))
{
System.out.printf("Your score? ");
double examOneScore = keyboard.nextDouble();
}
System.out.printf("Do you know your score of secondexam? ");
String examTwo = keyboard.nextLine();
if(answerTwo.equalsIgnoreCase("yes") || answerTwo.equalsIgnoreCase("y"))
{
System.out.printf("Your score? ");
double examTwoScore = keyboard.nextDouble();
}
double csEx1 = (weightExamOne * examOneScore);
double csEx2 = (weightExamTwo * examTwoScore );
}
}
You have to define the variables that you want to use later outside of the if statement:
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.printf("Weight of Exam 1: ");
double weightExamOne = keyboard.nextDouble();
System.out.printf("Weight of Exam 2: ");
double weightExamTwo = keyboard.nextDouble();
System.out.printf("Do you know your score of first exam? ");
String examOne = keyboard.nextLine();
double examOneScore = 1;
if(examOne.equalsIgnoreCase("yes") || examOne.equalsIgnoreCase("y"))
{
System.out.printf("Your score? ");
examOneScore = keyboard.nextDouble();
}
System.out.printf("Do you know your score of second exam? ");
String examTwo = keyboard.nextLine();
double examTwoScore = 1;
if(examTwo.equalsIgnoreCase("yes") || examTwo.equalsIgnoreCase("y"))
{
System.out.printf("Your score? ");
examTwoScore = keyboard.nextDouble();
}
double csEx1 = (weightExamOne * examOneScore);
double csEx2 = (weightExamTwo * examTwoScore );
}
I used the value 1 for defining them, you have to look for yourself want you want to use there
I am new to Java and trying to make a basic body mass calculator.
My problem is I need to ask the questions, convert the measurements and then pass it to another method then display the results in a separate method.
I've added my code below but keep getting a 1.0 returned as the answer each time.
import java.util.Scanner;
public class calcBMI {
public static void main(String[] args)
{
Scanner keyboard = new Scanner( System.in );
System.out.print("Enter weight in pounds: ");
double weightInPounds = keyboard.nextDouble();
double weightInKg = (weightInPounds / 2.2);
System.out.print("Enter height in inches: ");
double heightInInches = keyboard.nextDouble();
double heightInMeters = (heightInInches / 0.254);
double resultBMI = 1;
displayResults(resultBMI);
}
public static double bodyMassIndex(double weightInKg, double
heightInMeters)
{
double resultBMI = weightInKg / Math.pow(heightInMeters, 2) * 1.375;
return resultBMI;
}
public static void displayResults(double resultBMI)
{
System.out.printf("The calculated body mass index was: " + resultBMI);
System.out.println();
}
}
Updated code, now getting;
Enter weight in pounds: 180
Enter height in inches: 68
The calculated body mass index was: 1.1415618118905313E-5
BUILD SUCCESSFUL (total time: 3 seconds)
import java.util.Scanner;
public class calcBMI {
public static void main(String[] args)
{
Scanner keyboard = new Scanner( System.in );
System.out.print("Enter weight in pounds: ");
double weightInPounds = keyboard.nextDouble();
double weightInKg = (weightInPounds / 2.2);
System.out.print("Enter height in inches: ");
double heightInInches = keyboard.nextDouble();
double heightInMeters = (heightInInches / 0.0254);
displayResults(bodyMassIndex(weightInKg, heightInMeters));
}
public static double bodyMassIndex(double weightInKg, double heightInMeters)
{
return (weightInKg / Math.pow(heightInMeters, 2));
}
public static void displayResults(double resultBMI)
{
System.out.printf("The calculated body mass index was: " + resultBMI);
System.out.println();
}
}
You are not calling the bodyMassIndex method in your code at all. Change
displayResults(resultBMI);
to
displayResults(bodyMassIndex(weightInKg, heightInMeters));
resultBMI equals 1, so of course the output would always be :
"The calculated body mass index was: 1"
Full code:
public static void main(String[] args) {
System.out.print("Enter weight in pounds: ");
double weightInPounds = keyboard.nextDouble();
double weightInKg = (weightInPounds / 2.2);
System.out.print("Enter height in inches: ");
double heightInInches = keyboard.nextDouble();
double heightInMeters = (heightInInches / 0.254);
// You can get rid of the resultBMI variable
displayResults(bodyMassIndex(weightInKg, heightInMeters));
}
You get 1.0 because you hard coded it as such.
Change this:
double resultBMI = 1;
To:
double resultBMI = bodyMassIndex(weightInKG, heightInMeters);
By the way, you could also have returned BMI directly in the method and there is no need to multiply by 1.375 anymore since you are already supplying weight in KG:
public static double bodyMassIndex(double weightInKg, double heightInMeters)
{
return (weightInKg / (heightInMeters*heightInMeters));
}
Add on:
Your conversion from inches to meters is wrong as well. It should be:
double heightInMeters = (heightInInches * 0.0254);
import java.util.Scanner;
public class DRYeck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); //declaration scanner
System.out.println("What is given:");
System.out.print("How many sides?"); //input the number of Sides that are given
System.out.println("");
double input = scanner.nextInt();
System.out.print("How many angles? "); //input the number of Angles that are given
System.out.println("");
double input2 = scanner.nextInt();
if((input+input2)>3){ //observes if the input is higher than 3 and errors if this is so
System.out.println("Please enter only 3 entries, you entered "+((int)(input+input2))+" eingegeben...");
}else if((input==1) && (input2==2)){
double side1 = inputDialogSide(); //input a Side
double angle1 = inputDialogAngle(); //input an Angle
double angle2 = inputDialogAngle(); //input an Angle
oneSideTwoAnglesGeneral(side1,angle1,angle2);
}else if((input==2) && (input2==1)){
System.out.println("Is the angle inclsive or exclusiv?");
String input3 = scanner.nextLine(); //input 3 for identification if the angle is inclusive or exclusive
if(input3.equals("inklusiv")){ //set variable 'inclu' to true if 'inclusive' is entered
//distinction of cases into inclusive and exclusive angle
double side1 = inputDialogSide(); //input one Side
System.out.println("");
double side2 = inputDialogSide(); //input the other Side
System.out.println("");
double angle1 = inputDialogAngle(); //input the Angle
twoSidesOneAngleIncl(side1,side2,angle1);
}else{
double side1 = inputDialogSide(); //input one Side
double side2 = inputDialogSide(); //input the other Side
double angle1 = inputDialogAngle(); //input the Angle
twoSidesOneAngleExcl(side1,side2,angle1);
}
}else if((input==3) && (input2==0)){ //condition if 3 Sides are inputed
double side1 = inputDialogSide(); //input first Side
double side2 = inputDialogSide(); //input second Side
double side3 = inputDialogSide(); //input third Side
threeSides(side1,side2,side3);
}
}
public static double inputDialogAngle(){ //subroutine for inputing an Angle
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an angle: ");
double input5 = scanner.nextDouble(); //input5(variable) for an Angle
System.out.println("");
return input5;
}
public static double inputDialogSide(){ //subroutine for inputing a Side
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the sidelength: ");
double input4 = scanner.nextDouble(); //input4(variable) for a Side
System.out.println("");
return input4;
}
static void collection(double alpha,double beta, double gamma,double sidea,double sideb,double sidec){ //sorting the value in the array
double[][] SidesAngles = new double [3][2]; //array for side length value of the angles
for(int i=0;i<SidesAngles.length;i++){
for(int j=0;j<SidesAngles[i].length;j++){
if((SidesAngles[0][0]==0)){
SidesAngles[0][0]=sidea;
}else if((SidesAngles[0][1]==0)){
SidesAngles[0][1]=alpha;
}else if((SidesAngles[1][0]==0)){
SidesAngles[1][0]=sideb;
}else if((SidesAngles[1][1]==0)){
SidesAngles[1][1]=beta;
}else if((SidesAngles[2][0]==0)){
SidesAngles[2][0]=sidec;
}else if((SidesAngles[2][1]==0)){
SidesAngles[2][1]=gamma;
}
}
}
PrintArray(SidesAngles);
}
public static double angleDiff(double angle1, double angle2){
double resuAng = 180-angle1-angle2;
return resuAng;
}
static void PrintArray(double SidesAngles[][]){ //printing the Array with all values
String[][] AngleSideNames = {{"Seite a","Alpha"},{"Seite b","Beta"},{"Seite c","Gamma"}}; //Names of angles and Sides
for(int i=0;i<SidesAngles.length;i++){
for(int j=0;j<SidesAngles[i].length;j++){
System.out.print(AngleSideNames[i][j]+": "+SidesAngles[i][j]+"\n");
}
}
}
public static double sinusRule(double angle1, double angle2, double side){
double angle3 = angleDiff(angle1,angle2);
double resuSide = side*(Math.sin(angle1)/Math.sin(angle2));
return resuSide;
}
static void threeSides(double sidea, double sideb, double sidec){ //subroutine for 3 Sides that are given
double alpha = Math.acos((Math.pow(sidea, 2)+Math.pow(sideb, 2)-Math.pow(sidec, 2))/(2*sidea*sideb));
alpha = Math.toDegrees(alpha); //alpha in degree
double beta = Math.acos((Math.pow(sidea,2)+Math.pow(sidec,2)-Math.pow(sideb,2))/(2*sidea*sidec));
beta = Math.toDegrees(beta); //output in degree
double gamma = angleDiff(beta,alpha); //determine the angle differance
collection(alpha,beta,gamma,sidea,sideb,sidec);
}
static void twoSidesOneAngleIncl(double sidea, double sideb, double gamma){ //subroutine for 1 Angle(inclusive) and 2 Sides
double sidec = Math.sqrt(Math.pow(sidea,2)+Math.pow(sideb,2)-(2*sidea*sideb*Math.cos(gamma)));
double alpha = Math.acos((Math.pow(sideb,2)+Math.pow(sidec, 2)-Math.pow(sidea, 2))/(2*sideb*sidec));
double beta = angleDiff(alpha,gamma);
collection(alpha,beta,gamma,sidea,sideb,sidec);
}
static void twoSidesOneAngleExcl(double sideb, double sidec, double beta){ //subroutine for 1 Angle(exclusive) and 2 Sides
double sidea=0,alpha=0,gamma=0; //initialize sidea, alpha, gamma
double d = ((sidec/sideb)*Math.sin(beta)); //variable for further movement
boolean acute=false,obtuse=false; //initialize check-variable for acute or obtuse triangle
if(d>1){ //condition if check-variable is higher than 1
System.out.println("There is no solution for this triangle");
}else if(d==1){ //if check-variable equals 1
gamma = 90; //gamma=90° because of the conditions
sidea = Math.sqrt(Math.pow(sideb,2)+Math.pow(sidec,2)); //solve sidea with pythagorean theorem
}else{ //if check-variable is lower than
System.out.print("Is the traingle obtuse or actuse: ");
Scanner scanner = new Scanner(System.in); //input for acute or obtuse statement
String input = scanner.nextLine();
if(input.equals("obtuse")){ //sets the right boolean to true so further operations are correct
acute = true;
}else if(input.equals("acute")){
obtuse = true;
}
if((sideb<sidec) && (acute)){ //checks if b<c and the triangle should be acute
gamma = Math.asin(d);
System.out.println("angle gamma: "+gamma);
sidea = sinusRule(beta,gamma,sideb); //Side a
}else if((sideb<sidec) && (obtuse)){ //checks if b<c and the triangle should be obtuse
gamma = Math.asin(d);
gamma = 180-gamma;
System.out.println("angle gamma: "+gamma);
sidea = sinusRule(beta,gamma,sideb); //Side a
}
System.out.println("There is no solution!!!");
}
collection(alpha,beta,gamma,sidea,sideb,sidec);
}
static void oneSideTwoAnglesGeneral(double sidec, double alpha, double beta){//subroutine for one side and two angles that are given
double gamma = angleDiff(alpha,beta); //determine the third angle
double sidea = sidec*(Math.sin(alpha)/Math.sin(gamma)); //determine side with the law of sinus
sinusRule(alpha,gamma,sidec);
double sideb = sidec*(Math.sin(beta)/Math.sin(gamma)); //same here to determine side b
sinusRule(beta,gamma,sidec);
collection(alpha,beta,gamma,sidea,sideb,sidec);
}
}
Exception:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at DRYeck.inputDialogSide(DRYeck.java:85)
at DRYeck.main(DRYeck.java:52)`
My Question is now how to get rid of the exception.
This Program is meant to calculate all sides and angles of an triangle with only 3 inputs. For example one angle and 2 sides or 2 angles and 1 side and so on.
Your issue is related to this section of your code:
else if((input==2) && (input2==1)){
System.out.println("Is the angle inklsiv or exclusiv?");
String input3 = scanner.nextLine(); //input 3 for identification if the angle is inclusive or exclusive
if(input3.equals("inklusiv")){
Since you are not requesting a full line here but just a token, use Scanner.next() instead of Scanner.nextLine();
public String next()
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.
So change this line:
String input3 = scanner.nextLine();
to
String input3 = scanner.next();
And your program should work fine!
I think there is a problem here:
double input = scanner.nextInt();
change it to this and all other occurences:
double input = scanner.nextDouble();