Where should scanner go in this program? - java

I'm working on a program that takes the input of two numbers and then does some different calculations. I have my TwoNumbers class with several different methods to calculate sum, distance, average, etc.
Should I put the scanner in this class, or should I put it in the Main method?
I know this is really basic but I've only been learning java for a couple weeks and I'm having a hard time finding how this should be done/how to get the input to correlate to my instance variables and firstNumber and secondNumber
public class TwoNumbers{
private double firstNumber;
private double secondNumber;
public double getSum()
{
double sum = firstNumber + secondNumber;
return sum;
}
public double getDifference()
{
double difference = firstNumber - secondNumber;
return difference;
}
public double getProduct()
{
double product = firstNumber - secondNumber;
return product;
}
public double getAverage()
{
double average = (firstNumber + secondNumber) / 2;
return average;
}
public double getDistance()
{
double distance = Math.abs(firstNumber - secondNumber);
return distance;
}
public double getMax()
{
double maximum = Math.max(firstNumber, secondNumber);
return maximum;
}
public double getMin()
{
double minimum = Math.min(firstNumber, secondNumber);
return minimum;
}
}

Each class should follow the single responsibility principle. Your TwoNumbers class should only work with the double numbers and perform operations on them, nothing more. Providing the double numbers for this class should be in the client, and also the ability to provide the numbers, which means that the client may define the Scanner or another way to provide the data.

The class you have displayed, the TwoNumbers class, should have no user input in it as it should encapsulate the concept of two numbers and two numbers only. It should be written in such a way that it can be used with a Scanner program or with a GUI program without having to change it. Thus the UI should be in main or in another class.

You would probably want to make a constructor for the class, and within the constructor pass the variables you want. This would mean that you get your input from somewhere else, IE the main method or some other means.
public TwoNumbers(double num1, double num2){
firstNumber = num1;
secondNumber = num2;
}

For example:
public double getSum(firstnumber, secondnumber) // <-- you need pass in the value
{
double sum = firstNumber + secondNumber;
return sum;
}
/*
* somewhere in the main or another method you can delare the first number / 2nd number
* for example:
*/
public void static main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter first number");
firstnumber = input.nextInt();
System.out.println("enter first number");
secondnumber = input.nextInt();
}
After that all you need to do is just calling the method you want to pass the number to.

You need to have a constructor in TwoNumbers:
public class TwoNumbers {
private double firstNumber;
private double secondNumber;
public TwoNumbers(double firstNumber, double secondNumber){
this.firstNumber = firstNumber;
this.secondNumber = secondNumber;
}
}
Then in some other Class, you can have your scanner:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter firstNumber");
double firstNumber = scanner.nextDouble();
System.out.println("Enter secondNumber");
double secondNumber = scanner.nextDouble();
TwoNumbers obj = new TwoNumbers(firstNumber, secondNumber);
//Call methods from TwoNumbers
}

Really the code would work if you put the scanner in the main class or in the TwoNumbers class. The best practice way of doing this would be to place your scanner and any other input/output code in you main class, and the processing/calculation code in another class. Which one you choose will be based on your application, but most of the time you will have the scanner in the main class. So...
public class Driver {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
String s;
while((s = in.nextLine()) != "stop"){
TwoNumbers.sum(Double.parseDouble(s.split(" ")[0]), Double.parseDouble(s.split(" ")[1]));
}
in.close();
}
}
public class TwoNumbers{
public static double sum(double a, double b){
return a+b;
}
}
}

Related

Java Method isn't implementing what it is supposed to

