static reference error with class methods java [duplicate] - java

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

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

I can't input a double number

enter code here package com.company;
import java.util.Locale;
import java.util.Scanner;
public class Main {
public static double min (double n1 , double n2 , double n3)
{
double minNumber = n1;
if (minNumber>n2)
minNumber=n2;
if (minNumber>n3)
minNumber=n3;
return minNumber;
}
public static double max (double n1 , double n2 , double n3){
double maxNumber = n1;
if (maxNumber<n2)
maxNumber=n2;
if (maxNumber<n3)
maxNumber=n3;
return maxNumber;}
public static void main(String[] args) {
while (true) {
Scanner input = new Scanner(System.in);
System.out.println("Enter 1 if you want minimum \nEnter 2 if you want maximum \nEnter 3 if you want to stop the program");
byte Enter = input.nextByte();
if (Enter==1) {
Scanner in = new Scanner(System.in);
System.out.println("Enter first number");
double x = in.nextInt();
System.out.println("Enter second number");
double y = in.nextInt();
System.out.println("Enter third number");
double z = in.nextInt();
double min = min(x,y,z);
System.out.println("the minimum number is :" + min);
}
else if (Enter == 2) {
Scanner in = new Scanner(System.in);
System.out.println("Enter first number");
double x = in.nextInt();
System.out.println("Enter second number");
double y = in.nextInt();
System.out.println("Enter third number");
double z = in.nextInt();
System.out.println("the maximum number is :" + max(x, y, z));
}
else if (Enter==3){
break;
}
else System.out.println("Enter again");
}
}
}
/* output is :
Enter 1 if you want minimum
Enter 2 if you want maximum
Enter 3 if you want to stop the program
1
Enter first number
12.3
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at com.company.Main.main(Main.java:39)
Process finished with exit code 1
You need write in.nextDouble() instead in.nextInt()

New to programming, need slight assistance

So basically, my program compiles correctly and is working. However, when the program calculates the simple interest, it displays the incorrect value. Say it should be displaying $470, instead it is only printing out 4.7, sorry for the bad explanation, could anyone figure out why this is happening?
import java.io.*;
import java.util.Scanner;
import java.io.File;
//import java.nio.file.*;
//import java.nio.file.Paths;
public class BankInterest {
public static void main (String [] args) throws IOException
{
/* TASK 1: Declare variables */
Scanner user_input = new Scanner (System.in);
boolean exit;
int accountType;
double balance;
double principal;
// double userInterest;
double r;
double r2;
int year;
String commBank = ("commbank.txt");
String westPac = ("westpac.txt");
/*Check if the expected command line is provided */
if (args.length < 1) {
/* Display the Usage */
System.out.println("Usage: java BankInterest interestRateFileName");
/* Programs quits with an error code */
System.exit(-1);
}
/* TASK 2: Read interest rates from a file */
String filename = (args[0]);
Scanner textReader = new Scanner(new File(filename));
r = textReader.nextDouble();
r2 = textReader.nextDouble();
System.out.println(r);
System.out.println(r2);
/* TASK 3: Take user input - Which Account */
Scanner keyboard = new Scanner (System.in);
System.out.println("Which Account: ");
System.out.println("1 - Savings");
System.out.println("2 - Term Deposits");
accountType = keyboard.nextInt();
if (accountType == 1) {
accountType = 1;
}
else if (accountType == 2) {
accountType = 2;
}
/* TASK 4: Take user input - Principal and Period */
Scanner input = new Scanner (System.in);
System.out.println("Principal: ");
principal = keyboard.nextDouble();
System.out.println("Years: ");
year = keyboard.nextInt();
/* TASK 5: Calculate balance for the chosen account type */
if (accountType == 1) {
double userBalance = principal * Math.pow((1 + r/100), year);
double userInterest = userBalance-principal;
System.out.println("");
System.out.println("The Compound Interest is: " + userBalance);
System.out.println("The total amount of Interest earned:" + userInterest);
}
else if (accountType == 2) {
double userBalance = (principal * r2 * year) / 100;
double userInterest = userBalance-principal;
System.out.println("");
System.out.println("The Simple Interest is: " + userBalance);
System.out.println("The total amount of Interest earned:" + userInterest);
}
}
}
I guess it's just because you are giving the interest rate as percent. I mean for 20% interest rate the value in your file is 0.20. And in your calculation you divide it by 100 again. Either change your interest value to 20 or get rid of the division by 100 section in your calculation.
Firstly formula is wrong. The right one is (assuming that r2 represents %):
double userInterest = (principal * r2 * year) / 100;
double userBalance = principal + userInterest;

why does my scanner(system.in) run twice

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.

Java Averaging Program

Write a class called Average that can be used to calculate average of several integers. It should contain the following methods:
 A method that accepts two integer parameters and returns their average.
 A method that accepts three integer parameters and returns their average.
 A method that accepts two integer parameters that represent a range. Issue an error message and return zero if the second parameter is less than the first one. Otherwise, the method should return the average of the integers in that range (inclusive).
