How do I call these methods? [closed] - java

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

Related

Java return (value) error

I tried different things in my code, but I always get errors.
The instructions for the program is that I need to have a function (besides from main) that receives arguments for an array of integer values and a second argument telling the desire value to look in the array by the user.
It must also return how many times the desire value is repeated on the array.
The errors are related to the counter and also some are in the main function.
I think I am not returning the counter value correctly.
This is my current code:
import java.util.Scanner;
import java.util.Arrays;
public class ArregloBusqueda2
{
static int findRepetition(int listOfValues[], int targetValue, int counter)
{
int i;
boolean found = false;
for(i=0; i<listOfValues.length; i++)
{
while((counter < listOfValues.length))
{
if(listOfValues[i] == targetValue)
{
counter = counter + 1;
}
}
}
return counter;
}
public static int main(String[] args)
{
Scanner input = new Scanner (System.in);
int targetValue;
int listOfValues[] = {1,6,3,8,5,8,3,4,8,3};
System.out.println("Please enter the desire number to look for: ");
targetValue=input.nextInt();
findRepetition(targetValue, counter);
if(counter != 0)
{
System.out.println("The frequency of the number " + targetValue + " is: " + counter);
}
else
{
System.out.println ("The number " + targetValue + " is not contained in the array list");
}
}
}
Multiple issues in your code.
public static int main(String[] args) should be public static
void main(String[] args)
findRepetition takes three arguments,
but you are passing two agruments
counter variable is not declared
Logical flaw, while((counter < listOfValues.length)) will keep on executing if counter value is less than listOfValues.
static int findRepetition(int listOfValues[], int targetValue) {
int i;
int counter = 0;
for (i = 0; i < listOfValues.length; i++) {
if (listOfValues[i] == targetValue) {
counter = counter + 1;
}
}
return counter;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int targetValue;
int listOfValues[] = { 1, 6, 3, 8, 5, 8, 3, 4, 8, 3 };
System.out.println("Please enter the desire number to look for: ");
targetValue = input.nextInt();
int counter = findRepetition(listOfValues, targetValue);
if (counter != 0) {
System.out.println("The frequency of the number " + targetValue + " is: " + counter);
} else {
System.out.println("The number " + targetValue + " is not contained in the array list");
}
}
You made your method accept three parameters.
static int findRepetition(int listOfValues[], int targetValue, int counter)
Ask yourself - do you want to "pass in a counter", or only return it? The instructions say the latter.
When you call this method, you are not providing the correct inputs.
findRepetition(targetValue, counter);
What about the listOfValues? You want to findReptition on listOfValues for targetValue, right? So provide the correct parameters into that method call.
Again, you likely do not need the counter passed-in. Because Java is always pass-by-value
Rather, you want to return counter, as you have written. You are looking for this.
int counter = findRepetition(listOfValues, targetValue);
Fixing the remainder of the code is a learning exercise.
You are not calling findRepetition() with required parameters, findRepetition method takes 3 arguments, but you are passing only 2 arguments.

How do I return an int data from a static void method to main method?