Hey everyone very new to coding!
So I was trying to make a calculator program using object oriented programming in Java however when I try to call my method for addition it doesn't do the job entirely so what am I doing wrong here ?
Thanks in advance :)
import java.util.Scanner;
public class CalculatorOOP {
Scanner input = new Scanner(System.in);
public static double currentValue;
public double valueInput;
public CalculatorOOP(double valueTyped){
valueTyped = currentValue;
}
public double addToValue(){
System.out.println("Type the value you want to add:");
double valueToAdd = input.nextDouble();
double valueAfterAddition = CalculatorOOP.currentValue + valueToAdd;
return valueAfterAddition;
}
public double substractToValue(){
System.out.println("Type the value you want to substract:");
double valueToSubstract = input.nextDouble();
double valueAfterSubstraction =
CalculatorOOP.currentValue - valueToSubstract;
return valueAfterSubstraction;
}
public double multiplyValue(){
System.out.println("Type the factor value:");
double factor = input.nextDouble();
double valueAfterMultiplication = CalculatorOOP.currentValue * factor;
return valueAfterMultiplication;
}
public double divideValue(){
System.out.println("Type the divisor value:");
double divisor = input.nextDouble();
double valueAfterDivision = CalculatorOOP.currentValue / divisor;
return valueAfterDivision;
}
}
import java.util.Scanner;
public class Main {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.println("Type a value:");
double valueInput = input.nextDouble();
CalculatorOOP obj = new CalculatorOOP(valueInput);
System.out.println("Enter the calculation option (1, 2, 3, or 4):");
int optionEntered = input.nextInt();
switch (optionEntered){
case 1 : obj.addToValue();
}
}}
Here this is what I get when running the code however it is not performing the addition it is just asking for values
Type a value:
2
Enter the calculation option (1, 2, 3, or 4):
1
Type the value you want to add:
4
Process finished with exit code 0
Your addToValue method seems to perform the addition correctly and return the calculated sum. Where you call the method, you are not picking up the return value — so it just disappears, is discarded. I believe you want to assign it back into CalculatorOOP.currentValue and/or print it. Either from inside the method or from where you called it.

interest rate java confusion with private static doubles [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
alright so i have already made a working compound interest rate program. but now for this program i have to re write the program using more methods. using
private static double FVCALC(..)
and
private static double validate(........)
i dont quite understand how i need to do this. the current code i have only lets me input the 3 values of interest rate and it stops. is it because of the private mehtods? im not sure what to do and i have searched for 3 days now.
bottom line is. my code is not working the way i want it to.
public class interest_rate
{
static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
double i;
double n;
double FVCalc;
double PV;
System.out.print("please enter value for n (years): ");
n = input.nextInt();
System.out.print("please enter interest rate: ");
i=input.nextDouble();
System.out.print("please enter Present Value: ");
PV = input.nextDouble();
}
private static double validate (double upLimit, double lowLimit, double PV)
{
upLimit=100000.00;
lowLimit=0.00;
while(PV>upLimit|| PV<lowLimit)
{
System.out.print("please enter value between "+upLimit+" and "+lowLimit);
System.out.print("please enter PV");
PV=input.nextDouble();
}
return PV;
}
private static double FVCalc(double PV, double i, double n, double FV)
{
FV = PV*Math.pow(1+(i/100), n);
return(FV);
}
}
First, you need to call the methods in main.
Secondly, you cant pass in PV, then reassign it and expect the value to update.
For example..
private static double validate (double upLimit, double lowLimit, double PV)
You need to call this in main like so
PV = 0.0; // some double value
double validated = validate(0,100000); // return the value, don't pass it in
And remove these lines in that method because overriding parameters is typically bad.
upLimit=100000.00;
lowLimit=0.00;
Next, add a field for your values that you want to use throughout the class.
public class InterestRate
{
static double pv , fvCalc;
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
}
And remove these lines in main and use those two class variables instead
double FVCalc;
double PV;
Additionally, I don't see a reason to store fvCalc as a variable. You can just calculate it
private static double fvCalc(double pV, double i, double n)
{
return pV*Math.pow(1+(i/100), n);
}
i believe i have figured it out. and i made it pretty. excuse the notes. i wanted to keep them there to see what i did wrong. thanks all.
public class interest_rate
{
static double pV , fvCalc, i, n;
static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
double validated;
double calculated;
double i;
double n;
//double fV;
//double pV1;
System.out.print("please enter value for n (years): ");
n = input.nextInt();
System.out.print("please enter interest rate: ");
i=input.nextDouble();
validated = validate(0,100000);
System.out.println("pV is validated and equal to: "+validated);
calculated= fvCalc(validated,i,n);
System.out.println("your calulation for interest is: "+calculated);
}
private static double validate(double upLimit, double lowLimit) {
double pV;
System.out.print("please enter pV");
pV=input.nextDouble();
while(pV<upLimit|| pV>lowLimit)
{
System.out.print("please enter value between "+upLimit+" and "+lowLimit);
System.out.println("please enter pV");
pV=input.nextDouble();
}
return pV;
}
private static double fvCalc(double pV, double i, double n)
{
double fV;
fV=pV*Math.pow(1+(i/100), n);
return fV;
}
}

