Java: Calling variables of user input from one method to another - java

I'm currently modifying a previous Java program that computes quadratic formula type math problems by breaking parts of my code down into methods and calling those methods to complete the same task. Currently I'm stuck on creating a method to calculate the discriminant in the numerator. As assigned, I'm supposed to have one method that receives user input for the a,b, and c values, but I'm not sure how to get those values from one method into the next that is supposed to use those values in calculations.
My instructor wants us to have the a b and c variables input into an array and I know the way it is now is a pretty manual way of putting values into an array, but should still work for this purpose.
Here is what I have thus far and thanks for reading.
EDIT: I've started again from scratch, I can't figure out how to properly return information from my methods so that the next can use it. I keep getting method argument not applicable errors. Any ideas?
import java.util.*;
public class QuadraticMethods {
public static void main(String[] args){
getValues();
calcDisc(userInput);
}
public static double[] getValues() {
double[] userInput;
userInput = new double[3];
Scanner kbd = new Scanner(System.in);
System.out.println("Fourth Assignment by MyNameHere");
System.out.println("Welcome to the quadratic formula computation tool.");
System.out.println("This tool will solve problems in the form of: a^x + bx + c.");
System.out.println("Please enter the values you would like for a, b, and c.");
for (int i = 0; i < userInput.length; i++) {
userInput[i] = kbd.nextDouble(); }
double aValue = userInput[0];
double bValue = userInput[1];
double cValue = userInput[2];
/*
System.out.println(aValue);
System.out.println(bValue);
System.out.println(cValue);
*/
return userInput;
}
public static double calcDisc(double[] userInput) {
double aValue = userInput[0];
double bValue = userInput[1];
double cValue = userInput[2];
double radicalValue = (Math.pow(bValue, 2) - (4*aValue*cValue));
System.out.println(radicalValue);
return radicalValue;
}
}

To get your current code to work, only a small change is required:
public static void main(String[] args) {
double[] userInput = getValues();
calcDisc(userInput);
}
Further these assignments are not actually used.
public static double[] getValues() {
// ...
double aValue = userInput[0];
double bValue = userInput[1];
double cValue = userInput[2];
// ...
}
Some other improvements could be:
The result should not be printed by the method that calculates it. You already declared the method the right way by returning the value. Now you should use the returned value and print the result in the calling method.
public static void main(String[] args) {
double[] userInput = getValues();
double radicalValue = calcDisc(userInput);
System.out.println(radicalValue);
}
// ...
public static double calcDisc(double[] userInput) {
double aValue = userInput[0];
double bValue = userInput[1];
double cValue = userInput[2];
double radicalValue = (Math.pow(bValue, 2) - (4 * aValue * cValue));
return radicalValue;
}
Printing the banner should probably not be mixed with requesting the user input. Imagine, you would want to repeat the read/evaluate/print cycle:
public static void main(String[] args) {
while (true) {
double[] userInput = getValues();
double radicalValue = calcDisc(userInput);
System.out.println(radicalValue);
}
}
would print the banner text every time. Isolating the responsibilities enables you to alter behaviour without affecting unrelated code.
public static void main(String[] args) {
printBanner();
while (true) {
double[] userInput = getValues();
double radicalValue = calcDisc(userInput);
System.out.println(radicalValue);
}
}
private static void printBanner() {
System.out.println("Fourth Assignment by MyNameHere");
System.out.println("Welcome to the quadratic formula computation tool.");
System.out.println("This tool will solve problems in the form of: a^x + bx + c.");
}
Scanner should be closed after use. Java 7 try with resources will do that for you.
public static double[] getValues() {
double[] userInput;
userInput = new double[3];
try (Scanner kbd = new Scanner(System.in)) {
System.out.println("Please enter the values you would like for a, b, and c.");
for (int i = 0; i < userInput.length; i++) {
userInput[i] = kbd.nextDouble();
}
}
return userInput;
}

Related

How do I use the return value from a method in another method different from the calling method?

