Java Overloaded Methods - java

I am trying to use one file to create a menu in the command window. The user selects from those menu options. They are prompted to enter a number. The number is passed to two overloaded methods which determine if the number is an integer or a float. After the calculation is done the result is printed to the screen and the menu reappears. Here is the code from my two files.
MyMathOpsTest class:
import java.util.Scanner; // import Scanner class
public class MyMathOpsTest
{
//method to pause until a key is pressed
public static void pause()
{
try
{
System.out.print("Press <Enter> to continue...");
System.in.read();
}
catch (Exception e)
{
System.err.printf("Error %s%c\n",e.getMessage(),7);
}
}//end pause
public static void main( String args[] )
{
//variables to capture keyboard input
Scanner keyBd = new Scanner( System.in );
char selection;
//int selection;
do{//display menu
System.out.println( "1. Square a Number");
System.out.println( "2. Cube a Number");
System.out.println( "3. Raise a Number to a Power");
System.out.println( "4. Maximum of Three Numbers");
System.out.println( "5. Minimum of Three Numbers");
System.out.println( "6. Exit");
System.out.print( "Selection[1-6]: " );
//get menu selection
selection = keyBd.next().charAt(0);
//selection = keyBd.nextInt();
//process menu selection
switch (selection){
case '1':
MyMathOpsTest.squareTheNumber();
pause();
break;
case '2':
MyMathOpsTest.cubeTheNumber();
pause();
break;
case '3':
MyMathOpsTest.raiseTheNumber();
pause();
break;
case '4':
MyMathOpsTest.maximumNumber();
pause();
break;
case '5':
MyMathOpsTest.minimumNumber();
pause();
break;
case '6':
//recognize as valid selection but do nothing
break;
default :
System.out.printf("%c\n",7);
System.out.println("Invalid Selection");
}//end switch
}while( selection != '6');
} // end method main
public static void squareTheNumber()
{
}
public static void cubeTheNumber()
{
}
public static void raiseTheNumber()
{
}
public static void maximumNumber()
{
MyMathOps.maximum();
}
public static void minimumNumber()
{
}
} // end class MyMathOpsTest
MyMathOps class:
import java.util.Scanner;
public class MyMathOps
{
public static int square(x:Integer):Integer
{
}
public static double square(x:Double):Double
{
}
public static int cube(x:Integer):Integer
{
}
public static double cube(x:Double):Double
{
}
public static int maximum(x:Integer, y:Integer, z:Integer):Integer
{
// create Scanner for input from command window
Scanner input = new Scanner( System.in );
// obtain user input
System.out.print( "Enter three integer values separated by spaces: ");
int numberl = input.nextInt();
// read first integer
int number2 = input.nextInt();
// read second double
int number3 = input.nextInt();
// read third double
// determine the maximum value
int result = maximum( numberl, number2, number3 );
// display maximum value
System.out.println( "Maximum is: " + result );
} // end method maximum
public static double maximum(x:Double, y:Double, z:Double):Double
{
// create Scanner for input from command window
Scanner input = new Scanner( System.in );
// obtain user input
System.out.print( "Enter three floating-point values separated by spaces: ");
number1 = input.nextDouble();
// read first double double
number2 = input.nextDouble();
// read second double
double number3 = input.nextDouble();
// read third double
// determine the maximum value
double result = maximum( numberl, number2, number3 );
// display maximum value
System.out.println( "Maximum is: " + result );
} // end method maximum
public static int minimum(x:Integer, y:Integer, z:Integer):Integer
{
// create Scanner for input from command window
Scanner input = new Scanner( System.in );
// obtain user input
System.out.print( "Enter three integer values separated by spaces: ");
int numberl = input.nextInt();
// read first integer
int number2 = input.nextInt();
// read second double
int number3 = input.nextInt();
// read third double
// determine the minimum value
int result = minimum( numberl, number2, number3 );
// display minimum value
System.out.println( "Minimum is: " + result );
} // end method minimum
public static double minimum(x:Double, y:Double, z:Double):Double
{
// create Scanner for input from command window
Scanner input = new Scanner( System.in );
// obtain user input
System.out.print( "Enter three floating-point values separated by spaces: ");
number1 = input.nextDouble();
// read first double double
number2 = input.nextDouble();
// read second double
double number3 = input.nextDouble();
// read third double
// determine the minimum value
double result = minimum( numberl, number2, number3 );
// display minimum value
System.out.println( "Minimum is: " + result );
} // end method minimum
} // end class MyMathOps
This code is a combination of code I type myself and example code from my text book. This will not compile for me in jGRASP. I get these errors.
MyMathOps.java:10: <identifier> expected
public static int square(x:Integer):Integer
^
MyMathOps.java:96: ')' expected
} // end method minimum
^
2 errors
----jGRASP wedge: exit code for process is 1.
----jGRASP: operation complete.
What am I doing wrong here? I have spent hours working on this and reading in my textbook. If I do not get this right. I will get a bad grade. I need to get a good grade in this class so I can get into a top notch Computer Science University. Thanks for your help.
In the unlikely event that my instructor or any administrator from Salt Lake Community College ever comes across this question, let me make my intentions clear. This question is posted in the greatest spirit of academic honesty. I ask this question to seek general advice and help in understanding the proper way to use the Java programming language. I in no way use the work of others and represent it as my own work. I use the answers provided here as a general aid in my understanding. I do all my own work and do not copy work provided by people answering my question.