(Beginner Java): Constructor no arguments?

I am trying to make a simple program that takes the average of three number, but I get an error saying that says
"constructor average in class average cannot be applied to given types;
required: no arguments
found: int,int,int "
Here is my code:
public class ave {
public static void main(String args[]) {
average object = new average(3,4,6);
}
}
and here is my constructor code
public class average {
public double takeaverage(double first, double second, double third) {
double ave = (first + second + third)/3;
System.out.println(ave);
return ave; }
}
The constructor's name should be same as the class name and feature no return type.
Try the following:
public class ave {
public static void main(String args[]) {
Average object = new Average(3,4,6);
}
}
public class Average {
public Average(double first, double second, double third){
double ave = (first + second + third)/3;
System.out.println(ave);
}
}
and if you don't want to change the code of Class Average, then just call the method from that class as following:
public class ave {
public static void main(String args[]) {
Average object = new Average();
double Avg = object.takeaverage(3,4,6);
}
}
public class Average {
public double takeaverage(double first, double second, double third) {
double ave = (first + second + third)/3;
System.out.println(ave);
return ave; }
}
The constructor must have the same name as the class.
You have to create:
public average(double a, double b, double c)
Actually the only constructor existing in the class is the constructor without arguments, that is created automatically.
You have not defined a constructor method that receives these arguments (3, 4, 6).
You have to create a constructor method like this:
public class average {
public double result
public average(int a, int b, int c){
this.result=this.takeaverage(double(a),double(b),double(c))
}
public double takeaverage(double first, double second, double third) {
double ave = (first + second + third)/3;
System.out.println(ave);
return ave; }
}
If you only want to take the average of 3 numbers, you can do it without creating an average object. I have shown it below:
import java.util.*;
public class Ave {
public static void main(String[] args){
double number1, number2, number3;
Scanner console = new Scanner(System.in);
System.out.println("Enter number 1:");
number1 = console.nextDouble();
System.out.println("Enter number 2:");
number2 = console.nextDouble();
System.out.println("Enter number 3:");
number3 = console.nextDouble();
double average = (number1 + number2 + number3)/3;
System.out.println("The average is: " + average);
}
}
The above program asks the user for 3 numbers and prints out their average. Note that it is still a bit redundant. You can also modify it to ask for average of any numbers, like shown below:
import java.util.*;
public class Ave {
public static void main(String[] args){
int howMany;
double sum = 0.0;
double number, average;
Scanner console = new Scanner(System.in);
System.out.println("How many numbers do you want to take average of:");
howMany = console.nextInt();
int count = 1;
while(count <= howMany){
System.out.println("Enter number " + count);
number = console.nextDouble();
sum += number;
count++;
}
average = sum/howMany;
System.out.println("The average is: " + average);
}
}
You can modify the programs to take the average of 3 numbers without asking the user too, where the doubles number1, number2, and number3 will be given numbers (hard-coded, which is not a good practice in general).
You have created the "takeaverage" method but haven't invoked it. And maybe you should use a setter or pass the three numbers using the constructor and initialize and then only call the "takeaverage" method for a double value and get the average assigned to that double variable.
You need to use the default constructor and create the object from "average" class. Below is a very simple solution :
public class average {
public double takeaverage(double first, double second, double third) {
double ave = (first + second + third)/3;
System.out.println(ave);
return ave;
}
}
//main class
public class ave{
public static void main(String []args){
average object = new average();
object.takeaverage(3,4,6);
}
}

How do I use a function involving integers?

