How to invoke multiple method signatures within a main method? - java

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

Related

How do I call these methods? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
I'm new to Java, and I'm trying to call the private methods I've set up earlier, but with no success. It's a simple program that generates random numbers and display messages. Anyone wants to lend a hand?
Sorry if the code is bad, I've only been learning this for less than month.
import java.util.Random;
import java.util.Scanner;
public class project2 {
private static int rollDie() {
int num_random2 = (int) (Math.random() * 6) + 1;
System.out.println("Die 2: " + num_random2);
return num_random2;
}
private static int rollDie2() {
int num_random = (int) (Math.random() * 6) + 1;
System.out.println("Die 1: " + num_random);
return num_random;
}
private static void printDice(int num_random, int num_random2) {
total = num_random + num_random2;
System.out.println("Total: " + total);
}
int total = num_random + num_random2;
private static void printSpecialMessage(int total) {
String message1 = "Snake Eyes";
String message2 = "Box cars";
if (total = 12) {
System.out.println(message2);
} else if (total = 2) {
System.out.println(message1);
} else {
break;
}
}
public static void main(String[] args) {
System.out.println("Welcome to my app!");
System.out.println();
System.out.println("Dice Roller");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
do {
rollDie();
rollDie2();
printDice();
printSpecialMessage();
System.out.print("Roll Again? (y/n): ");
choice = sc.next();
System.out.println();
}
while (choice.equalsIgnoreCase("y"));
}
}
I keep getting these errors:
The method printDice(int, int) in the type project2 is not applicable for the arguments ()
The method printSpecialMessage(int) in the type project2 is not applicable for the arguments ()
at project2.main(project2.java:51)
At this point I'm about to just give up. Hopefully someone can help me out!
Few errors in your code I found.
if (total = 12) should be replaced with if (total == 12).
Make sure you always use two equals in if condition. One = is for assignment and two = for condition check.
printDice() -> The signature is not matching. Pass two values to this function.
total should be declared as static.
printSpecialMessage -> The signature is not matching. Pass one values to this function.
I suggest you start with writing simple code and then gradually go ahead with writing complex codes.
Your code does not compile. The following code does. Compare it with your code.
import java.util.Scanner;
public class Project2 {
private static int rollDie() {
int num_random2 = (int) (Math.random() * 6) + 1;
System.out.println("Die 2: " + num_random2);
return num_random2;
}
private static int rollDie2() {
int num_random = (int) (Math.random() * 6) + 1;
System.out.println("Die 1: " + num_random);
return num_random;
}
private static void printDice(int num_random, int num_random2) {
int total = num_random + num_random2;
total = num_random + num_random2;
System.out.println("Total: " + total);
}
private static void printSpecialMessage(int total) {
String message1 = "Snake Eyes";
String message2 = "Box cars";
if (total == 12) {
System.out.println(message2);
}
else if (total == 2) {
System.out.println(message1);
}
}
public static void main(String[] args) {
System.out.println("Welcome to my app!");
System.out.println();
System.out.println("Dice Roller");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
do {
int one = rollDie();
int two = rollDie2();
printDice(one, two);
printSpecialMessage(one + two);
System.out.print("Roll Again? (y/n): ");
choice = sc.next();
System.out.println();
} while (choice.equalsIgnoreCase("y"));
}
}
The things I changed (in no particular order).
Method printSpecialMessage requires an argument. You call that method from method main without an argument. Hence the following [compiler] error.
The method printSpecialMessage(int) in the type Project2 is not applicable for the arguments ()
Similarly for method printDice. That method requires two arguments but you call it with no arguments, which gives the following [compiler] error.
The method printDice(int, int) in the type Project2 is not applicable for the arguments ()
You need to save the value returned from method rollDie in a variable. You also need to save the value returned from method rollDie2 in another variable. Then you call method printDice with those two variables as arguments. In the code above I named the variables one and two.
break is not used in if statements. See method printSpecialMessage.
When comparing integers, use == (double equals sign). Again see method printSpecialMessage.
The following line of code is not inside the body of a method. It belongs in method printDice.
int total = num_random + num_random2;
Here is a sample run of the above code.
Welcome to my app!
Dice Roller
Die 2: 5
Die 1: 3
Total: 8
Roll Again? (y/n): y
Die 2: 6
Die 1: 3
Total: 9
Roll Again? (y/n): n

I have one variable but Java considers them as two