The lines like this are not valid Java syntax:
public static int square(x:Integer):Integer
public static int maximum(x:Integer, y:Integer, z:Integer):Integer
...
This looks like a UML or pseudo-code syntax. "x:Integer" is "language-agnostic" notation that means that x is an Integer type (which maps to an int or Integer object in Java). The ":Integer" at the end means that the method returns an Integer type, which you are doing correctly already.
Try changing all your method declarations to look like this:
public static int square(int x) // Or "Integer x" if you want to use the Integer class, rather than the primitive int
public static int maximum(int x, int y, int z)
....

I am guessing that you are used to Pascal (or a derivative).
public static int square(x:Integer):Integer
in Java that is
public static int square(int x)
Also since the code is inside of "MyMathOpsTest" you do not need to prefix the method calls with "MyMathOpsTest.".
Also, why call it "MyMathOps" instead of "MathOperationsTest"? Of course it is yours - it doesn't be long to me or anyone else! Pick names that have meaning, try to avoid shorthands like "Ops", unless it is common for the field you are working in (URL is a good one, "Ops" isn't).
And now for the generl programming advice for a beginner:
write a single line of code
get that line of code to compile
once that line of code compiles work on the next one
get the next line of code to compile
keep doing that until the program is done.
There is no point in making the same mistakes over and over again - all you get good at is making mistakes, and that isn't much fun.
So to get you started...
Step 1:
public class MathOperations
{
public static int maximum(final int x, final int y, final int z)
{
}
}
(compile the above code)
Step 2:
public class MathOperations
{
public static int maximum(final int x, final int y, final int z)
{
final Scanner input;
}
}
(compile the above code)
Step 3:
public class MathOperations
{
public static int maximum(final int x, final int y, final int z)
{
final Scanner input;
intput = new Scanner(System.in);
}
}
(compile the above code)
and then keep going one line at a time. Once you get the hang of it you can do more than one line, but at the start, doing it one line at a time will show you immediately when you make a mistake. Make sure that you fix ALL of the mistakes before you move on to the next line.

Also, at the end of the first method pause(), you need another curly brace:
public static void pause()
{
try
{
System.out.print("Press <Enter> to continue...");
System.in.read();
}
catch (Exception e)
{
System.err.printf("Error %s%c\n",e.getMessage(),7);
}
}<-- this one is missing in yours
Hope this helps!

I don't know what the point of the exercise is - the math ops, the overloading, or the menu. But I'd recommend that you start over with these as your basis. At least they compile and run:
public class MyMathOps
{
public static int square(int x)
{
return x*x;
}
public static double square(double x)
{
return x*x;
}
public static int cube(int x)
{
return x*x*x;
}
public static double cube(double x)
{
return x*x*x;
}
public static int maximum(Integer... values)
{
Integer maxValue = Integer.MIN_VALUE;
for (Integer value : values)
{
if (value.compareTo(maxValue) > 0)
{
maxValue = value;
}
}
return maxValue;
}
public static double maximum(Double... values)
{
Double maxValue = Double.MIN_VALUE;
for (Double value : values)
{
if (value.compareTo(maxValue) > 0)
{
maxValue = value;
}
}
return maxValue;
}
public static int minimum(Integer... values)
{
Integer minValue = Integer.MAX_VALUE;
for (Integer value : values)
{
if (value.compareTo(minValue) < 0)
{
minValue = value;
}
}
return minValue;
}
public static double minimum(Double... values)
{
Double minValue = Double.MIN_VALUE;
for (Double value : values)
{
if (value.compareTo(minValue) < 0)
{
minValue = value;
}
}
return minValue;
}
}
and the test class (simplified):
public class MyMathOpsTest
{
public static void main(String args[])
{
Integer [] intValues = { 1, 2, 3, };
Double [] doubleValues = { 11.0, 14.0, -6.0 };
for (Integer value : intValues)
{
System.out.println("value : " + value);
System.out.println("squared: " + MyMathOps.square(value));
System.out.println("cubed : " + MyMathOps.cube(value));
System.out.println("min : " + MyMathOps.minimum(intValues));
System.out.println("max : " + MyMathOps.maximum(intValues));
}
for (Double value : doubleValues)
{
System.out.println("value : " + value);
System.out.println("squared: " + MyMathOps.square(value));
System.out.println("cubed : " + MyMathOps.cube(value));
System.out.println("min : " + MyMathOps.minimum(doubleValues));
System.out.println("max : " + MyMathOps.maximum(doubleValues));
}
}
}
When this is done running, you'll know that your methods are correct. Spare yourself the difficulties of reading in values on the first try.

