Java Array index out og bounds Exception when getting input in java - java

I got Java ArrayIndexOutOfBoundsException when getting String input in Java. Please help me. This is my code: I edited my code to split using : it says "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at solution2.Solution.main(Solution.java:27)
"
import java.util.Scanner;
public class Solution {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
String str = scan.next();
String strarr[] = str.split(",");
String temp = strarr[0];
String temparr[] = temp.split(".");
String temp1 = strarr[1];
String temparr1[] = temp.split(".");
int x1 = Integer.parseInt(temparr[0]);
int x2 = Integer.parseInt(temparr[1]);
int y1 = Integer.parseInt(temparr1[0]);
int y2 = Integer.parseInt(temparr1[1]);
System.out.println(distance(x2,x1,y2,y1));
}
public static int distance(int x1,int y1,int x2,int y2){
int xlen=x2-x1;
int ylen=y2-y1;
return (xlen+ylen)*10-(ylen*5);
}
}

You need to escape the dot character in the String.split() regex, otherwise any character will be matched:
String temparr[] = temp.split("\\.");
For temparr1, I think you meant to use temp1:
String temparr1[] = temp1.split("\\.");
If you are expecting double values you could use Scanner.nextDouble() instead.

Did you notice that you are assigning temp.split() to temparr1 instead of temp1.split()?
Also, split takes in a regular expression as an argument, and as it happens, the regexp . matches just about anything. So, you should correct that.
I assume, from lack of anything disproving my guess, that you are parsing an input of format 1.2,3.4, where 1,2,3, and 4 are arbitrary numbers.
Beside that, Scanner.next reads in the next token, meaning that it will read only "1" from "1.2,3.4". You have to use Scanner.nextLine.

Related

Fixed string length adding spaces and deleting exceeding char

Context:
I wish to have a fixed string lenght since I'm formatting an output file, I built 2 functions that should be applied to string based on my string length.
First function: if you want a string X char long, but you got one which is X-Y, this adds spaces 'till desired length is reached, in this particular case, Y. This seems correct, it works
public String formatSpace(String s, int desiredlength){
while (s.length()<desiredlength){
s+=" ";
}
return s;
}
Second function: if you want a string X char long but you got one which is X+Y, this "removes" char until desired length is reached, in this particular case, Y. This seems to be wrong.
public String truncString(String s, int desiredlength){
return s.substr(0,s.length()-desiredlenght);
}
Error:
I apply these two based on string length that I test in another part of code:
[...]//here i built my class
int maxlen = 60;
[...] //here there is more code but it just collects data and I already tested fields
if (field.length()<maxlen){
field = formatSpace(field,maxlen);
}else if (field.length()>maxlen){
field = truncString(field,maxlen);
}
[...] //here i put string on file
Error I get is about string index being negative, I don't know why, I tried code on paper (yes, I know it's dumb) but it works there
Why second function is not working?
Also, it would be better to make one function which format my string, how should I make it?
Solution:
Thanks to everyone who commented, I solved my problem with this single function I wrote, I don't even test string anymore, if they fit my length they're ok, else I format them:
private String formatString(String s, int length) {
while (s.length() < length) {
s += " ";
}
return s.substring(0, length);
}
Second argument in substring function is the length of your new String. Why do you have a substraction ?
This should work :
public String truncString(String s, int desiredlength){
return s.substr(0,desiredlenght);
}
I usually use something like:
private static String spaces(int width) {
// May be more efficient ways of doing this.
return String.join("", Collections.nCopies(width, " "));
}
private static String fixedWidth(String s, int width, boolean padLeft) {
String spaces = spaces(Math.max(0,width-s.length()));
return (padLeft ? spaces + s : s + spaces).substring(0, width);
}
public void test(String[] args) {
String[] tests = {"Hello", "Loooooooooooooong!!!"};
for ( String t: tests) {
System.out.println(fixedWidth(t,10,false));
System.out.println(fixedWidth(t,10,true));
}
}
Or you can try this approach for a simple one line solution.
String test="type something here";
int desiredLength=15;
System.out.println(String.format("%1$-"+desiredLength+"s", test.substring(0, desiredLength)));
The idea is => substring first to the desired length (this will happen if string is longer) and then use String format to fill to desired length with spaces ( %1$-10s is the format for left aligned string filled to 10 spaces).
You have a typo. Inside truncString you write desiredlenght instead of desiredlength.
The problem in the second function is a logic problem. Imagine you're desired length is 4 and you introduce a String which length is 6. If you do the String length - desired length you're going to obtain a String which length is 2.
A way to fix this problem is to return directly the substr: return s.substr(0,desiredLenght)

