why does my scanner(system.in) run twice - java

I am new to java, been self teaching for the last week. I cannot find the reason why the if else statement runs twice. here is the whole code, I know is simple but still trying to learn.
package tickets;
import java.util.Scanner;
public class tickets {
public static void main(String[] args) {
//program designed to ask how many visitors
//are in a party of people and work out
//the total cost of the entry tickets.
double adult = 12.50;
double consession = 9.90;
double child = 6.25;
double percentage = 0.80;
System.out.println("please enter the amount of adults");
Scanner adult1 = new Scanner (System.in);
//adding code that would give a percentage discount for
//4 adults or more
{
if ( adult1.nextInt() >= 4
{
double adult2 =( adult1.nextInt() * percentage);
}else {
double adult2 = (adult * adult1.nextInt());
System.out.println("please enter the amount of consessions");
Scanner consession1 = new Scanner (System.in);
double consession2 = (consession *consession1.nextInt());
System.out.println("please enter the amount of children");
Scanner child1 = new Scanner (System.in);
double child2 = (child * child1.nextInt());
System.out.println( "total"+" " + (adult2 +consession2 + child2) );
System.out.println("hope you enjoy your visit today!");
//woop woop it works!!!!!!!!!!
}
}
}
}

The reason why your program asked for two inputs was because adult1 is the name of your scanner and in your if statement the condition was if the user input is >= 4 then take an Integer input again from the user and multiply that with percentage and store it in adult2, instead this should be done as follows
public static void main(String[] args)
{
double adult = 12.50;
double consession = 9.90;
double child = 6.25;
double percentage = 0.80;
double adult2 = 0.0 // you dont need to redeclare below
System.out.println("please enter the amount of adults");
Scanner adult1 = new Scanner (System.in);
// remove this unneccessary bracket {
int num = adult1.nextInt();
if ( num >= 4)
{
adult2 =( num * percentage);
}
else
{
adult2 = (adult * num);
}
System.out.println("Adult2 is " + adult2);
}

Store the int from the scanner and use that value in your ifs and calculations. You're calling nextInt() more than once and each time you get another int.
After you enter the if or else you will wait for more input of the integer type stopping the program.

Related

How to create a helper method that takes 2 double inputs into a class global array?

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();
}
}

How can I use input from user that exist inside of if statement in Java?

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

static reference error with class methods java [duplicate]

