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 9 years ago.
Improve this question
Error :
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 2
at java.util.LinkedList.checkElementIndex(LinkedList.java:553)
at java.util.LinkedList.get(LinkedList.java:474)
at InterfacePackage.Main.main(Main.java:116)
Java Result: 1
Code (shortened) :
if(input.length() > 0)
{
if(command.size() == 1)
{
switch(command.get(0).toLowerCase())
{
case "exit":
case "qqq":
active = false;
break;
default:
System.out.println("invalid input, for complete list of commands enter 'help'...");
break;
}
}
else if(command.size() > 1)
{
if(command.get(0).equalsIgnoreCase("shutdown") && command.size()==3)
{
Shutdown shutdown = new Shutdown();
shutdown.Start(command);
}
else if(((command.get(0).equalsIgnoreCase("scan")
&& command.get(1).equalsIgnoreCase("ips"))
|| command.get(3).equalsIgnoreCase("/e"))
&& (command.size()>=2 || command.size()<4))
{
SystemsIPs sips = new SystemsIPs();
sips.Start(command);
}
else
{
System.out.println("invalid input, for complete list of commands enter 'help'...");
}
}
}
The error occurs when the users enters two string within a line that doesn't exist in the else if(command.size() > 1) loop.
For example, if the user would enter : hello world the program produces this error.
So this is a program that does various things based on user input to a console. I've been getting this error and and wanting to know what is causing it. I know I can just catch it, but I really want to know what causing this error.
Your error seems to be caused by
command.get(3).equalsIgnoreCase("/e"))
There is no index 3. Check if that index exists first, before you do that.
You're getting an IndexOutOfBoundsException as it says, and it occurs when you're trying to access a position in a collection/array and that position is empty, you're trying to access to an index that doesnt exist. If you don't want that to happen then force the program to use an Collection with a size more than 3 element.
The problem is in this line:
else if(((command.get(0).equalsIgnoreCase("scan") &&
command.get(1).equalsIgnoreCase("ips")) ||
command.get(3).equalsIgnoreCase("/e")) &&
(command.size()>=2 || command.size()<4))
You are using command.get(3) to retrieve the 3rd element of the LinkedList, but it's not guaranteed that there are at least 3 elements in the list.
So you'd better add a condition command.size() >= 3 before command.get(3).
Ok so here is how I solved the problem :
else if((command.get(0).equalsIgnoreCase("scan") && command.get(1).equalsIgnoreCase("ips")) && (command.size()>=2 || command.size()<4))
So I removed the
|| command.get(3).equalsIgnoreCase("/e"))
... from the code entirely, and improved the case in the separate class that this if statement directs to.
Here is what I did in the separate class...
if(command.size()==3 && command.get(2).equalsIgnoreCase("/e")) { }
else if(command.size()==2) { }
And it works (:
Related
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 2 years ago.
Improve this question
So, I just started to get my hands dirty on Java this week and I found something rather odd. I'll add the code and then walk you through.
import java.util.Scanner;
public class kids
{
public static void main(String[] args)
{
System.out.println("How old are you, doll?");
Scanner scanner = new Scanner(System.in);
int age = scanner.nextInt();
System.out.println("Doggie lover or a cat person?");
String animal = scanner.nextLine();
if(age < 18 && animal.contains("dog")) // 1st comparison
{
System.out.println("Hello cutie, welcome");
}
else if(age < 18 && animal.contains("cat")) // 2nd comparison
{
System.out.println("Oh, hi"); // This statement gets skipped
}
else if(age < 18 && animal.contains("cat")); // 3rd comparison
{
System.out.println("Hiya, Doggie lover!");
}
}
}
I've attached my output here
Output
So, I gave an input "dogcat" to the string animal. It is pretty clear or at least to me that the three comparisons should return TRUE but my output says otherwise. Seems like only the first and the third comparisons return TRUE but clearly if the third comparison returns TRUE since it contains the string "cat" so does the second comparison. Why is Java skipping my comparison here?
For input dogcat, it only executes the first if condition. Since other two conditions are given as else if conditions, they do not get executed.
Confusion happens because of the typo of having an semicolon just after the 3rd if condition. So the typo makes an empty statement for 3rd if condition.
The statements in the last set of curly braces are not a part of 3rd if condition due to the typo.
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 a beginner in Java and I am working right now with a small projekt, a hangman game. One of the functions I am working on right now is a method where it takes a char input, check if the input is already added to the list or not, if it is, a message will show up saying "You have already used that character!" and the user will have to guess again, otherwise the input will be added to the list. My issue right now is that nothing is happening, inputs are not added to the list at all.
This is what I have done so far:
Any advice/help would be appreciated!
public static ArrayList<Character> getGuesses(ArrayList<Character> allGuesses, char input){
for (int i = 0; i < allGuesses.size(); i++) {
if (allGuesses.get(i) == input) {
System.out.println("You have already used that character!");
}else {
allGuesses.add(input);
}
}
return allGuesses;
}
You are adding the input character on each iteration as you search the collection. You should only add it after you have searched the collection and not found it.
for (int index = 0 ; index < allGuesses.size() ; ++index) {
if (allGuesses.get(index) == input) {
System.out.println("You already used that character!");
return allGuesses;
}
}
allGuesses.add(input);
return allGuesses;
However, this can be simplified by using the Collection contains method such that you do not employ a loop.
if (allGuesses.contains(input)) {
System.out.println("You already used that character!");
return allGuesses;
}
allGuesses.add(input);
return allGuesses;
If possible, consider switching the type of allGuesses to a Set implementation (e.g. HashSet). A Set seems to better match how you are using your collection and allows you to reduce this method to...
if (! allGuesses.add(input)) {
System.out.println("You already used that character!");
}
return allGuesses;
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 3 years ago.
Improve this question
I am trying here to measure how many white spaces there are in text typed in a JTextArea. I am getting an outofbounds exception. Why so?
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:658)
at ClassTest.main(ClassTest.java:11)
import javax.swing.*;
public class ClassTest {
public static void main(String [] args) {
JFrame frame = new JFrame();
JTextArea textarea = new JTextArea();
frame.setSize(300, 300);
frame.add(textarea);
frame.setVisible(true);
String text=textarea.getText();
int count = 0;
for(int i=0;i>=text.length();i++) {
char spacecount = text.charAt(i);
if(spacecount==' ') {
System.out.print(count++);
}
}
}
}
I believe it should be < not >= for the 'for' loop condition.
Your for loop is as follows:
for(int i=0; i>=test.length();i++){
char spacecount = test.charAt(i);
if(spacecount==' '){
System.out.println(count++);
}
}
Let us take a walk through the for loop. The first part says, we create an int called i and initialize it to 0;
i = 0;
Next part says, keep looping while this condition is true. So it will loop while
i >= test.length()
The next part says, after each iteration, let us add 1 to i. The only reason it could possibly run is
if test.length() == 0;
if test.length() == 1;
0 is not >= 1 so it won't run. That means, the only reason it could run is if the length is 0. Now if the string is of length 0, it would be "".
What is the charAt(0)? Nothing. There is no 0 index. If the String were "a". Then charAt(0) would return "a". It is reaching for something that does not exist and therefore will not run. So one of the problems is that you need to change the condition to < instead of >=. Next, it is recommended to use camel case for fields (such as spacecount) which means you should change it to spaceCount.
Lastly, it may not occur in this case but let us say, test = null. What happens? What is null.length()? Is that even possible? Well actually it will compile in the case that test = null; and then test.length() is executed. However, you cannot call such a method on a null value so you will get the dreaded runtime error, the "NullPointerException". This says, uh oh. We have a string that points to null. Well we cannot do anything with it. Here comes the exception. So in future code, it is recommended to be able to account for such cases. So what do we do? How do we check if a String == null? Well... String == null. So in the future, if it is possible for something to be null, put the for loop in an if statement that says:
if(test != null){
//put for loop here
} else{
//do something else
}
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 am trying to get a Save button to enable/disable based on if the EditTexts actually change, but my string comparison is not working at all.
public void afterTextChanged(Editable editable) {
String newSet = editable.toString();
newSet = newSet.trim();
if(!newSet.equals(ip) || !newSet.equals(port) || !newSet.equals(username) || !newSet.equals(password)){
saveButton.setEnabled(true);
}else{
saveButton.setEnabled(false);
}
}
It keeps telling me the strings are different even though they aren't. Even when I print it out I get exactly the same String back.
Can anyone help me?
Thanks
Probably you want && instead of ||:
public void afterTextChanged(Editable editable) {
String newSet = editable.toString().trim();
saveButton.setEnabled(!newSet.equals(ip) &&
!newSet.equals(port) &&
!newSet.equals(username) &&
!newSet.equals(password));
}
enable saveButton if newSet is not a ip, port, username or password
You should write it like that, way easier to read :
if (!Arrays.asList(ip, port, username, password).contains(newSet))
{
saveButton.setEnabled(true);
}
else
{
saveButton.setEnabled(false);
}
Or :
saveButton.setEnabled(!Arrays.asList(ip, port, username, password).contains(newSet));
newSet can't be equal to all four of these Strings, unless all 4 are equal to each other. Therefore the condition will most likely return false.
If you require that newSet be equal to either one of those 4 Strings, the correct condition would be :
if(!(newSet.equals(ip) || newSet.equals(port) || newSet.equals(username) || newSet.equals(password)))
replace || with &&
if(!newSet.equals(ip) && !newSet.equals(port) && !newSet.equals(username) && !newSet.equals(password))
Reason :
OR(||) If any condition get satisfied it will enter inside the loop.
AND(&&) If all conditions get satisfied then and then only it will enter inside the loop.
In your case you need to satisfy all the conditions, that's why use and operator instead of or operator.
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 9 years ago.
Improve this question
I'm trying to set up a while loop as follows:
while(!data.equals("String");
Whenever I run this code, I get a NullPointerException.
Why is this?
If I change the code to:
while(data.equals("String");
I get no such exception, so there must be data in data, correct?
EDIT: Adding real code at the behest of commentors.
The following code is a method that attempts to convert infix notation into postfix notation.
public static Queue infixConvert (LinkedListTest infix){
Stack stack = new Stack();
Queue postfix = new Queue();
while(infix.head.data != "EOF"){
if(isNumber(infix.head.data)){
postfix.insert(infix.head.data);
System.out.println("Insert Queue");
System.out.println("Operator");
}
else if (infix.head.data.equals("(") || infix.head.data.equals(")")){
if(("(").equals(infix.head.data)){
stack.push(infix.head.data);
System.out.println("Open paren");
}
else {
infix.delete(")");
while(!"(".equals(stack.head.data)){
stack.delete(")");
postfix.insert(stack.pop());
System.out.println("Insert Queue");
}
stack.delete("(");
System.out.println("Close Paren");
}
}
else{
if(!(highPrec(stack.head.data, infix.head.data))){
stack.push(infix.head.data);
System.out.println("Push onto Lesser Operand");
}
else if(highPrec(stack.head.data, infix.head.data)){
while(stack.head.data != null){
if (stack.head.data != "("){
postfix.insert(stack.pop());
}
else break;
}
stack.push(infix.head.data);
System.out.println("Push onto Greater Operand");
}
if (infix.head.data == "EOL"){
while(stack.head.data != "EOL"){
postfix.insert(stack.pop());
System.out.println("End Line");
}
}
}
System.out.println(infix.head.data);
infix.head = infix.head.next;
System.out.println("loop\n");
}
return postfix;
}
}
EDIT: Added stack trace
at Calculator.infixConvert(Calculator.java:57)
at Test.main(Test.java:7)
You could do it "Yoda-style":
while(!"String".equals(data)) {
//writing code here you must!
}
because for the case data is null then it would not cause NPE because you call equals method of the "String"
I have resolved the issue.
There was some other unintentional behavior that caused the "(" String to be removed from the stack, so when the while loop ran it would run through the entire stack until it hit null, and provided me with a NPE.