Splitting a string at a certain character in java

In this code, I'm trying to split a string at a definite position, but it doesn't work and i'm not sure what to put, knowing that I'm trying to have it in the format "xy" without spaces, commas, anything.
import java.util.*;
public class xy {
public static void main(String[] args) {
System.out.println("Enter a number with the format 'xy'. x is the row number and y the column number.");
Scanner scanner = new Scanner(System.in);
String[] xy = scanner.nextLine().split(charAt(1)); // not sure what to put here so I tried charAt but it doesn't work
String x = xy [0];
String y = xy [1];
}
}
In this code, I'm trying to split a string at a definite position, but it doesn't work and i'm not sure what to put, knowing that I'm trying to have it in the format "xy" without spaces, commas, anything
You don't have to use split, there is no delimiter in the input received. Since the expected input is of xy. Receive it as a String and use charAt:
String input = scn.nextLine();
char x = input.charAt(0);
char y = input.charAt(1);
Or
String x = input.substring(0, 1);
String y = input.substring(1);
In this case you don't need to split. You basically know that the first string should go from index 0 to n-1, and then you got a second string from n-1 to "length".
Thus: don't split; simply call substring() twice, and give the required numbers.
And as you only deal with two chards in the first place; just go:
char x = str.charAt(0);
char y = str.charAt(1);
Done.

Java: split; cannot convert string[] to string

I'm trying to set up a program that prompts the user to enter a math equation only containing addition and place it in parentheses. My code is meant to search for these equations and give back the sum of the equation.
The part I am having trouble with is when I try to split the addition signs from the code, and parse it so I can turn it into a int. But when I try to split, I get an error that says cannot convert String[] to String.
Here is the coding I have thus far:
String userinput = in.nextLine();
int parentheses;
int parenthesesclose, parse;
String usersubstring;
String split;
while (parentheses >= 0) {
parentheses = userinput.indexOf("(");
parenthesesclose = userinput.indexOf(")");
usersubstring = userinput.substring(parentheses + 1, parenthesesclose);
split = usersubstring.split(+);
split.trim();
if (split.isdigit) {
parse = Interger.parseInt(split);
}
}
Exactly as the error message tells you, String#split() returns a String[], which is a string array. Change your declaration to this:
String[] split;
You should declare variable split as String[]. split() will return you an array of Strings.
String userinput=in.nextLine();
int parentheses;
int parenthesesclose, parse;
String usersubstring;
String[] split;
while ( parentheses >= 0){
parentheses = userinput.indexOf("(");
parenthesesclose = userinput.indexOf(")");
usersubstring = userinput.substring( parentheses + 1, parenthesesclose);
split = usersubstring.split("+");
}
Method split returns an string array, so you should change the type of your split variable to an array.
Also, the multiply symbol not in brakets.
Is this declaration of variables local? If yes, you should define them, otherwise there are possible errors in the heap.

StringIndexOutOfBoundsException while converting string to char. Possible causes?