I have initiated the variable 'answer' in the near header of the class.
Later on when, a random number within an entered range has been generated, that same variable gets a new different value (due to the random generator). But as you can see, the variable 'answer' is indicated in two different colors (blue vs light brown), and as you expect, the routines that I have made are therefore not working. Somehow answer is not equal to answer. What did I do wrongly???? (unfortunately here you don't see the difference in colors).
In eclipse the color of 'answer' at the very top static int answer = 0; is BLUE.
But the one int answer = ThreadLocalRandom.current().nextInt(1, userinput); is GREY
Here's my code:
package Package1;
import java.util.concurrent.ThreadLocalRandom;
import java.util.Scanner;
public class test6KOPIE
{
static int numberofattempts = 0;
static int maxnummerofattemptsallowed = 5;
static int answer = 0;
public static void main(String[] args)
{
if (answer == 0)
{
Scanner maxinput = new Scanner(System.in);
System.out.println("Under which number do you want to guess");
int userinput = maxinput.nextInt();
int answer = ThreadLocalRandom.current().nextInt(1, userinput);
System.out.println(answer);
main(args);
}
else if (numberofattempts < maxnummerofattemptsallowed)
{
Scanner higherlower = new Scanner(System.in);
System.out.println("Higher or Lower");
int digit = higherlower.nextInt();
if (answer == digit)
{
System.out.println("very well");
}
else {
if (answer > digit )
{
++numberofattempts;
System.out.println("Higher, you have " +(maxnummerofattemptsallowed - numberofattempts)+" attempt(s) left)");
System.out.println(numberofattempts);
main(args);
}
else
{
++numberofattempts;
System.out.println("Lower, you have " +(maxnummerofattemptsallowed - numberofattempts)+" attempt(s) left)");
main(args);
}
}
higherlower.close();
}
else {
System.out.println("Maximum number of attempts used, the answer was" +answer);
}
}
This is because you are re-initializing your answer variable by retyping int before it. If you simply want to reassign the value, the line should be:
answer=ThreadLocalRandom.current().nextInt(1, userinput);

How can I use this method in conjunction with another method?

I am trying to finish this code off and get it working, but I cannot figure out why it is not working, the program is using methods to compute a grade from an exam mark input and pring out a pass/fail string. I have been putting the program together well until now, the last method won't function or compile. The copiler says:
error: cannot find symbol
gradeMessage(examGrade);
^
However, as my program shows, the method is there. So what am I doing wrong? A word of warning, as this is an assessment, the main method must have the four statements only, nothing else.
import java.util.Scanner;
public class GradeClassifier
{
public static void main(String[] args) {
titleString();
int examMark = getMark();
examGrade(examMark);
gradeMessage(examGrade);
}
/**
Prints title of the program
#param title the string with dashed underline
*/
public static void titleString() {
// Print Title
System.out.println("Grade Classifier\n****************");
}
/**
Gets the exam mark for the user
#param getMark from scanner
#return the mark
*/
public static int getMark() {
// Declare and create a Scanner to read input values
Scanner in = new Scanner(System.in);
System.out.println("");
System.out.print("Enter exam mark :> ");
int mark = in.nextInt();
return mark;
}
/**
Determine the grade
#param mark
#return string grade
*/
public static String examGrade(int mark) {
// Print out grade
String grade;
if (mark <= 100 && mark >=70) {
grade = "A";
} else if (mark <= 69 && mark >= 60) {
grade = "B";
} else if (mark <= 59 && mark >= 50) {
grade = "C";
} else if (mark <= 49 && mark >= 40) {
grade = "D";
} else {
grade = "F";
}
return grade;
}
/**
Display grade message
#param result to find pass or fail
*/
public static void gradeMessage(String result) {
// Compute if grade leads to pass or fail
String message;
if (result == "F") {
System.out.println("Unfortunately, you have a Grade F, so you have"
+ " failed this exam");
} else {
System.out.println("Congratulations, you are awarded a Grade"
+ message + " Pass");
}
}
}
First of all I noticed in your last method gradeMessage you create a String variable message and try to print it out rather than trying to print out the result parameter passed into your method. For example your last method should look like this:
public static void gradeMessage(String result) {
// Compute if grade leads to pass or fail
if (result == "F") {
System.out.println("Unfortunately, you have a Grade F, so you have failed this exam");
}
else {
System.out.println("Congratulations, you are awarded a Grade" + result + " Pass");
}
}
Now if you want to use the method in conjunction with one another you would end up with a main method looking like so:
public static void main(String[] args) {
titleString();
int examMark = getMark();
gradeMessage(examGrade(examMark));
}
In this main method we call the examGrade method and pass in the parameter examMark. The String value returned from the examGrade method is then passed into the gradeMessage method.

Beginner to java and not sure what this means

import java.util.*;
public class decimalToBinaryTest {
public static void main(String[] args) {
int number;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive interger");
number = in.nextInt();
if (number < 0) {
System.out.println("Not a positive interger");
}
else {
System.out.print("Convert to binary is: ");
System.out.print(binaryform(number) + ".");
}
}
private static Object binaryform(int number) {
int remainder;
if (number <= 1) {
System.out.print(number);
return null;
}
remainder = number % 2;
binaryform(number >> 1);
System.out.print(remainder);
{
return " ";
}
}
}
In the main part of a program an int variable was created. In the next part is says private static Object binaryform ( int number ). Is the int number in the Objectrelating to the variable I the main method?
Yes and no. The variable name number has nothing to do with the main method. It is a formal parameter to the method named binaryform. The parameter number only exists within the method itself. However, when binaryform is called, the actual value of the variable (or constant) used in the call becomes the value of number while the method is executing.
public class Example {
public static void main(String[] args) {
int n = 3; // the name could be "number" and no behavior would change
Object bf = binaryForm(n);
// do something with bf
}
private static Object binaryform(int number) {
// from the call above, number will have the value 3
Object o = . . .;
// generate or modify o from the value of number
return o;
}
}

Java Overloaded Methods

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.

Categories