Related

How can I pass the return value from this method to another class using Java?

I created a method that returns a row of arrays via user input. I managed to display the set of inputted number on the same class using System.out.println by assigning each value in userDigits.
My question is, how can I pass the same value in another class?
public class LottoTicket extends Ticket {
public int NUM_DIGITS = 5;
public int[] userDigits = new int[NUM_DIGITS];
#Override
public void buyTicket() {
Scanner input = new Scanner(System.in);
int number = 0;
double amount = 0;
System.out.println("-------=======LOTTO TICKET SCREEN=======--------");
System.out.println("");
System.out.println("There are three Types (Prima, Ambo and Terro)");
System.out.print("Please select one (P, A, T): ");
String lotteryOption = input.next();
switch (lotteryOption) {
case "P": {
break;
}
case "A": {
break;
}
case "T": {
amount = getAmount(amount);
getUserData(userDigits);
int ticketSold;
ticketSold = +1;
int tik = ticketSold +1;
System.out.println(amount);
System.out.println("Your numbers are: " + userDigits[0] + " "
+ userDigits[1] + " " + userDigits[2] + " " + userDigits[3]
+ " " + userDigits[4] + " ");
System.out.println("Ticket/s Sold: " + tik);
System.out.println("Thank you for playing");
Ticket.pressAnyKeyToContinue();
LotteryApplication.loginScreen();
break;
}
default: {
System.out.println("Invalid Input. Please try again.");
System.out.println("");
buyTicket();
break;
}
}
}
#Override
public double getAmount(double amount) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter amount of money: ");
amount = input.nextDouble();
//input.close();
return amount;
}
#Override
public int getUserData(int[] userInput) {
Scanner input = new Scanner(System.in);
System.out.print("Choose a number from 1 to 90: ");
userDigits[0] = input.nextInt();
System.out.print("Choose a number from 1 to 90: ");
userDigits[1] = input.nextInt();
System.out.print("Choose a number from 1 to 90: ");
userDigits[2] = input.nextInt();
System.out.print("Choose a number from 1 to 90: ");
userDigits[3] = input.nextInt();
System.out.print("Choose a number from 1 to 90: ");
userDigits[4] = input.nextInt();
//key.close();
//Returns last value of array
return userDigits[4];
}
//public int userDigits[];
public static void printTicket(){
// System.out.println(getUserData.userDigits[4]);
// for (int i = 0; i < array.length)
}
}
Well, in this case, since you defined userDigits as public, you can do it easily - it is accessible to any class that has a visibility to your instance of LottoTicket. With the current setup you could do something like this:
// you need to instantiate LottoTicket somewhere in your app
LottoTicket ticket = new LottoTicket();
// get the input from user
ticket.buyTicket();
// at this point you can access the numbers and pass them to some other method like this
checkNumbers(ticket.userDigits);
The example posted above needs you to provide a method checkNumbers that has, for example, the following signature:
public void checkNumbers(int[] numbers) {
// the comparison code goes here...
Also, this is somewhat unrelated to your question, but I'd like to point out two issues with your current code:
defining class fields as public is done rather rarely, more common approach is to define these as private and provide methods for getting/setting the field values; this restricts the operation on these fields to only those you allow - having public field allows anyone who has a visibility to that field to perform basically any operations, which is usually not what you want
you call buyTicket() from default in case user didn't select valid lottery type; in extreme cases this could lead to StackOverflowError - better approach would be to use a loop that keeps asking user for input until a valid one is provided
Hope this helps at least a bit.
You can easily pass input array to method of another class arguments.
class PassValue{
public static void display(int[] elements){
Anotherclass obj= new Anotherclass();
obj.display2(elements);
}
}
class Anotherclass{
public void display2(int[] values){
do whatever you want
}
}

How to invoke multiple method signatures within a main method?

So I have three required codes I have already figured out. They are the codes for a quadratic formula, codes for an ISBN checker, and a code for Newtons Method. I'm supposed to make a menu with options 1, 2, and three each containing these codes respectively.
I guess this means I need different methods for this right? I was never really taught - I was told we had to always put in public class void main (String []args){ for everything, and I was just told there were variations to this?
For Quadratics formula, the information is : Return - void and parameters of three doubles, Newtons method: Return - double and parameters of 1 double, and ISBN checker: Return: Boolean and Parameters of 1 string. I don't really understand the parameters thing either. Help would be appreciated. I know this aesthetically looks horrible, but because my codes for now are relatively short I just edit the style when I' done. I know a lot of things are wrong in this too and I've spent time trying to figure them out.
import Java.util.Scanner;
public class HelperMethod{
public static void main(String[] args) {
Scanner userInputScanner = new Scanner (System.in);
System.out.println ("You have three options. press one for the quadratic Formula, 2 for the newtons Method, and 3 for an ISBN checker.");
int input = userInputScanner.nextInt();
if (input = 1){
}else if (input = 2) {
private class NewtonsMethod {
public static void NewtonsMethod(String[] args) {
Scanner userInputScanner = new Scanner (System.in);
double guess, fX, fPrimeX, newGuess;
System.out.println ("enter in a value give");
guess = userInputScanner.nextDouble();
System.out.println ("Your guess is " + guess);
while (true) {
fX = (6 * Math.pow (guess,4)) - (13 * Math.pow (guess,3)) - (18 * Math.pow (guess,2)) + (7 * guess) + 6;
fPrimeX = (24 * Math.pow (guess,3)) - (39 * Math.pow (guess,2)) - 36 * guess + 7;
newGuess = guess - (fX / fPrimeX);
System.out.println ("A possible root is " + newGuess);
if (Math.abs(newGuess - guess) < 0.00001) {
break;
} else {
guess = newGuess;
}
}
System.out.println ("The root is: " + newGuess);
}
}
}else{
private class BookNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char f;
int e, g, h;
int result = 0;
System.out.println ("Pleas enter a thirteen digit number");
String a = scanner.nextLine();
if (a.length() == 13){
for (int i = 0; i < 13; i ++) {
f = a.charAt(i);
e = Character.digit(f, 10);
if (i % 2 == 0) {
g = e * 1;
result = result + g;
} else {
g = e * 3;
result = result + g;
}
}
System.out.println ("The added sum of you numbers is " + result);
if (result % 10 == 0) {
System.out.println ("This combination IS a ISBN number");
} else {
System.out.println ("This is NOT an ISBN number");
}
} else {
System.out.println ("This combination is not thirteen digits long");
}
}
}
}
}
}
First of all, right now you're setting input to 1 in your first if statement. To compare input to 1 instead, use the == operator, i.e. if (input == 1) {.... Secondly, you don't really need to use classes, you can simply have methods NewtonsMethod(), BookNumber() etc. and run them when the input is correct.
public class HelperMethod{
public static void main(String[] args) {
int input;
//Handle user input
switch (input) {
case 1:
newtonsMethod();
break;
case 2:
bookNumber();
break;
case 3:
anotherMethod();
break;
}
}
public static void newtonsMethod() {
//Your code
}
public static void bookNumber() {
//Your code
}
public static void anotherMethod() {
//Your code
}
}
Methods should never be inside one another. That is what classes are for. A method is an element within a class. For example, in your case your class was named "HelperMethod". Your methods need to begin after the main method's code block is closed with a curly brace "}"
as an example
// This would be your main method.
public static void main(String args[]) {
// Your method is CALLED here.
someMethod();
{
// Then this is where your next method would start.
public static void someMethod() {
// Your code for the method of course goes here.
}
Of course you need your class setup and needed imports ABOVE the main method but you have that setup correctly already. With this setup, it makes it easy to call public methods that are in other classes. Your private methods are not really needed unless you intend to use more than one class, at which point you will need to import that class and then call the method like so
SomeClass.someMethod();

Output error resulting from logic error when determining percentage based on incremental while loop

I have created a simple class which calculates the win/loss percentage and returns the amount of necessary consecutive wins to obtain the desired win/loss percentage of the given input from the user, based on the given values of wins, loss, and desired win/loss. However, whilst running the program, I notice the output gives an exceedingly large number in the place of what should be a relatively small number (the number of wins needed). I am not certain what error I have made that created this, but I'm certain it's relative to the while loop located in my howManyToWinLoss() method, or perhaps some error I've made in the tester class's output. At any rate, they are both located below, and I appreciate the assistance:
public class WinLossCalculator
{
private int win;
private int loss;
private int totalGames;
private double desiredWinLoss;
private double winLoss;
private int gamesToDWL;
public WinLossCalculator(int w, int l, double dwl)
{
win = w;
loss = l;
totalGames = w + l;
desiredWinLoss = dwl;
}
public double winPercent()
{
return winLoss = (double)win/(double)totalGames;
}
public double lossPercent()
{
return (double)loss/(double)totalGames;
}
public int howManyToWinloss()
{
int x = 0;
while(winLoss < desiredWinLoss)
{
winLoss = (win+x)/(win+x+loss);
if(winLoss < desiredWinLoss)
{
x++;
}
}
return gamesToDWL = x;
}
}
and
import java.util.*;
public class WinLossTester
{
public static void main(String []args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter the amount of matches you've won: ");
int wins = in.nextInt();
System.out.print("\nEnter the amount of matches you've lost: ");
int losses = in.nextInt();
System.out.print("\nEnter your desired match win percentage (eg. 75.4): ");
double desiredWLP = in.nextDouble();
System.out.println();
WinLossCalculator one = new WinLossCalculator(wins, losses, (desiredWLP / 100));
one.winPercent();
one.howManyToWinloss();
System.out.printf("Win percentage: %6.1f", (one.winPercent()*100));
System.out.print("%");
System.out.printf("\nLoss percentage: %5.1f", (one.lossPercent()*100));
System.out.print("%");
System.out.println("\nVictories required to reach desired W/L percent (without loss): " + one.howManyToWinloss());
}
}
Additionally--I feel as though my tester class's output section is a little ugly, might anyone have any suggestions concerning formatting or cleaning up the code in the output section?
Ok, apparently it has to do with me not casting the first line in my for loop to double like this winLoss = (double)(win+x)/(double)(win+x+loss); I don't know why that broke it, but, that's why it was broken.

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

Print my recursive factorial result

I need to print my final answer for my method. However, it shows the whole calculation to the end! How can I eliminate the process to get only the result?
Instead, call your method from another one and only print the final value:
System.out.println(getFactorial(5));
If you really need to do it from inside the method you can create a sort of "trampoline" method, like so:
private static int getFactorial(int userInput) {
int fact = _getFactorial(userInput);
System.out.println(fact);
return fact;
}
private static int _getFactorial(int userInput) {
// real implementation
}
This is a recursive function call, which is executed in all the cases without special condition checks.
printing from another method is a good option.
private static int getFactorial(int userInput){
int ans = userInput;
if(userInput >1 ){
ans*= (getFactorial(userInput-1));
}
return ans;
}
// New method;
private static void printFactorial(int userInput){
System.out.println("The value of " + userInput + "! is " + getFactorial(userInput));
}
// Calculate the factorial value
private static int getFactorial(int userInput){
int ans = userInput;
if(userInput >1 ){
ans*= (getFactorial(userInput-1));
}
return ans;
}
and print outside the function
System.out.println("The value of "+ b +"! is "+ getFactorial(b));
Print only once, when you got the final answer.
Since you don't like the idea of just returning a value and printing from the caller code, you can add a "print the answer" flag as an argument:
// Calculate the factorial value
private static int getFactorial(int value, boolean print){
if (value > 1) {
value *= getFactorial(value-1, false);
if (print) {
System.out.println("The value of "+ b +"! is "+ value);
}
}
return value;
}
Personally, though, I'd prefer the "trampoline method" of Jake King's answer.
// Calculate the factorial value
private static int getFactorial(int userInput){
int ans = userInput;
if(userInput >1 ){
ans*= (getFactorial(userInput-1));
//System.out.println("The value of "+ b +"! is "+ ans);
}
return ans;
}
public static void main(String[] args)
{
int ans;
//get input
ans = getFactorial(input);
System.out.println("The value of "+ b +"! is "+ ans);
}

Categories