Java Related, regarding: If-Else, Do-While, Try-Catch [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 days ago.
Improve this question
I am in my first semester of a Java Course. I am struggling to understand how I put exclusiveness on a statement. I am writing a Class for an Object Couch. I have tried to build a well formed class, but for the outcome from my main, in the console it must only have 4 or 8 legs on the couch. There is no user input as I am hard coding the variables, but I want to be sure that if I hard code for 5 legs it will stop me or an error message will pop up. Any suggestions?
public void setNbrLegs(int nbrLegs){
if ((nbrLegs == 2) || (nbrLegs == 4)){
this.nbrLegs = nbrLegs;
}
}
I tried putting an "else" with a message that that number is bad, but what is did was bypass my error message and just insert the incorrect number ofLegs as 5.

Consider looking for the opposite: a condition where you must fail. From there, you can use runtime exceptions to ensure a few things:
The invalid state is not applied
A developer passing this invalid state will get an exception, and have a clear reason to fix their code
You no longer have to worry about invalid state further on in the method (i.e. legs will only be 2 or 4 further on).
In doing so, your method may end up looking like this:
public void setNbrLegs(int legs) {
if (legs != 4 && legs != 2) {
throw new IllegalArgumentException("Can only have 2 or 4 legs");
}
this.nbrLegs = legs;
}
This preconditional checking is also good to do early in your methods (fast-fail), as it will prevent excess work being done for a method that will only "fail".

Related

Error: illegal argument using java.util.Random.nextInt(2) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 9 days ago.
Improve this question
I'm trying to implement a method in which it randomly gets into an if. I implemented it this way:
public void mover(){
int escolha;
Random generator = new Random();
// Next room
do{
// Verify external door
if(this.minhaLocalizacao instanceof IPortaExterna){
IPortaExterna local = (IPortaExterna) minhaLocalizacao;
escolha = generator.nextInt(2);
if(escolha == 1){
setMinhaLocalizacao(local.getLocalPorta());
}
}
escolha = generator.nextInt(minhaLocalizacao.saidas.length - 1);
setMinhaLocalizacao(minhaLocalizacao.saidas[escolha]);
}while(!(this.minhaLocalizacao instanceof IEsconderijo));
}
The program can compile and run normally, but sometimes I receive the error message:
Exception in thread "main" java.lang.IllegalArgumentException: bound must be positive
at java.base/java.util.Random.nextInt(Random.java:557)
...
I know the method nextInt() doesn't accept the argument 0 or negative numbers, but in this case I'm using 2 as the argument. I already tried with other numbers (for example 3), but sooner or later this same error appears. I can't understand why this error is happening.

Java while loop help - nested if else statement [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am brand new to java and trying to create a story based around goldilocks and the three bears in which I ask the user a series of questions and the questions loop until the expected answer is given. It is for a class, and the expectation is we use while loops and if/ nested if else statements to do so. I have managed to get it set up so that the correct messages appear if the user inputs the wanted answer, however, haven't managed to get the question to loop if they input the wrong choice. Instead it just prints the error message and ends the program.
Can anyone give me any tips on where I am going wrong/ no exact fixes just a basic outline would be appreciated. Please assume that there is more to the program but I don't want to have anything flagged for plagiarism of myself later.
This is my if else statement so far (we are using GTerm https://jupiter.csit.rmit.edu.au/~e58140/GTerm/doc/GTerm.html hence gt.getInputString and so forth)
String porridge1;
porridge1 = gt.getInputString("How hot was the porridge? Cold, hot, somewhere in the middle?");
//dialog box asking user question about porridge
gt.println("\n" + "How did Golidlocks find the porridge? Too cold, too hot, or just right?");
// printed message about porridge temperature for user to follow
if (porridge1.equalsIgnoreCase("cold") || porridge1.equalsIgnoreCase(hot")) {
gt.showErrorDialog("Oh no. This porridge was too " + porridge1 + "!");
//if user input = cold or hot; error dialog box appears
gt.println("Oh no! This porridge was too " + porridge1 + "!");
//if user input = cold or hot; print error message
} else {
gt.showMessageDialog("This porridge is just the right temperature!");
//if user types anything else, dialog box confirming correct choice to appear
gt.println("How wonderful! This porridge is just right!");
//if any other input given (middle, warm, perfect, just right etc, print following message
From what I can see there's no loops anywhere that's why it's ending. Put that code inside a while loop to keep it running then put the keyword break whenever you want it to break out of the loop.
while(true){
//Your code here
if(condition...){}
else(condition...){
//Your code here
break;
}
}
Also just a note, typically commenting code goes above the line(or side) of code you're referring to, not under

Understanding a coding challenging in finding the first duplicate value in an array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am currently practicing with my coding skills and one of the challenges I ran into was finding the first duplicate value produced in an array. I had solve the challenge, but not in a timely manner. I looked at the solution for the problem and ran into this solution and wanted help in understanding how it exactly works. I have the solution commented in the areas that I understand and what exactly is the purpose of that block of code, but I would like help in understanding the if-statement why it works the way it does.
int firstDuplicate(int[] a) {
for(int i=0;i<a.length;i++)
//Checks ???????????
if(a[Math.abs(a[i])-1]<0)
return Math.abs(a[i]);
//Make the checked value negative
else{
a[Math.abs(a[i])-1]=-a[Math.abs(a[i])-1];
}
//If there are no duplicates it returns -1
return -1;
}
Constraints:
1 ≤ a.length ≤ 105,
1 ≤ a[i] ≤ a.length.
Welcome to SO. I will not give you the exact answer but instead provide you with tools for you to figure it out.
In order for you to figure out this code, you need to debug it. Here are some ways you could go about it.
Set a breakpoint just prior to calling the function (look up how to do this for your IDE), thereafter step into your code line-by-line.
You could use a combination of temporary variables and System.out.println() statements. Looking into your code, break it down into modular bits that you can track. For instance you could re-write the expression inside the if statement as
int currentElementAbsolute = Math.abs(a[i]);
System.out.println(currentElementAbsolute);
int difference = currentElementAbsolute - 1;
System.out.println(difference);
int element = a[difference]
System.out.println(element);
if (element < 0)
{
return Math.abs(a[i]);
}
As you can see, for each operation/line, I print out the current value thus keeping track of events. Practice this and re-write the else part
PS: Upon completion you will realise this method fails to capture all duplicates when certain type of numbers are used. Happy Hunting :)

I am having problems compiling my Java Code.. I am presuming it is because of a casting/promotinng error in the second method "method1" [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Terminal
Java Code
Hello everyone.
I am having problems compiling my Java Code.. I am presuming it is because of a casting/promotinng error in the second method "method1".
If anyone could spot the errors and let me know that would be great!
Thank you in advance
Whenever you define a new variable, it is 'available' within some scope. For the vast majority of java variable definitions, that scope is 'lexical': Look for the nearest enclosing pair of brackets. Within that, it is visible. Outside, it does not exist.
On line 22 you define variable n1: int n1 = ...;. The nearest braces are on line 21 through at least 40 (the screenshot isn't wide enough) – certainly not line 12, where you reference it. So, at line 12, n1 simply does not exist. at all. That's one error explained.
Another is line 24: Line 23 returns. There is no way for the code to continue execution after that, and javac won't let you compile this: Line 24 is erroneous in that it is impossible to reach. I don't know how to fix it because your code is not clear; I don't know what you are trying to do here.
Perhaps you think 'return' is like 'export'; that's.. just not how it works. return returns from the method. Execution stops right then and there in that method and swaps back to the caller, and the method's value is whatever the expression you supply to the return statement calculates to.
It feels like you want to return 3 separate values from the method. That's not how java works: You can return only one. You can make this some sort of object (an array, or a new instance of a class you write) and in that way effectively 'return multiple values', but you have to package them up into a single thing to return.

How multiple recursion works? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
This post was edited and submitted for review 8 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I need help with a question I saw in my last exam.
Write the output of the execution of the following method by the call pX(7).
public static void pX(int x) {
if (x > 1) {
pX(x/2);
pX(x/2);
}
System.out.println(x);
}
I don't understand recursion when a method calls itself twice. I tried to solve problems with multiple recursion, but I just can't "invert" my mind in a way to multiple recursive thinking.
Can someone explain how multiple recursion works?
Is there any specific mechanism for understanding it?
Will writing a recursion tree or stack call on a blank list will help to understand it?
Is there any reading (like books or articles) about multiple recursion that's worth reading?
Recursion is when a method or function calls itself.
Multiple Recursion is when a method or function contains multiple self-references. This is when it gets a bit tricky. Lets take a look at your example.
You call px(7), and since the parameter is over the value of 1 as your condition checks for, it will enter that code block and encounter the first recursive call, dividing your parameter by half, px(7/2), which evaluates to px(3) (rounded down for integers).
Now that you've entered your first recursive call, lets put your original call on hold for a sec and focus on this new call of px(3). Your condition determines that x is still greater than 1, so we encounter our first recursion within this call. So we call ourselves again, dividing the parameter by half, px(3/2) which evaluates to px(1) (again, rounded down).
Now our condition will no longer pass, so there will be no recursive calls within this iteration, We will go directly to System.out.println(x); and print out the value 1
Back to where px(3/2) got called, the next line in that condition is to do it again. So we call px(3/2) again.
Still, our condition will not pass, so we will not call any more recursive calls and go directly to System.out.println(x);
And again, back to where that second px(3/2) got called. We've completed our condition block and can finally call System.out.println(3);
Here are your first three lines in the output, 1,1,3
It can be kind of tricky, but you need to focus, retain and follow the call stack to really get this down.

Categories

Resources