The code below is giving problems, I just need to turn a letter from a string into a character, and when I run my testing, I keep getting an error when the code gets to char c = t.charAt(0); The exact error message is:
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
I cannot get it to just turn the string letter into a char. Any tips would be greatly appreciated.
String[] zombies;
int num = 0;
Vector<Zombie> practice = new Vector<Zombie>();
String zombieString = "SZI1";
zombies = zombieString.split("");
for (String t : zombies) {
if (isNumeric(t)) {
int multiplier = Integer.parseInt(t);
String extraZombie = zombies[num - 1];
char x = extraZombie.charAt(0);
for (int i = 0; i <= multiplier; i++) {
Zombie zombie = Zombie.makeZombie(x);
practice.add(zombie);
}
} else {
char c = t.charAt(0);
//Zombie zombie = Zombie.makeZombie(c);
//practice.add(zombie);
num++;
}
}
Your split("") returns an empty string, and if you call charAt(0) on an empty string it will give this error.
To solve this you could replace the split("") operation with toCharArray(), this will directly generate an array of chars:
char[] zombies = zombieString.toCharArray();
Since it says "string index out of range 0", then your string has no characters in it. Might have something to do with the fact that you're telling String.split() to split on an empty string, when it needs a string delimiter on which to split.
Quoted:
https://stackoverflow.com/a/5235439/2214674
"SZI1".toCharArray()
But if you need strings
"SZI1".split("")
Edit: which will return an empty first value (extra empty String => [, S, Z, I,1].).

out of range error for condition statement

I don't understand why when I use the code below it throws the following exception: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at java4.main(java4.java:11)
import java.util.Scanner;
public class java4{
public static void main (String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Enter start time");
String startTime = console.nextLine();
String [] tokens = startTime.split(":");
double starttimeHours = Double.parseDouble(tokens[0]);
double startMinutes = Double.parseDouble(tokens[1]);
if (starttimeHours >=6 && starttimeHours <=9 );
int wage = 2;
System.out.println("Enter estimated hours work:");
String esthourswork = console.nextLine();
double wagedoubleNumber = Double.parseDouble(esthourswork);
if (starttimeHours >=06.0 && starttimeHours <=09.0 );
double totalPay = 2 * wage;
double totalPay1 = (Math.round(totalPay *100))/100.0;
System.out.println("Total fare:$ " + totalPay1);
}}
Because I think it is for this section of code:
if (starttimeHours >=06 && starttimeHours <=9 );
With this section when I change the <=9 to <=09 it comes up with the red cross and says:
The literal 09 of type int is out of range. But I thought int range was from 2.5 million to either way of 0.. I tried changing <=9 to <=09.0 which does not give me a red cross but still throws the same runtime error when I run it. Does anyone know how to solve this? thanks
You are using String [] tokens = startTime.split(":"); before explicitly using tokens at index 0 and 1. That is, you are assuming that whatever the user entered definitely contains at least one colon.
After you split the entered string, make sure to verify the length of your array and also make sure to verify that each individual token represents the value you want (you are using parseDouble - so make sure that each token contains a double value. The easiest way would be to just surround your conversion with try/catch and catch NumberFormatException.
Problem is probably here
double starttimeHours = Double.parseDouble(tokens[0]);
double startMinutes = Double.parseDouble(tokens[1]);
Make sure that lenght of your tokens is 2.
String [] tokens = startTime.split(":");
if(tokens.length>2) {
double starttimeHours = Double.parseDouble(tokens[0]);
double startMinutes = Double.parseDouble(tokens[1]);
your code would throw indexoutofbound when the length of tokens is less than 2.
You need to escape : in startTime like startTime.split("\\:");
// error may lie here, you will get exception when user enters string which does not contain :
String [] tokens = startTime.split(":");
double starttimeHours = Double.parseDouble(tokens[0]);
// exception is thrwon from following line as tokens[] contain only one element
double startMinutes = Double.parseDouble(tokens[1]);
06 is an octal literal in Java, which is why 09 in an error. 09.0 is a double, but since that's not the reason you get an ArrayIndexOutOfBoundsException, of course you'll still get it. See the other answers for that.

Categories