I'm kinda new to to java and stumbled on a problem that needs me to do currency conversion declaring different methods for:
getting amount, getting conversion rate, doing the actual conversion and printing the outcome of the conversion
import java.util.*;
public class Conver {
public static void main(String[] args){
amountToConvert();
exchangeRate();
convert();
}
public static double amountToConvert() {
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount you wish to convert...");
double amount = input.nextDouble();
return amount;
}
public static double exchangeRate(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the currency you wish to convert from... ");
String initialCurrency = input.next();
System.out.println("Enter the currency you wish to convert from... ");
String finalCurrency = input.next();
System.out.println("How many " + initialCurrency + " makes one " + finalCurrency + "?");
double rate = input.nextDouble();
return rate;
}
public static double convert(){
int x = amount*rate;
return x;
}
public void printResult(){
System.out.println(x);
}
}
Learn to use parameters in the methods. Change the convert() method so that it looks like this:
public static double convert(double amount, double rate){
int x = amount*rate;
return x;
}
In the method above, double amount and double rate are the parameters. Use variables to help pass in parameters to convert() in the main method:
public static void main(String[] args){
double amount1 = amountToConvert();
double rate1 = exchangeRate();
double result = convert(amount1, rate1);
printResult(result);
}
Hope this helps!
Pass returned values to the method convert:
import java.util.*;
public class Conver {
public static void main(String[] args){
double amount = amountToConvert();
double rate = exchangeRate();
double result = convert(amount, rate);
printResult(result);
}
public static double amountToConvert() {
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount you wish to convert...");
double amount = input.nextDouble();
return amount;
}
public static double exchangeRate(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the currency you wish to convert from... ");
String initialCurrency = input.next();
System.out.println("Enter the currency you wish to convert from... ");
String finalCurrency = input.next();
System.out.println("How many " + initialCurrency + " makes one " + finalCurrency + "?");
double rate = input.nextDouble();
return rate;
}
public static double convert(double amount, double rate){
double x = amount * rate;
return x;
}
public void printResult(double x){
System.out.println(x);
}
}
Also, don't use double for money!
First off, you need to change the "receiving method" so that it takes an argument. A method like:
public static double convert() {}
that needs to take in a value for amount and rate, needs to have those added to the method signature:
public static double convert (double amount, double rate) {}
Putting the two comma separated values inside of the parens means that this method takes two values, doubles, as arguments. This makes those values available to use inside of that method.
Now that you have a method that can take the required arguments, you need to actually use that method in your code. When calling this method, you start out the same as with others:
convert(
but then you need to add in the arguments you are using:
double amount = amountToConvert();
double rate = exchangeRate();
convert(rate, amount);
If you want to avoid creating those two additional variables in main(), you can actually call those methods inside of your new method:
convert(amountToConvert(), exchangeRate());

How to divide two numbers without using the "/" symbol?

I wrote some code pertaining to the problem but I just can't get it to work. After I input the two numbers, the program gets stuck in an infinite loop. Is there any way this method could work or is it outright wrong?
import java.util.Scanner;
public class Arithmetic {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter the numerator and denominator respectively : ");
double a = input.nextDouble();
double b = input.nextDouble();
double c;
for(c=0;;c+=0.000000000001){
if(b*c==a){
break;
}
}
System.out.print(c);
}
}
I can think of one way without a slash:
double c = a * Math.pow(b, -1);
You can also substitute a Unicode escape for the / character.
double c2 = a \u002f b;
You can also convert to BigDecimals, use the divide method, and then convert the quotient back to a double.
double c3 = new BigDecimal(a).divide(new BigDecimal(b)).doubleValue();
You can use exponent and logarithm becasue exp(log(a)-log(b)) =a/b
public class HelloWorld{
public static void main(String []args){
System.out.println(Math.pow(10,Math.log10(a)-Math.log10(b)));
}
}
You need to add checks for a>0 and b>0 and make logic so it work for all a,b but this you can do yourself.
For example if b = 0
Throw error
if a<0 and b>0
System.out.println(-Math.pow(10,Math.log10(-a)-Math.log10(b)));
etc.
System.out.println("The result is : " + (a * Math.pow(b, -1)));
public class Num {
public static void main(String[] args) {
double num, den, res;
num = 10;
den = 2;
res = Math.pow(Math.E, (Math.log(num)-Math.log(den)));
System.out.println(res);
}
}

How to store a double in an array incrementally