This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 5 years ago.
New to java. Do not understand error. Basically trying to return value to then determine output but error "Cannot make static reference to non static field appears on line 13" in the class bosscalc. Return values from operators class.Please help. I have indicated line 13 in the class bosscalc. Thanks
package calculator;
import java.util.Scanner;
public class bosscalc {
Scanner input = new Scanner(System.in);
public static void main(String args[]) {
operators operatorobjects=new operators();
String answer;
System.out.println("What would you like to do? ");
answer =input.nextLine(); -------------------------LINE 13
if (answer=="a"){
double adding = operatorobjects.add();
}
if (answer=="s") {
double subtrat = operatorobjects.sub();
}
if (answer=="m") {
double multiply = operatorobjects.sub();
}
}
}
Class operators:
package calculator;
import java.util.Scanner;
public class operators {
double add() {
double n1,n2,a;
Scanner input=new Scanner(System.in);
System.out.print("Enter number 1 ");
n1=input.nextDouble();
System.out.print("Enter number 2 ");
n2=input.nextDouble();;
a=n1+ n2;
return a;
}
double sub() {
double n1,n2,d;
Scanner input=new Scanner(System.in);
System.out.print("Enter number 1 ");
n1=input.nextDouble();
System.out.print("Enter number 2 ");
n2=input.nextDouble();;
d=n1 - n2;
return d;
}
double m() {
double n1,n2,m;
Scanner input=new Scanner(System.in);
System.out.print("Enter number 1 ");
n1=input.nextDouble();
System.out.print("Enter number 2 ");
n2=input.nextDouble();;
m=n1/n2;
return m;
}
}
As the error message says: From a static context (your static main function) you cannot reference a non-static variable (input).
You can fix it by making input static, i. e. declare it as follows:
static Scanner input = new Scanner(System.in);
I have spent five minutes changing (refactoring) your code. There were a few simple errors. I have moved everything into a single class, and added some comments.
There are lots of improvements which can be made. But this is all down to practice and experience:
import java.util.Scanner;
public class Operators {
/**
* add numbers
* #return n1 + n2
*/
double add() {
double n1, n2, a;
Scanner input = new Scanner(System.in);
System.out.print("Enter number 1 ");
n1 = input.nextDouble();
System.out.print("Enter number 2 ");
n2 = input.nextDouble();
a = n1 + n2;
return a;
}
/**
* subtract numbers
* #return n1 - n2
*/
double sub() {
double n1, n2, d;
Scanner input = new Scanner(System.in);
System.out.print("Enter number 1 ");
n1 = input.nextDouble();
System.out.print("Enter number 2 ");
n2 = input.nextDouble();
d = n1 - n2;
return d;
}
/**
* multiply numbers
* #return n1 * n2
*/
double multiply() {
double n1, n2, m;
Scanner input = new Scanner(System.in);
System.out.print("Enter number 1 ");
n1 = input.nextDouble();
System.out.print("Enter number 2 ");
n2 = input.nextDouble();
m = n1 * n2;
return m;
}
/**
* divide numbers
* #return n1 / n2
*/
double divide() {
double n1, n2, m;
Scanner input = new Scanner(System.in);
System.out.print("Enter number 1 ");
n1 = input.nextDouble();
System.out.print("Enter number 2 ");
n2 = input.nextDouble();
m = n1 / n2;
return m;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Operators operatorobjects = new Operators();
String answer;
System.out.println("What would you like to do? ");
answer = input.nextLine();
/**
* String equality use String.equals()
*/
if (answer.equals("a")) {
double adding = operatorobjects.add();
/**
* Debug output println
*/
System.out.println("adding = " + adding);
} else if (answer.equals("s")) {
double subtract = operatorobjects.sub();
System.out.println("subtract = " + subtract);
} else if (answer.equals("m")) {
double multiply = operatorobjects.multiply();
System.out.println("multiply = " + multiply);
} else if (answer.equals("d")) {
double divide = operatorobjects.divide();
System.out.println("divide = " + divide);
}
/**
* More debug exiting
*/
System.out.println("exiting");
}
}
I have added a divide method, and renamed to multiply. The output from running is:
What would you like to do?
a
Enter number 1 10
Enter number 2 10
adding = 20.0
exiting
What would you like to do?
s
Enter number 1 10
Enter number 2 2
subtract = 8.0
exiting
What would you like to do?
m
Enter number 1 2
Enter number 2 5
multiply = 10.0
exiting
What would you like to do?
d
Enter number 1 6
Enter number 2 3
divide = 2.0
exiting

only allowing java scanner to allow numbers