So everything is working but my only issue is that I'm not sure how to return a piece data from my speakLine() method. I'm trying to print the amount of right answers I got from a set of problems.
Something like this: you got "2" out of 3 correct.
Public static void main(String[] args) throws Exception {
int cal;
int i;
for (i = 0; i < 3; i++) {
int num1 = randomA();
int num2 = randomB();
cal = num1 + num2;
speakLines(num1, num2, cal);
}
I need the "count" int from speakLine method():
System.out.println("You got " + count + "of " + i + "right");
} // end main()
This is the method
public static void speakLines(int num1, int num2, int cal) {
int count = 0;
Scanner scanner = new Scanner(System.in);
Voice voice;
// set up a Voicemanager object and use it to link voice with a particular voice
VoiceManager voiceManager = VoiceManager.getInstance();
voice = voiceManager.getVoice("kevin16");
// load the selected voice
voice.allocate();
// begin speaking the text
System.out.println("what is " + num1 + " + " + num2 + ":");
voice.speak("what is " + num1 + " + " + num2 + ":");
//talk
System.out.println("Please enter answer");
int answer = scanner.nextInt();
//talk
if (answer == cal) {
System.out.println("That's right");
voice.speak("That's right");
count += 1;
"Count +=1" above ^ -- I need to print this count int from the main() method. This is the data "count" that I'm trying to return to the main method. This tells me how many answers the user got right.
} else {
System.out.println("Sorry, the answer is" + cal);
voice.speak("Sorry, the answer is " + cal);
}
} // end speakLines()
public static int randomA() {
int A;
A = 1 + (int) (Math.random() * 10);
return A;
}
public static int randomB() {
int B;
B = 1 + (int) (Math.random() * 5);
return B;
}
// end randomB()
} // end class
Now I know static void methods do not return data. But I know there should be a way to return a specific data.
Declare a class variable public static int count; to replace the local variable count in the speakLines method.
After doing so, you should be able to access and print score in the main method.
The return code is probably not want you want here. You likely want to write the answer to Standard output. This way some other program could pick it up. There are various methods on System.out that will write to standard output.
If you want to use a java program to be a part of a chain of programs, you use standard input and standard output.
That System.out.println is causing the program to send output. This could be read by another program. For example you could run this and redirect it's output to a file: java -jar yourjar > out.txt
You can also use a pipe character to send this output to another program:
java -jar yourJar | grep of
I don't know what specifically you want to do with the output.
You can either use a static filed on the containing class (the one that is above the main function) and reset it at the beginning of speakLines.
Usually you don't need static for that but since the main is a static method it cannot access non static fields of the containing class.
or
Use a class parameter that will hold the int value, and also reset the value at at the beginning of speakLines.
Taking help from the #DizzyCode, how about-
1. Declare public static int count in line 2
2. Initialize variable count in line 9
3. Comment initialisation of your local variable 'count' in the method 'speakLines'
//******************************
public static int count;
Public static void main(String[] args) throws Exception {
int cal;
int i;
//set count to 0 before the loop starts
count=0;
for (i = 0; i < 3; i++) {
int num1 = randomA();
int num2 = randomB();
cal = num1 + num2;
speakLines(num1, num2, cal);
}
System.out.println("You got " + count + "of " + i + "right");
} // end main()
public static void speakLines(int num1, int num2, int cal) {
//**************************************
//make this count invalid and create a public static count variable before main method
// int count = 0;
Scanner scanner = new Scanner(System.in);
Voice voice;
// set up a Voicemanager object and use it to link voice with a particular voice
VoiceManager voiceManager = VoiceManager.getInstance();
voice = voiceManager.getVoice("kevin16");
// load the selected voice
voice.allocate();
// begin speaking the text
System.out.println("what is " + num1 + " + " + num2 + ":");
voice.speak("what is " + num1 + " + " + num2 + ":");
//talk
System.out.println("Please enter answer");
int answer = scanner.nextInt();
//talk
if (answer == cal) {
System.out.println("That's right");
voice.speak("That's right");
count += 1;}
else {
System.out.println("Sorry, the answer is" + cal);
voice.speak("Sorry, the answer is " + cal);
}
} // end speakLines()
public static int randomA() {
int A;
A = 1 + (int) (Math.random() * 10);
return A;
}
public static int randomB() {
int B;
B = 1 + (int) (Math.random() * 5);
return B;
}
// end randomB()
} // end class

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

Static reference to the non-static method (In main method) [duplicate]

This question already has answers here:
Cannot make a static reference to the non-static method
(8 answers)
Closed 8 years ago.
I've looked all over for an answer that I understand about this question. I'm writing a program where a user inputs a number, and then the program prints out the number and if it is odd or even as well as if it's a multiple of 7.
I'm getting this error for these lines of code:
"Cannot make a static reference to the non-static method Method Name"
getNum ();
evenOdd ();
multiple ();
System.out.println(number1 + " : " + evenOdd + " : " + multipleOr);
This is what my code is:
import java.util.Scanner;
public class Multiples {
int number1;
String evenOdd;
String multipleOr;
public static void main(String[] args) {
printMsg();
System.out.println("Enter a number: ");
getNum ();
evenOdd ();
multiple ();
System.out.println(number1 + " : " + evenOdd + " : " + multipleOr);
}
public static void printMsg() {
System.out.println("Welcome to the Multiplicity program.");
System.out.println("Enter a number and I will tell you if it is a multiple of 7 and if it is odd or even.");
return;
}
public int getNum() {
Scanner input = new Scanner (System.in);
number1 = input.nextInt();
return number1;
}
public String evenOdd(){
if (number1 / 2 == 0);
evenOdd = "EVEN";
if (number1 / 2 != 0);
evenOdd = "ODD";
return evenOdd;
}
public String multiple(){
if (number1 / 7 == 0);
multipleOr = "MULTIPLE";
if (number1 / 7 != 0);
multipleOr = "NOT";
return multipleOr;
}
}
Really unsure of how to fix this issue. I tried putting "static" into all of the methods but then the variables were all messed up inside of them.
Note: It's supposed to print as "Number : Even : Multiple".
Make your variables and methods static and that will fix your problem. Just make sure you understand the difference between static and non-static. Static variables and methods are shared by all objects (instances) of a particular class while non-static variables and methods are specific to each instance of a particular class. For what you are doing making your variables and methods all static is the correct thing to do. Or you could create your global variables in the main method as non-static variables and pass them to each method that needs them.