this is my first post and I hope someone can help. I have been struggling for ages to understand the problem I have and it looks as though I have done everything right yet problem persists. I have written a simple account program and would like to store the new balance after each transaction into an array index. From printing out balance I can see that it is adding and subtracting properly, however it is updating every single array index with the new balance rather than each incremental index. Can anyone spot my mistake. Thank you for any help with this.
Richard
public class TestAppAccount {
public static void main(String args[]) {
int count = 0;
do {
AppAccount.transaction();
AppAccount.storeBalance();
AppAccount.printBalance();
count++;
//Account1.printBalance2();
} while (count <= 100);
}
public class AppAccount {
public static double[] currentBalance = new double[100];
static Scanner keyboard = new Scanner(System.in);
static double balance;
static int transaction;
public static void transaction() {
System.out.println(" Press 1 to add funds, 2 to withdraw ");
transaction = keyboard.nextInt();
if (transaction == 1) {
System.out.println("Enter an amount to add ");
double amount = keyboard.nextInt();
double newBalance = balance + amount;
balance = newBalance;
} else
{
System.out.println("Enter an amount to withdraw");
double amount = keyboard.nextInt();
double newBalance = balance - amount;
balance = newBalance;
}
}
public static void storeBalance() {
for (int i = 0; i < currentBalance.length; i++) {
currentBalance[i] = balance;
}
}
public static void printBalance() {
System.out.println("Balance: " + balance);
System.out.println("Balance: " + currentBalance[3]);//testing by printing 3rd index
}
}
Your storeBalance() method is iterating through the entire array and updating the values. If you want to only update one value, you'll need to keep track of where you've written up to and only write to the location one after that.
e.g.
Instead of
public static void storeBalance() {
for (int i = 0; i < currentBalance.length; i++) {
currentBalance[i] = balance;
}
}
try this:
static int lastStored = 0;
public static void storeBalance() {
currentBalance[lastStored++] = balance;
}
for (int i = 0; i < currentBalance.length; i++) {
currentBalance[i] = balance;
}
That for loop is setting every value in the array to the value of balance. If each index is supposed to be a different account I would suggest passing an index to each function.
The problem is here:
public static void storeBalance() {
for (int i = 0; i < currentBalance.length; i++) {
currentBalance[i] = balance;
}
}
That for-loop will step through every element in the array, one by one, and will overwrite each value with whatever the current balance is.
There are a couple of ways you could fix this. My first reaction would be to create a variable that tells you the next index to write to:
static int nextIndex = 0;
and then storeBalance() would look like this:
public static void storeBalance() {
currentBalance[nextIndex] = balance;
nextIndex++;
}
You issue is you do a for loop and update every single value. You just want to update once when storeBalance() is called. Keep track of i as a static variable:
static int i = 0;
Then do this:
public static void storeBalance() {
if(i >= currentbalance.length)
i = 0;//restart value so it doesnt do array out of bounds
currentbalance[i] = balance;//update a single value
i++;//increment for next call
}
Make sure you do the out of bounds check. That's what the other answers are forgetting to check. Of course this will over write old values, so you can choose to do something else (what ever seems fitting for your requirements).
Stop pretending that java is c.
Java is not c.
Java likes objects.
Use objects.
Avoid arrays.
Here is some code:
// start Main.java file
public class Main
{
public static void main(String args[])
{
int count = 0;
do
{
AppAccount.transaction();
AppAccount.storeBalance();
AppAccount.printBalance();
count += 1;
}
while (count <= 4);
}
}
// start AppAccount.java file
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class AppAccount
{
private static List<Double> currentBalanceList = new ArrayList<Double>();
private static Scanner keyboard = new Scanner(System.in);
private static double runningBalance;
private static int transaction;
public static void printBalance()
{
System.out.println("Running Balance: " + runningBalance);
}
public static void storeBalance()
{
currentBalanceList.add(runningBalance);
}
public static void transaction()
{
double amount;
System.out.println(" Press 1 to add funds, 2 to withdraw ");
transaction = keyboard.nextInt();
if (transaction == 1)
{
System.out.println("Enter an amount to add ");
amount = keyboard.nextDouble();
runningBalance = runningBalance + amount;
}
else
{
System.out.println("Enter an amount to withdraw");
amount = keyboard.nextDouble();
runningBalance = runningBalance - amount;
}
}
}

How to compare enum value to scanner input in java for switch statement

Im' trying to get user input if he presses "a", he can do the average, calls in average method if he types in "s", he uses the sum method.
Im new to enums so im experimenting. I made an enum that stores a,b and am trying to compare it's values to user input using scanner.
I could be using if statements and forget the whole enum thing but i want to know how it works.
thanks.
public enum RecursionEnum {
s, a
}
main class:
import java.util.*;
public class Recursion {
static RecursionEnum enumtest;
public static void yn() {
Scanner boges = new Scanner(System.in);
System.out.println("Enter a for average or s for sum");
String answer = boges.nextLine();
switch (enumtest) {
case a:
average();
case s:
sums();
}
}
public static void main(String[] args) {
yn();
}
public static int sums() {
int i = 0;
int j = 0;
int sum = i + j;
return sum;
}
public static double average() {
Scanner avgs = new Scanner(System.in);
System.out.println("Enter total number of numbers; ");
double tnum = avgs.nextDouble();
double[] nums = new double[(int) tnum];
double sum = 0;
for (int i = 0; i < tnum; i++) {
System.out.println("Enter number " + (i + 1) + " : ");
nums[i] = avgs.nextDouble();
sum += nums[i];
}
System.out.println(" ");
double avg = sum / tnum;
return avg;
}
}
This is the output:
Enter a for average or s for sum
a
Exception in thread "main" java.lang.NullPointerException
at com.towerdef.shit.Recursion.yn(Recursion.java:14)
at com.towerdef.shit.Recursion.main(Recursion.java:26)
Enumerable types have a synthetic static method, namely valueOf(String), which will return an enum instance matching the input, if it exists. Note that the input is case-sensitive in this case. Trim is used to deal with potential extraneous whitespace.
You can switch on that:
public static void yn() {
Scanner boges = new Scanner(System.in);
System.out.println("Enter a for average or s for sum");
String answer = boges.nextLine();
switch (RecursionEnum.valueOf(answer.trim())) {
case a:
average();
case s:
sums();
}
}
Of course, on Java 7 and higher, you can switching on strings. You may thus use:
public static void yn() {
Scanner boges = new Scanner(System.in);
System.out.println("Enter a for average or s for sum");
String answer = boges.nextLine();
switch (answer.trim()) {
case "a":
average();
break;
case "s":
sums();
break;
}
}

using scanner class to average numbers in java

I am using a scanner class to average numbers together. I am using a method to do the averaging. I do not want the program to run if there are more than 20 args. I cant seem to get this to work. I am very new at java and trying to learn.
I appreciate any help I can get. Thanks!
import java.util.Scanner;
class programTwo {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
double x = 0.00d;
if (args != null) {
System.out.println ("Enter your numbers to be averaged. Remember no more than 20!:");
x = scan.nextInt();
if (x <= 21) {
System.out.println("Please do not add more than 20 numbers");
}
} else {
}
}
public double average(double [] values) {
double average = 0.0;
if ((values != null) && (values.length > 0)) {
for (double value : values) {
average += value;
}
average /= values.length;
}
return average;
}
}
Just run a while loop that breaks when 20 "args" is met or until a break like -1 is entered. Then if you are taking double values, you should use x = scan.nextDouble(). You also do not have a place where you are inserting the values into your array. At the end of your while loop you could put x into an array of doubles.
private double x;
private double Foo[] = new Foo[20];
private int this = 0; //Your counter
while(this < 20 && x != -1)
{
x = scan.nextDouble();
Foo[this++] = x;
}
Then carry out your public double Average by adding up the values in the array and dividing by (double)this
Here is a solution (cleaning up a lot of your code as well) that gets all the numbers on one line after the start of the program:
import java.util.Scanner;
class programTwo {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
double values[] = new double[20];
int count = 0;
System.out.println ("Enter your numbers to be averaged. Remember no more than 20!:");
String inputs = scan.nextLine();
scan = new Scanner(inputs); // create a new scanner out of our single line of input
while(scan.hasNextDouble())
{
if(count == 20)
{
System.out.println("You entered too many numbers! Fail.");
return;
}
values[count] = scan.nextDouble();
count += 1;
}
System.out.println("Your average is: " + average(values, count));
}
public static double average(double [] values, int count) {
double average = 0.0;
for (double value : values) {
average += value;
}
average /= count;
return average;
}
}
I got thinking you might want to use the args that are passed to main, since you use a null check, so you want to run your program like this:
java programTwo num1 num2 num3 num4 num5
etc. If that's the case, we have another solution:
class programTwo {
public static void main (String[] args) {
if(args.length > 20)
{
System.out.println("You entered too many numbers! Fail.");
return;
}
double values[] = new double[args.length];
for(int i=0; i< args.length; ++i)
values[i] = Double.valueOf(args[i]);
System.out.println("Your average is: " + average(values));
}
public static double average(double [] values) {
double average = 0.0;
for (double value : values) {
average += value;
}
average /= values.length;
return average;
}
}
The args != null check is unnecessary. One way to accomplish what you want is to accept numbers while the scanner has a next number (scanner.hasNext() perhaps) and break if the number of inputs thus far is less than 20. Since the number of double numbers is unknown, you're better off using an ArrayList.
List<Double> doubles = new ArrayList<Double>();
and calling the add method on doubles
doubles.add(x);
Then pass this to a method that averages the values in the arraylist.

Categories