I've been having issues catching non numbers.
I tried try / catch but I can't grasp a hold of it. If anything I get it to catch non numbers, but doesn't let the user try entering again... It just stops my code completely.
Here is my code:
package triangle;
import java.util.Scanner;
public class traingle {
public static void main(String[] args){
//explaining what the program is going to do
System.out.println("You will be able to enter 3 angles to equal the sum of a triangle,\nthis automated program will tell you if the angle you entered is issosoliese, eqilateral or scalene");
//creating input 1,2,3 for user
Scanner angle1 = new Scanner(System.in); // Reading from System.in
System.out.println("Enter angle degree number 1: ");
int n = angle1.nextInt();
Scanner angel2 = new Scanner(System.in);
System.out.println("Enter angle degree number 2: ");
int n2 = angel2.nextInt();
Scanner angel3 = new Scanner(System.in);
System.out.println("Enter angle degree number 3: ");
int n3 = angel3.nextInt();
//this is just telling how much degrees the user had in total if they didnt match up to triangle standards
This should get you started.
package triangle;
import java.util.Scanner;
public class triangle {
public static void main(String[] args){
//explaining what the program is going to do
System.out.println("You will be able to enter 3 angles to equal the sum of a triangle,\n");
System.out.println("this automated program will tell you if the angle you entered is isoceles, eqilateral or scalene");
//creating input 1,2,3 for user
Scanner s = new Scanner(System.in); // Reading from System.in
String line;
int [] angles = new int [3];
int count = 0;
do {
System.out.print("Enter angle degree number " + (count+1) + ": ");
line = s.nextLine();
while (true ) {
try {
angles[count] = Integer.parseInt(line);
System.out.println("You entered " + angles[count]);
count++;
break;
} catch (NumberFormatException e ) {
System.out.println("Invalid number: try again: ");
line = s.nextLine();
}
}
} while (count < 3);
}
}
You have a simple issue.. You just use one Scanner for the code in main method.
package triangle;
import java.util.Scanner;
public class traingle {
public static void main(String[] argc){
System.out.println("You will be able to enter 3 angles to equal the sum of a triangle,\nthis automated program will tell you if the angle you entered is issosoliese, eqilateral or scalene");
Scanner angle1 = new Scanner(System.in);
System.out.println("Enter angle degree number 1: ");
int n = angle1.nextInt();
System.out.println("Enter angle degree number 2: ");
int n2 = angel2.nextInt();
System.out.println("Enter angle degree number 3: ");
int n3 = angel3.nextInt();

Trying to combine multiple programs together

I am trying to take 3 different programs I have created and put them under a single class. My professor has stated I must do this and I have no clue on how to. I am not looking for a hand out here, just some how I can do this quickly and efficiently. I am also trying to figure out how to call from the same scanner for each program or if I should just make multiple ones.
import java.util.Scanner;
public class AssignmentOneFahrenheit {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello, I can convert Fahrenheit to Celsius!");
System.out.println("Please enter the degrees Fahrenheit you want converted.");
double degreesF;
double degreesC;
Scanner keyboard = new Scanner(System.in);
degreesF = keyboard.nextDouble(); //Allows user to input decimal number
keyboard.close();
System.out.println("The temperature in Degrees Celsius is: ");
degreesC = 5*(degreesF - 32)/9;
System.out.printf("%.2f", degreesC);
}
import java.util.Scanner;
public class AssignmentOneHate {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a line containing 'hate'.");
String text = keyboard.nextLine();
System.out.println("I have changed that line to read: ");
System.out.println(text.replaceFirst("hate", "love"));
keyboard.close();
}
import java.util.Scanner;
public class AssignmentOneVerticalDisplay {
public static void main(String[] args) {
// TODO Auto-generated method stub
int userInput;
System.out.println("Please enter a 4 digit integer.");
Scanner keyboard = new Scanner(System.in);
userInput = keyboard.nextInt();
System.out.println(userInput / 1000);
userInput = userInput % 1000;
System.out.println(userInput / 100);
userInput = userInput % 100;
System.out.println(userInput / 10);
System.out.println(userInput % 10);
keyboard.close();
}
}
I basically just copied and pasted 2 programs I created. If anybody can help guide me in the correct direction here that would be great.
You can use the Double.parseDouble(String string); function together with a try-Catch to check if it was a number or a string in the input.
(...)
String text = keyboard.nextLine();
try {
//We try and assume that it is a number
Double number = Double.parseDouble(text);
/**
* Do stuff with the number like in the 1st program
*/
}
catch (NumberFormatException e)
{
//The input turned out not to be a number.
/**
* Do stuff here with the string like the 2nd program
*/
}
Am not really certain what your trying to accomplish, but if it's really necessary you combine all three classes together try using Java Inner Classes
I think that your professor is looking for a more object oriented solution. You can create a class that contains the three programs as separated methods like this
import java.util.scanner;
public class AssignmentScanner {
public double convertToCelsius() {
Scanner keyboard = new Scanner(System.in);
double degreesF = keyboard.nextDouble();
keyboard.close();
return 5*(degreesF - 32)/9;
}
public String replaceHate() {
Scanner keyboard = new Scanner(System.in);
String text = keyboard.nextLine();
String replacedText = text.replaceFirst("hate", "love");
keyboard.close();
return replacedText;
}
public int oneVerticalDisplay() {
Scanner keyboard = new Scanner(System.in);
int userInput = keyboard.nextInt();
System.out.println(userInput / 1000);
userInput = userInput % 1000;
System.out.println(userInput / 100);
userInput = userInput % 100;
System.out.println(userInput / 10);
System.out.println(userInput % 10);
keyboard.close();
}
}
You still need to create a main program that use this object like this:
public class AssignmentMain {
public static void main(String[] args) {
AssignmentScanner assignmentScanner = new AssignmentScanner();
System.out.println("Hello, I can convert Fahrenheit to Celsius!");
System.out.println("Please enter the degrees Fahrenheit you want converted.");
double degreesC = assignmentScanner.convertToCelsius();
System.out.println("The temperature in Degrees Celsius is: ");
System.out.printf("%.2f", degreesC);
System.out.println("Please enter a line containing 'hate'.");
String replacedText = assignmentScanner.replaceHate();
System.out.println("I have changed that line to read: ");
System.out.println(replacedText);
System.out.println("Please enter a 4 digit integer.");
assigmentScanner.oneVerticalDisplay();
}
}
This way your main program only knows about the AssignmentScanner and its three methods. This make the main program easier to read and maintain. There is still room for improvement but i think it's OK for a first approach.

Categories