Calculator tip why is it not compiling [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 8 years ago.
Improve this question
import java.util.Scanner;
public class Hw4Part4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Ask for the diners’ satisfaction level using these ratings: 1 = Totally
// satisfied, 2 = Satisfied,
// 3 = Dissatisfied.
System.out.println("Satisfacion leve: ");
int satisfactionNumber = sc.nextInt();
// Ask for the bill subtotal (not including the tip)
System.out.println("What is the bill subtotal: ");
double subtotal = sc.nextInt();
// Report the satisfaction level and bill total.
System.out.println("The satisfaction level is: " +
satisfactionLevel(satisfactionNumber));
System.out.println("The bill total is: " +
getBillTotal(tipPercentage, subtotal));
}
public static String satisfactionLevel(int satisfactionNumber) {
String satisfactionL = "";
if (satisfactionNumber == 1) {
satisfactionL = "Totally-satisfied";
}
if (satisfactionNumber == 2) {
satisfactionL = "Satisfied";
}
if (satisfactionNumber == 3) {
satisfactionL = "Dissatisfied";
}
return satisfactionL;
}
// This method takes the satisfaction number and returns the percentage of tip
// to be
// calculated based on the number.
// This method will return a value of 0.20, 0.15, or 0.10
public static double getPercentage(int satisfactionNumber) {
double getPercentage = 0;
if (satisfactionNumber == 1) {
getPercentage = 0.20;
}
if (satisfactionNumber == 2) {
getPercentage = 0.15;
}
if (satisfactionNumber == 3) {
getPercentage = 0.10;
}
return getPercentage;
}
public static double getBillTotal(double tipPercentage, double subtotal) {
double totalWithTip =
(subtotal + (getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
}
Error where it says getPercentage(satisfactionNumber)*subtotal..... says SatisfactionNumber cannot be resolved to a variable
And in the Main method there is a error on
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal)); I believe it is the related to the last error.
In getBillTotal, satisfactionNumber is undefined, it has meaning within the context of the method. In order to use it, you would need to define the variable within the context of the method either as a parameter or as a local variable...
In your main method, You have the same problem with tipPercentage, it's undefined...
Your close. You will need to pass in satisfactionNumber into getBillTotal by adding another parameter. Otherwise it don't know what you are taking about when you say satisfactionNumber. It can't directly see the variables in other functions.
public static double getBillTotal(double tipPercentage, double subtotal, int satisfactionNumber) {
double totalWithTip = (subtotal + (getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
Then in your main method call pass it in.
public static void main(String[] args) {
....
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal, satisfactionNumber));
}
And actually you don't need tipPercentage, in fact it's not even defined in main. Since it can be found by satisfactionNumber you could do this.
public static void main(String[] args) {
....
System.out.println("The bill total is: " + getBillTotal(subtotal, satisfactionNumber));
}
...
public static double getBillTotal(double subtotal, int satisfactionNumber) {
double totalWithTip = (subtotal + (getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
OR you could pass in the tipPercentage by calculating it first.
public static void main(String[] args) {
....
double tipPercentage = getPercentage(satisfactionNumber);
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal));
}
...
public static double getBillTotal(double tipPercentage, double subtotal) {
double totalWithTip = (subtotal + (tipPercentage * subtotal));
return totalWithTip;
}
Any of these last two would be okay.

Categories