Java: Parameter list without comma - java

I came across a method with a parameter list where the parameter were not separated by comma and no declaration of the variable type:
public int compareWith(Choice anotherChoice){
Later these parameters were called without any further declaration inside the body in an if-else statement in combination with another method:
if ((this.type == 0)&&(anotherChoice.getType() == 1)){
return -1;
This is a brief summary of the entire class:
public class Choice
{
private int type;
public Choice(int type)
{
//initialize the "type" instance varialble
this.type = type;
}
public int getType()
{
return type;
}
public int compareWith(Choice anotherChoice)
{
Choice choice1 = new Choice(0);
Choice choice2 = new Choice(1);
if ((this.type == 0)&&(anotherChoice.getType() == 1)){
return -1;
The program goes on. I really don't get the link between anotherChoice, getType() and choice2. It is a task in an online course and the program works as intended, but I don't know why.

To clear up your confusion, in this method declaration:
public int compareWith(Choice anotherChoice){
anotherChoice is the parameter of type Choice.

I'm guessing you're new to programming, so I'll give a quick explanation of what's going on. If I've missed the point of your question entirely, I'm sorry.
This line:
public int compareWith(Choice anotherChoice){
is part of the Choice object. It takes another Choice object and compares it with itself. ...or at least, that's what I would expect. The code you provided:
public int compareWith(Choice anotherChoice)
{
Choice choice1 = new Choice(0);
Choice choice2 = new Choice(1);
if ((this.type == 0)&&(anotherChoice.getType() == 1)){
return -1;
is incomplete and I have no idea what choice1 and choice2 are supposed to be doing. The code I would expect to see would look more like
public int compareWith(Choice anotherChoice)
{
if (this.type == anotherChoice.getType())
return 0;
return -1;
}
or something like that.
Does that help?

This was my solution for the course. Probably not the best solution but it worked and i receved my grade. I'm at this moment stuck with LAB 04 TASK 3.
int player=this.getType();//get value of choice1
int computer=anotherChoice.getType();// this get the value choise2 out of anotherChoise
int som;// this INT i made to make a sum
int result;
result = 0;//i already gave a value on the INT result
som = player - computer;//this is the sum of de values choice1 and choise2
if(player == computer) //all ties
result = 0;
else if(som == -1) //player ROCK and comp. PAPER or PAPER and SCISSOR
result = -1;
else if(som == 2) //player SCISSOR and comp. ROCK
result = -1;
else if(som == 1)//player SCISSOR and comp PAPER or PAPER and ROCK
result = 1;
else if(som == -2)//player ROCK and comp. SCISSOR
result = 1;
return result; // this line should be modified/removed upon finishing

Related

Creating a Helper method in Java

So Im creating a Helper method in Java to calculate postage based on size, but I can't seem to figure out the return part. Im still new to helper methods and accessors etc. Im using Eclipse and its telling me "Add return statement" but I did.. What am I doing wrong here?
Here is my code:
//Helper Method.
public int calculatePostageCost() {
double postCost;
if(satchelSize.equals("small"))
postCost = 10;
else if(satchelSize.equals("Medium") || satchelSize.equals("medium"))
postCost = 13;
else if(satchelSize.equalsIgnoreCase("Large") || satchelSize.equals("large"))
postCost = 17;
else {
return calculatePostageCost();
}
}
The problem is that you do not have a guaranteed return statement at the end of the function. What would happen if your function does not encounter a satchel size, which is either "small", "medium", etc, you will return the value of what your function calculatePostageCost returns (I will return to that later).
In every other case, however, you do not have a return in your function. When you encounter "small" as satchel size, you enter the first if block of code, where you will set postCost to 10, then you jump over the rest of the code (since it is all else if).
Most likely you are missing a statement like return postCode; below the else block. This would at least eliminate the error message from eclipse. I am not fully sure about your code, but you could have an endless recursion here. Your else block might be a problem:
else {
return calculatePostageCost();
}
You need to check if it is possible, that in the next call of this recursion, the else block will not be reached. When this is not the case, you will have an endless recursion everytime you enter this function while you are in a state where the satchel size is not "small", "medium", etc, because you won't have a chance to change the state and get out of these calls anymore.
Don't use strings to compare your size, create an enum to do that:
public enum Size {
SMALL, MEDIUM, LARGE
}
private Size satchelSize; ....
public int calculatePostageCost() {
switch(satchelSize) {
case SMALL:
return 10;
case MEDIUM:
return 13;
case LARGE:
return 17;
}
}
If you are very keen on keeping the strings you can switch on strings too:
private String stachelSize = ....;
public int calculatePostageCost() {
switch(satchelSize.toUpperCase()) {
case "SMALL":
return 10;
case "MEDIUM":
return 13;
case "LARGE":
return 17;
default:
throw new AssertionError("Don't know satchel size " + satchelSize);
}
}
Note that your original code had
else {
return calculatePostageCost();
}
Which would call the same function again, which would end up in the same else branch, calling the same function again, which would end up in the same else branch, which.... would eventually give a StackOverflowException.
(I understand that strictly it does not answer your question 'why doesn't this compile'.)
The problem is that your return statement is within the scope of the else statement ,it should be outside like this : `
public int calculatePostageCost() {
double postCost;
if(satchelSize.equals("small"))
postCost = 10;
else if (satchelSize.equals("Medium") || satchelSize.equals("medium")){
postCost = 13;
else if(satchelSize.equalsIgnoreCase("Large") || satchelSize.equals("large"))
postCost = 17;
return postCost;
}
If you return calculatePostageCost() you create a recursive loop which causes a stack overflow error.
Do like this,
//Helper Method.
public int calculatePostageCost() {
int postCost = 5; // i don't know about default conndition, i am taking 5
if(satchelSize.equals("small"))
postCost = 10;
else if(satchelSize.equals("Medium") || satchelSize.equals("medium"))
postCost = 13;
else if(satchelSize.equalsIgnoreCase("Large") || satchelSize.equals("large"))
postCost = 17;
}
return postCost ;
}
You have to return value on every possible scenario. Right now you are returning (infinite recursion thus stak overflow will happen) only single in case if package is not small not medium nor large. You have to return value for every of this variants, like that:
public int calculatePostageCost() {
int postCost=1234; // default cost for not small nor medium nor large package
if(satchelSize.equals("small"))
postCost = 10;
else if(satchelSize.equals("Medium") || satchelSize.equals("medium"))
postCost = 13;
else if(satchelSize.equalsIgnoreCase("Large") || satchelSize.equals("large"))
postCost = 17;
return postCode
}
Or even better
public int calculatePostageCost() {
if(satchelSize.equalsIgnoreCase("small"))
return 10;
else if(satchelSize.equalsIgnoreCase("Medium"))
return 13
else if(satchelSize.equalsIgnoreCase("Large"))
return 17;
return 12345; // cos of non small, medium nor large package
}

Storing an integer, adding to itself, and using it as a parameter in a method in java

I have a problem where I have to store an integer, if a user answers Y, from an input and then using it on a method, storing that integer and then adding it to a different input from the user. The total will be used on the same method and printed only if the user inputs N.
For instance,
Y
input =3
method(input)
Y
input = 4
method(input)
N
total = 3+4
method(input, total)
I have most of the code already, I just want to know if it is possible to get the total and use it on the method
Edit: here is the code
public static boolean walk(boolean bool, String answer) {
while(bool==true) {
if (answer.equals("Y") || answer.equals("y")) {
return bool=true;
}
else if (answer.equals("N") || answer.equals("n")) {
return bool=true;
}
}
return bool;
}
public static boolean continueWalking(boolean bool, String answer, int average) {
while(bool==true){
if (answer.equals("Y") || answer.equals("y")){
return bool=true;
}
else if(answer.equals("N") || answer.equals("n")){
System.out.println("Great exercise!");
System.out.println(average);
System.exit(0);
}
}
return bool;
}
while(bool) {
System.out.println("Do you want to start/continue walking?");
String continueWalk=input.next();
int totsteps=numberOfSteps;
continueWalking(true, continueWalk,totsteps);
System.out.println("How many steps do you want to walk in this section?");
totsteps=numberOfSteps + numberOfSteps;
int numberOfSteps = input.nextInt();
NumOfsteps(numberOfSteps,1);
}
Just a couple of syntax/formatting things to start with:
your while statement while(bool==true) can be changed to just while(bool). A while loop statement just needs to evaluate to a boolean in Java, and boolean bool is already a boolean. You can do a similar thing for your return statements, change them to return bool;
To answer your question, to update an int value in Java, use +=.
int test = 0;
test += 1;
System.out.println(test); // Prints out 1
In your code, declare totsteps outside of the while loop, and change the line int totsteps=numberOfSteps; to totsteps += numberOfSteps;

Returning an int value from a method java

I'm pretty new to java, but I'm trying to make a simulation of the finger game, 'Sticks', using my limited knowledge. This may not be the neatest, but if you're going to make a suggestion on me to do something, link a page explaining what that thing is, and I'll read it.
Ok, so the issue comes up basically when I call a method to decide who's turn it is and trying to return the value for the "count" up to 5, but it's not returning to main()
public static int TurnCalcBB(int PLH, int PRH, int BRH, int BLH, int Death)
{
//Attacking with bot Right hand
Random botAtk = new Random();
if(botAtk.nextInt(2) == 1 && PRH <= 5)
{
PRH = BRH + PRH;
JOptionPane.showMessageDialog(null,"Your right hand is now at " + PRH);
return PRH;
} else if(botAtk.nextInt(2) == 0 && PLH <= 5){
PLH = BRH + PLH;
JOptionPane.showMessageDialog(null, "Your left hand is now at " + PLH);
return PLH;
}
return Death;
}
Death is there because I was getting an error telling me that I always need to return SOMETHING so I'm returning a static value.
Basically, the problem is getting PLH (player left hand) or PRH (player right hand) to return to main. If I'm not wrong, they should return as their initial variable name (PL, and PR) with the returned value correct? If not, what can I do to fix this?
The code is a lot larger than this, and this issue is happening throughout the whole program, so I'm showing just 1 method and assuming they're all the same issue; the methods are almost all the same.
Also, while I'm typing a question already, is nextInt() the best way to do a random number generator? When I had it as nextInt(1) it was exclusively attacking the left hand, and when I switched it to nextInt(2) now it's attacking both, but occasionally the code... "crashes" (what I mean by crashes is that it generates a number outside of what the If statements are looking for). I obviously need to to generate either a 1 or a 2 (or 0 and 1 if 0 counts).
You can change your code to
public static Integer TurnCalcBB(int PLH, int PRH, int BRH, int BLH, int Death)
{
//Attacking with bot Right hand
Random botAtk = new Random();
if(botAtk.nextInt(2) == 1 && PRH <= 5)
{
PRH = BRH + PRH;
JOptionPane.showMessageDialog(null,"Your right hand is now at " + PRH);
return PRH;
} else if(botAtk.nextInt(2) == 0 && PLH <= 5){
PLH = BRH + PLH;
JOptionPane.showMessageDialog(null, "Your left hand is now at " + PLH);
return PLH;
}
return null;
}
NOTE: make sure you first check for null values where you call this function.
You are generating random number twice, this is why you can observe "strange" behvior.
Random botAtk = new Random();
if(botAtk.nextInt(2) == 1 && PRH <= 5) {
...
}
else if(botAtk.nextInt(2) == 0 && PLH <= 5) {
...
}
Try generating random only once:
Random botAtk = new Random();
boolean right = botAtk.nextInt(2) == 1; // flip coin only once
if(right && PRH <= 5) {
...
}
else if(!right && PLH <= 5) {
...
}
I know the answer will not get accepted, because there is an accepted one, but nevertheless:
I suspect that you have a wrong understanding of method parameter passing in Java.
What I read from your question and comments is that you expect this to work:
public static int psInt = 0;
static void main() {
int someNumber = 1;
int someOtherNumber = 5;
method1( someNumber, someOtherNumber );
// You expect "someNumber" to be 6 right now.
// But in fact, the value will be unchanged.
// What WILL work: psInt is 0 now
method3(); // this method will modify the static class var
// psInt is 5 now.
}
static void method1( int numParam, int someothervalue ){
numParam = numParam + someothervalue;
}
static void method2( int someNumber, int someothervalue ){
someNumber = someNumber + someothervalue; // <- same name won't work either!
}
public static void method3(){
psInt = 5;
}
But in Java method arguments are passed by value. That is: a copy!
So no matter how you name the variables and arguments, you will never have an "out" argument here.
What you can do:
In a static method, you can use and modify static class variables.
In a non-static method, you can use and modify non-static and static class variables.
You can pass a State-Object, of which you can modify field values.
You can return a value.
... there are more possibilites. These just to start with.
In your case, 4. does not make so much sense, because you wouldn't know if it is the new right or left hand value.

Java complains about invalid method declaration, return type required

it's for a JOptionPane YES_NO_CANCEL_OPTION I did the following method:
public NewCard()
{
int ans = JOptionPane.showConfirmDialog(null, "Do you wish another card?", "7 in 1", JOptionPane.YES_NO_CANCEL_OPTION );
if (ans == JOptionPane.YES_OPTION)
{
ans = 1;
}
if (ans == JOptionPane.NO_OPTION)
{
ans = 2;
}
if (resp == JOptionPane.CANCEL_OPTION)
{
ans = 3;
}
return ans;
}
I want to read this answer from the main but a grammatical error appears. It says:
Invalid method declaration; return type required but I tried to write a return in all if statements and got the same error.
You must have the return type in the function declaration.
Your function returns an int, so:
public int NewCard() {
See the int there.
If you don't want to return anything, use void.
This really should be a comment, but I needed the formatting.
You need to be careful when you reuse a variable like ans.
The values of the following constants are:
JOptionPane.YES_OPTION = 0;
JOptionPane.NO_OPTION = 1;
JOptionPane.CANCEL_OPTION = 2;
You could have just as easily added 1 to ans as coded the 3 if statements.
The way you wrote your code:
if (ans == JOptionPane.YES_OPTION)
{
ans = 1;
}
if (ans == JOptionPane.NO_OPTION)
{
ans = 2;
}
if (resp == JOptionPane.CANCEL_OPTION)
{
ans = 3;
}
If ans = 0 (the YES option), you set it to 1 in the first if.
Then ans (your ans, not the original ans) = 1 (the NO option).
The same thing happens in the 3rd if.
So, if your user clicks on the YES button, you return a 3. If your user clicks on the NO button, you return a 3. Same for the CANCEL button. You return a 3.
Either use two different variables, change your second and third if to an else if, or just add 1 to ans.

Binary Search output issue?

This is a first for using a binary search for me, so I've run into a small issue (hopefully!) first the program, it allows the user to type in a random number, and if that number matches any book it outputs the title.
class b {
String book1, book2;
b () {
book1 = "Wicked Awesome Title";
book2 = "How to Read a Book";
public static Book getBook(Book [] A, int left, int right, String bookTitle) {
int middle;
Book found = null;
/**Your average Joe binary search...*/
while (found == null && left <= right) {
//If middle item == 0, returns true
middle = (left + right)/2;
int compare = A[middle].sameTitle(bookTitle);
if (compare == 0) {
found = A[middle];
} else {
if (compare >0) {
right = middle -1;
} else {
left = middle + 1;
}
}
}
return found;
}
Now this is the problem, after pressing the "find" book button,
private void findActionPerformed(java.awt.event.ActionEvent evt) {
String book1 = "Wicked Awesome Title";
String book2 = "How to Read a Book";;
Book b = getBook(book1, book2); //this entire line is underlined,
if (b != null){
itsATextField.setText("You've found the book " + b);
}
so what am I missing to make this work? Any ideas?
Your getBook function is declared as:
public static Book getBook(Book [] A, int left, int right, String bookTitle) {
When you try to call it only with two String arguments:
Book b = getBook(book1, book2);
If you want to call a function, you must call it with the expected arguments.
Also, not sure if related or not but you'r missing } at the end of the constructor.
BTW, adding the error you get will help us help you.

Categories

Resources