OutofBounds Exception [closed] - java

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
}

Related

If-else One line statement (with string and integer) [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 1 year ago.
Improve this question
I'm creating a program. This code below is the Java program. Checking if the value of B and H, input by the user is equal to zero. If it is true, then a math formula will execute which is p = b*h then if it is false, a string will be shown on the console. But the thing is, it keeps on giving me an error that string cannot be converted to int or int cannot be converted to string.
Here is the code:
import java.util.Scanner;
public class StaticProject{
static {
Scanner input = new Scanner (System.in);
int B = input.nextInt();
int H = input.nextInt();
int P;
int solution = B>=0 && H>=0 ? P = B*H : "java.lang.Exception: Breadth and height must be positive";
}
How can I improve my coding when it comes in doing this oneline bi-conditionals statement? Any tips?
your solution variable Type is int, and your else statement returns an String, this is the cause of error.
you can change your code to this:
Scanner input = new Scanner (System.in);
int B = input.nextInt();
int H = input.nextInt();
int P;
if (B >= 0 && H >= 0) {
P = B*H;
} else {
throw new Exception("Breadth and height must be positive");
}
System.out.println(P);
}
You are trying to assign string to an int variable, if your statement is evaluated as false.
You need to use if/else condition, which both sides have the same type.
In your case, it's not possible.
another possibility is use System.out.println() command, to print the result of whatever resulted by the condition.
There is no virtue in writing code in as few lines as possible. By all means, don't write unnecessary code, but just don't think that concise code is objectively "better".
The best type of code to write is simple code. Maybe it's a little more verbose; but if you write code that people can understand at a glance, they know what it does straight away.
Here is how I would write it:
if (B < 0 || H < 0) {
// Actually, non-negative, rather than positive.
throw new Exception("Breadth and height must be positive");
// Or, maybe, don't even use exceptions at all:
// System.out.println("The message");
// return;
}
// No need for `solution` variable.
P = B * H;
System.out.println(P);
Of course, you might argue this isn't code everybody will understand at a glance. Sure. Readability is subjective; but I assert that anybody with just a little bit of experience in Java can work it out.
You can write a conditional ?: expression which results in an exception being thrown in the case of the condition being false.
// Define a method which does the throwing.
static int justThrow(String message) throws Exception {
throw new Exception(message);
}
// In the main method:
int solution = B>=0 && H>=0 ? P = B*H : justThrow("Breadth and height must be positive");
I emphasize that you can, but you shouldn't do this. It's obscure. It's trying to be "a bit too clever". It will have people reading your code and scratching their heads, because they will wonder why you wrote a method for something so simple; what is the solution variable for, given that it will have the same value as P etc.

Can I return Boolean value in a loop 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 7 years ago.
Improve this question
I just came up with a problem returning a Boolean value in accordance with a given condition. I thought in order to check the given condition for full possibilities I need to use for loop. But when I tried to compile it, it gives me error, possibly because there is uncertainty returning a Boolean value using for loop. Here is an original problem:
Return true if the given string contains a "bob" string, but where the middle 'o' char can be any char.
bobThere("abcbob") → true
bobThere("b9b") → true
bobThere("bac") → false
And here is my code:
public boolean bobThere(String str)
{
for(int i=0; i<str.length()-3; i++)
{
if (str.length()>=4): && str.charAt(i)=='b' && str.charAt(i+2)=='b')
{
return true;
}
else
return false;
else if (str.length()==4 && str.charAt(0)=='b' && str.charAt(2)=='b')
{
return true;
}
else
{
return false;
}
}
}
I just wanted to ask :
1. Can I fix the this code for returning a value. I mean, can I use for loop and return specific value for a given condition? If yes, please could you give me a sample.
2. Or are there any ways other than for loop to solve this problem.
Thanks in advance.
The compiler error is almost certainly because you have an elseif after an else. That's invalid.
Looking at your code, what you seem to want to do is loop through the string, and then return true if you're at the start of a b?b string. I'm not sure why you have your second if condition in there - at the moment your code would check the first and third characters of the string on every iteration of the loop, if the string happens to be exactly four characters long. Pointless, it doesn't need to be there. The check for length isn't necessary at all.
Additionally, your end condition for the loop is currently i < string.length()-3. This means that the final three characters of the string will not be checked. You would need to change this to either i <= string.length()-3 or i < string.length()-2 to solve this.
Your else return false stuff is going to give you a serious problem. Your code will enter the loop once, and then either return true or false, without ever going to the next phase of the loop. What you should do is loop through the string, and if you find what you're looking for, return true. Otherwise, don't return at all, and keep going with the loop. If you get to the end of the loop it means you never found what you were looking for, so you can at that point return false.
Taking those comments into account, your revised code would look like this (please note I haven't compiled or run this):
public boolean bobThere(String str)
{
for(int i = 0; i <= str.length() - 3; i++)
{
if (str.charAt(i) == 'b' && str.charAt(i + 2) == 'b')
{
return true;
}
}
return false;
}

Iteration stops at zero [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
public class Main {
public static void main(String [] args) {
int i = 0;
do {
System.out.println(i);
i++;
} while (i==3);
}
}
// Outputs 0
Why do iterations stop at zero? while(i==3) is a condition, which tests for equality of i to 3. But then, even after incrementing the value of i as i++ why the output is only 0?
Because it'll print i, which is 0, then will increment it, and won't loop since 3 != 1:
do {
System.out.println(i); //i is 0, will print 0
i++; //i is now 1
} while (i==3); //false
Read The while and do-while Statements to better understand how the do-while loop works.
I'm carefully assuming that you meant to write while(i != 3);, if that's the case, your program will loop and will print 0 1 2.
Your condition would be i!=3. Change to while(i!=3). You have mistakenly put the wrong condition in the while loop. You have said it to loop the while only when i==3 otherwise to exit the loop. So you need to change it to
do {
System.out.println(i);
i++;
} while (i!=3);
Hope this clarifies!
Because you increment after printing.

How to use do while loops [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 am trying to put a password onto this section of code, I am trying to use a do while loop but it carries on looping.
Can you please show me where my errors are? The password I am using is 1234.
import javax.swing.*;
public class cipherprac
{
static int choice = 0;
public static String msg;
public static int password = 1234;
public static int response = 0;
public static void main (String[] args)
{
msg = JOptionPane.showInputDialog("Enter the message");
response = Integer.parseInt(JOptionPane.showInputDialog("Enter the password"));
do
{
char enc;
String encmsg = "";
int len = msg.length();
for (int i = 0; i < len; i++)
{
char cur = msg.charAt(i);
int val = (int) cur;
val = val - 30;
enc = (char) val;
encmsg = encmsg + enc;
msg = encmsg;
}
}
while(response == password) ;
JOptionPane.showMessageDialog(null, " " + msg);
}
}
You don't change the response (nor password) in your code, so if you set it to 1234 then it will be looping for ever.
response = Integer.parseInt(JOptionPane.showInputDialog("Enter the password")); is the last time you set "response", so it will be that forever, hence the infinite loop.
This seems to be some sort of custom encryption? Anyway, you'd want to do something like:
do
{
...
}
while(response == password && "Certain condition isn't met");
This way it will end the loop if for some reason the user input changes OR if it is done with your process.
Well you do not change the value of your password or response variable inside the loop. So how is the loop supposed to stop?
Your loop will run once and at the end check whether condition for continuing is met. If yes, it will start the next iteration of the loop code block. If you do not change anything inside the loop which has an effect on the loop's condition, it will run once (if the condition evaluates to false) or until you kill the program (if the condition evaluates to true).
As for the normal work of a loop, here you can find a good explanation with examples in many languages (including Java): Wikipedia link
There are multiple issues:
Not updating response inside the loop
While condition loops again if successful, I think it should try again on unsuccessful password if I understand correctly.
Do you want to keep trying until your password is correct?
In this case, your while condition should be true when they are not equal, so that if it is not successful, you keep trying.
In your case, if your response is not 1234, it will not try, and if it is, it will loop forever.
Ideally for a do while loop:
set condition value before loop
do{
// do some work
// update condition value
}while(condition);

Java: NullPointerException with substrings [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 having a problem in one of my methods. Please keep in mind that I am learning Java in college so I might not be up to speed on simple things. Below is a method that is made to add expressions. The problems I'm running into is found where x = x.substring.(1, x.length() - 1); I'm getting an exception that reads:
Exception in thread "main" java.lang.NullPointerException
I have no idea what that means and/or how to fix it. If you could point me in the right direction, that'd be great.
Thanks.
public static int adder(String x){
int total = 0;
x = x.substring(1, x.length() - 1);
sopln(x);
String[] nums = x.split("\\+");
for(int i = 0; i < nums.length; ++i){
if(nums[i].charAt(0) == ' ' || nums[i].charAt(nums[i].length()-1) == ' '){
sopln("ERROR: Excess whitespace identified.");
nums[i] = nums[i].trim();
}
nums[i] = nums[i].replaceAll(" ", "");
if(nums[i].charAt(0) == '-')
total -= Integer.parseInt(nums[i]);
else
total += Integer.parseInt(nums[i]);
}
return total;
}
It probably means that your String x is null and not actually set to an Object of a String.
How are you calling the method?
Does it happen when you call it with a hard coded string like
int num = adder("string checking in");
if not, then somewhere upstream in your code, that String variable you are passing into the adder method is null.
you are passing a null value when you call adder(the_string), where the_string is null
The problems I'm running into is found where x=x.substring.(1,x.length() - 1);
This means that at some point you are calling adder with an argument that is null. That's the only way you can get an NPE at that point.
Find out where and why the argument is null, and then fix it.
(It could be an explicit null, but it is more likely to be coming from an uninitialized field, or from some method that returns a null to indicate something; e.g. BufferedReader.readLine() returns null when the reader reached the EOF position.)

Categories

Resources