Error: illegal argument using java.util.Random.nextInt(2) [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 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.

Related

Java Related, regarding: If-Else, Do-While, Try-Catch [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 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".

I'm a Java beginner- Convert String value to Integer using JTextField [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 5 years ago.
Improve this question
I have created a simple java program that takes a string input from user through 2 boxes of Jtextfields and then convert it to integer.
These 2 integer values are then converted to decimal values by dividing them.
The decimal values are then seen by the user with a dialog box (basically a fraction to decimal converter)
When I run the program I get errors that I do not understand.
my code
code error
It must throw NumberFormatException if you try to parse it to integer.
Check before parsing. or handle Exception properly.
Exception Handling*
try{
int i = Integer.parseInt(input);
}catch(NumberFormatException ex){ // handle your exception
...
}
or
- Integer pattern matching -
String input=...;
String pattern ="-?\\d+";
if(input.matches("-?\\d+")){ // any positive or negetive integer or not!
...
}

Display different Error message after a Limit? [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
I need to display a error Message.I have declared a counter.Whenever the counter is 3 it has to display a different error message.So i have written the below snippet.
It returns error: <identifier> expected on the declaration.
//declaration
private static attempts = 0;
//operation
switch (xmlRpcFault.getFaultCode()) {
case 403:
attempts++;
if(attempts = 3)
{
mErrorMsgId = R.string.username_or_password_incorrect;
//reinitialize counter
attempts = 0;
}
else
mErrorMsgId = R.string.username_or_password_incorrectfull;
break;
The statement:
if(attempts = 3)
probably should be:
if (attempts == 3)
?
The source of the error you asked about is that you need to specify the actual type of the variable in your declaration. You have:
//declaration
private static attempts = 0;
You probably mean:
//declaration
private static int attempts = 0;
Note the int (or whatever type you want it to be).
Also, the issue that Harmlezz mentions (attempts = 3 vs. attempts == 3) is another problem.
As an aside: Most of the code you posted, as well as the question you asked, was irrelevant. The correct code to post would have been only the line with the compiler error. The correct question is "why does 'private static attempts = 0' cause a compiler error". Even the tags: This was not an Android question, or a question about while loops or if statements or counters. I mention this constructively: Think about the problem at hand, and try narrowing it down. It's a general thought process that will help you in all cases.
Granted, by posting all of it, it let us spot a few other issues, but that was incidental; your general problem solving thought-process did not match the problem itself.
Question titles are a good window into a person's thought process; in general, you can learn a lot by reexamining your question titles here after your problem is solved.

Java Input Empty show alert [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm doing a small project in Java whilst I'm learning the language.
Basically what I'd like is for a user to input a string via JOptionPane.showInputDialog();, if that string is empty, I want it to make them re-enter a valid string and then the program will continue.
What I did consider doing is using goto but I read up on it and it said it's not good practice.
Any help would be greatly appreciated.
Thanks :)
I would do it in an infinite loop asking for input (using OptionPane.showInputDialog()).
Here you have some pseudo code:
message = ""
while message.equals(""):
message = ask_for_input() // (.trim() if needed)
end
You could do it in a loop. So you take a while-loop where the condition is that the input is empty. Then the message will pop up until the user entered something.
Despite goto is a reserved keyword in Java, it's actually (implicitly) meant for not being used.
JOptionPane.showInputDialog(...) returns a String.
I suggest using an infinite while loop and comparing it to empty, through String.isEmpty().
For instance:
String input = null;
while (true) {
input = JOptionPane.showInputDialog("Your input (not empty):");
if (!input.trim().isEmpty()) {
// TODO something with the input variable
break;
}
}
This is what do ... while loops are for. You could also use the Apache commons StringUtils class.
String input;
do {
input = JOptionPane.showInputDialog("Please enter your string");
} while (StringUtils.isBlank(input));

java arrayoutofbounds exception error when program together [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I am doing an assignment and I have to do several simple string manipulations. I think I have the last one figured out, and it works by itself, but it does not work when I put it together with the other string manipulations, giving me an arrayoutofbounds exception error. Any advice?
Here is the small code I made
public static void main (Strings[] args) {
Scanner sc = new Scanner(System.in);
String theSentence = sc.nextLine();
String [] theWords = theSentence.split(" ");
Arrays.sort(theWords);
System.out.println(theWords[1]);
System.out.println(Arrays.toString(theWords));
}
This does not work when it is put together with the rest of the code even though it works by itself. For reference, this code is supposed to take in a small sentence and give me the smallest word lexicographically. Ex: input: "4 WHAT WAIT IS THIS" output would be "IS"
The code is assuming that theWords will always have at least two elements in it. If the sentence provided by the user does not have any spaces, theWords will never get an element in position 1 and so the program will crash on System.out.println(theWords[1]);
In Java arrays are indexed from zero, where the 0th element is the first.
As Mark said you are assuming that there are always two words entered in this case. You should check the length of theWords before trying to access an element.

Categories

Resources