I am totally new to Java and programming, this has me completely lost! Here's what I've tried.
import java.util.Scanner;
public class Average {
public static void main(String[] args) {
double numb1, numb2, numb3;
System.out.println("Enter two numbers you'd like to be averaged.");
Scanner keyboard = new Scanner(System.in);
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
}
public double average (int num1, int num2) {
return (num1 + num2) / 2.0;
}
public double average (int num1, int num2, int num3)
{
return (num1 + num2 + num3) / 3.0;
}
}
The program doesn't go past getting the values from the user. Please help!
You have to actually call your methods.
Just place
Average avg = new Average();
System.out.println("The average is: " + avg.average(numb1, numb2));
at the end of your main method.
Alternatively you can make the methods static:
public static double average (int num1, int num2) {
return (num1 + num2) / 2.0;
}
More info on constructors and static.
It looks like your not actually printing out the results. Try the following.
System.out.print(average(numb1, numb2));
Let's detail what you did there.
public static void main(String[] args) {
//Create variables numb1, numb2 & numb3
double numb1, numb2, numb3;
System.out.println("Enter two numbers you'd like to be averaged.");
//Read standard input (keyboard)
Scanner keyboard = new Scanner(System.in);
//Retrieve first input as an int
numb1 = keyboard.nextInt();
//Retrieve second input as an int
numb2 = keyboard.nextInt();
}
Then your two next methods compute for two or three given integers their average.
The main method is the first method called during your program execution. The jvm will execute everything inside. So it will declare the three doubles, read two values from keyboard and then end.
If you want to compute the average of numb1 & numb2 using your method, you have to create an object Average and call your average method like this
public static void main(String[] args) {
//Create variables numb1, numb2 & numb3
double numb1, numb2, numb3;
System.out.println("Enter two numbers you'd like to be averaged.");
//Read standard input (keyboard)
Scanner keyboard = new Scanner(System.in);
//Retrieve first input as an int
numb1 = keyboard.nextInt();
//Retrieve second input as an int
numb2 = keyboard.nextInt();
//Declare the average value
double average;
//Create an average instance of the class average
Average averageObject = new Average();
//Call your average method
average = averageObject.average(numb1,numb2);
//Print the result
System.out.println("Average is : " + average);
}
Everything in Java is object (read about Object Oriented Programming).
Writing your class "Average" defines how your object is structured. It has attributes (characteristics) and methods (actions). Your Average object has no attributes. However it has two methods (average with two and three numbers) acting on integers.
However your class is just the skeleton of your object. You need to create an object from this skeleton using the keyword new as :
Average averageObject = new Average();
Sincerely
public class Marks {
int roll_no;
int subject1;
int subject2;
int subject3;
public int getRoll_no() {
return roll_no;
}
public void setRoll_no(int roll_no) {
this.roll_no = roll_no;
}
public int getSubject1() {
return subject1;
}
public void setSubject1(int subject1) {
this.subject1 = subject1;
}
public int getSubject2() {
return subject2;
}
public void setSubject2(int subject2) {
this.subject2 = subject2;
}
public int getSubject3() {
return subject3;
}
public void setSubject3(int subject3) {
this.subject3 = subject3;
}
public void getDetails(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the marks of subject1");
this.subject1 = sc.nextInt();
System.out.println("Enter the marks of subject2");
this.subject2 = sc.nextInt();
System.out.println("Enter the marks of subject3");
this.subject3 = sc.nextInt();
System.out.println("Enter the roll number");
this.roll_no = sc.nextInt();
}
public int getAverage(){
int avg = (getSubject1() + getSubject2() + getSubject3()) / 3;
return avg;
}
public void printAverage(){
System.out.println("The average is : " + getAverage());
}
public void printRollNum(){
System.out.println("The roll number of the student is: " + getRoll_no());
}
public static void main(String[] args){
Marks[] e1 = new Marks[8];
for(int i=0; i<2; i++) {
System.out.println("Enter the data of student with id:");
e1[i] = new Marks();
e1[i].getDetails();
e1[i].printAverage();
}
System.out.println("Roll number details");
for(int i=0; i<2; i++){
e1[i].printRollNum();
}
}
}
If you'd like your program to find the average you need to include a call to that method in your main method.
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
System.out.println("The average of " + numb1 + " and " + numb2 + " is " + average(numb1,numb2);
}
you need to call the methods that you have written after you accept the input.
...
System.out.println("Enter two numbers you'd like to be averaged.");
Scanner keyboard = new Scanner(System.in);
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
System.out.println(average (int numb1 , int numb2 ))
...
You probably want to provide a menu of options for the user to select to determine which method to call
System.out.println("Select one option");
System.out.println("1. Enter two numbers you'd like to be averaged.");
System.out.println("2. Enter the 3 numbers you want averaged.");
System.out.println("3. Enter the number Range you want averaged.");
and based on that answer you can determine which method to call
After the access specifier (public) and before the return type (double) place the Java keyword static. You shouldn't worry about what this means right now.
You have to use bitwise operators.
average of int a and b can be calculated as
avg= (a >> 1) + (b >> 1) + (((a & 1) + (b & 1)) >> 1);
The main method will only execute what it is asked to. If you want the average methods to be executed, you will have to create an object, pass the required variable and call the methods from the main method. Write the following lines in the main method after accepting the input.
Average avrg = new Average();
System.out.println("The average is: " + avrg.average(numb1, numb2, numb3));
Write only numb1 and numb2 if you want to average only two numbers.

Categories