We have an assignment in class to create a greatest common divider (gcd) program using functions. I missed out on the lesson where we learned how to properly use them. I finished the part that actually does the division but I don't know how to separate it into a function and have it work. I'd like to have the input in the main class and the process in function.
This is what I have, it does not work when I run it
package gcd.function.java.program;
import java.util.Scanner;
/**
*
* #author sarah_000
*/
public class GCDFunctionJavaProgram {
public static void main(String[] args) {
int num1;
int num2;
int div;
Scanner input = new Scanner(System.in);
System.out.print("Enter your first number: ");
num1 = input.nextInt();
System.out.print("Enter your second number: ");
num2 = input.nextInt();
System.out.printf("The GCD is %d ", div);
}
public static void GCDFunction() {
if(num1 > num2)
div = num2;
else div = num1;
while((num1 % div!= 0)||(num2 % div != 0))
{
div --;
}//end of while loop
}
}
Any tips or help you can give to me will be greatly appreciated, I'm very new
You declare two parameters and modify the return type in your GCDFunction like this:
public static int GCDFunction(int num1, int num2)
You are currently trying to access the variables in the main method but are out of scope.
Also, you never actually call your GCDFunction
Think of it like passing functions in math. The GCDFunction() has to receive the numbers into the function so we do
public static void GCDFunction(int num1, int num2)
That also lets Java know the type it is, type int. And your java variables are scoped inside of the functions so you have to print the output in the function that created the variable in your scenario.
So once you have that function set up to receive the variables and output after processing, you call the function in the main with a
GCDFunction(num1, num2);
Where num1 and num2 are the variables that have your integers stored in.
The end result after a little rearranging looks like this.
import java.util.Scanner;
public class GCDFunctionJavaProgram {
public static void main(String[] args) {
int num1;
int num2;
Scanner input = new Scanner(System.in);
System.out.print("Enter your first number: ");
num1 = input.nextInt();
System.out.print("Enter your second number: ");
num2 = input.nextInt();
GCDFunction(num1, num2);
}
public static void GCDFunction(int num1, int num2) {
int div;
if(num1 > num2){
div = num2;
}
else{ div = num1;}
while((num1 % div!= 0)||(num2 % div != 0))
{
div --;
}//end of while loop
System.out.printf("The GCD is %d ", div);
}
Trying to give you a example of how the code should be to take in variable number of parameters.
public int gcd(Integer... numbers) {
int gcd = 1;
int miNNumber=Collections.min(Arrays.asList(numbers));
boolean isDivisible;
for(int i=2; i<=miNNumber;i++) {
isDivisible=true;
for(Integer eachNumber : numbers) {
if(eachNumber%i!=0) {
isDivisible=false;
break;
}
}
if(isDivisible) {
gcd=i;
}
}
return gcd;
}
You can call it
gcd(10, 200, 400);
or
gcd(10, 200, 400, 4000, 40);

Display method to display results from other methods Java

I'm trying to show the results from GCD and LCM using the display method. I try accessing the numbers object in the display method and it cannot resolve the symbol. Everything works with the code I'm just not sure how else I can access the numbers object inside the display method. Any help is greatly appreciated! Thanks
public static void main(String[] args) {
TwoNumbers numbers = getNumbers();
System.out.println(numbers.getNum1());
System.out.println(+numbers.getNum2());
GCD(numbers.getNum1(), numbers.getNum2());
System.out.println(GCD(numbers.getNum1(), numbers.getNum2()));
LCM(numbers.getNum1(), numbers.getNum2());
System.out.println(LCM(numbers.getNum1(), numbers.getNum2()));
}
public static TwoNumbers getNumbers(){
int num1;
int num2;
Scanner input = new Scanner(System.in);
System.out.println("Enter your first number: ");
num1 = input.nextInt();
System.out.println("Enter your second number");
num2 = input.nextInt();
return new TwoNumbers(num1, num2);
}
public static int GCD(int a, int b) {
if (b==0) return a;
return GCD(b,a%b);
}
public static long LCM(int a, int b) {
return a * (b / GCD(a, b));
}
public static void display(){
}
TwoNumbers numbers = getNumbers();
If you are trying to access numbers of main method. Then you can not do that, scope of numbers is only inside main method. You can not access it directly from other method.
Either you pass the numbers as parameter to display method or you can declare numbers as class level static variable.
public static void display(TwoNumbers numbers){
//Now you have numbers inside display
}
Moreover, you do not need to call the GCD and LCM method again from the display. You can simply pass result of both methods to display method from main.
TwoNumbers gcdNumbers = GCD(numbers.getNum1(), numbers.getNum2());
display(gcdNumbers);
TwoNumbers lcmNumbers = LCM(numbers.getNum1(), numbers.getNum2());
display(lcmNumbers);

Categories

Resources