Array not accepting fourth input? - java

I'm getting an ArrayIndexOutOfBoundsException with this program and I can't figure out what the problem is. It allows the user to type 3 inputs but then just gives the error!
If anyone can see where I'm going wrong (I believe it's with the 'parts' after the .split(), but I need the delimiter) ...
public class SplittingStrings
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
//Sample input(not sorted the validation yet) "Chelsea : Arsenal : 2 : 1"
Scanner sc = new Scanner(System.in);
String results = sc.nextLine();
int count = -1;
String str = null;
String[] parts = new String[100];
parts = results.split(":");
String home_team = parts[0];
String away_team = parts[1];
String home_score = parts[2];
String away_score = parts[3];
String[] refinedArray = new String[parts.length];
for (int i = 0;i < 100; i++){
results= sc.nextLine();
for(String s : parts) {
if(s != null) { // Skips over null values. Add "|| "".equals(s)" if you want to exclude empty strings
refinedArray[++count] = s; // Increments count and sets a value in the refined array
}
}
if(sc.equals("stop")) {
Arrays.stream(parts, 0, i).forEach(System.out::println);
}
parts[i] = str;
}
}

It is because of this statement: parts[i] = str. You change value of variable parts in this statement: parts = results.split(":"); so you change size of this array (possibly lesser than 100) and in the for loop you access to an element of this array which is not existed.

Creating an array of 100 elements was pointless
String[] parts = new String[100];
You overwrote it with an array of only 4 (?)
parts = results.split(":");
Your loop goes up to 100, but parts[4] throws the exception
It's not really clear what results is supposed to be, either

Related

How to unstructure a text string that has characters and convert it to an object

I have a text string that I receive from PL/SQL. I need to convert each object that is separated by a ';'.
This is my string enter image description here
I need to get that information and create the objects that come in that string.
//all objects come in a single text string
first object is 830114921-1<,>TIGO<,>13<,>RECARGA CELULAR TIGO;
second object is 800153993-7<,>PROTOCOLO CLARO<,>426<,>PAQUECLARO 24HRS;
third object is 800153993-7<,>PROTOCOLO CLARO<,>7<,>PINES 2000;
fourth object is 900102005-1<,>GLOBAL TV TELECOMUNICACIONES<,>92<,>JOHATRUJILLO;
Example:
Class MyClass{
Integer number;
String text;
Integer number2;
String text;
}
List<MyClass> myList = new ArrayList<>();
myClass.SetNumber(830114921-1);
myClass.SetText("TIGO");
myClass.SetNumber2(13);
myClass.SetText2("RECARGA CELULAR TIGO");
myList.add(myClass);
//I can split the 4 objects but if more objects come in the text string, can //no longer be.
String str = "830114921-1<,>TIGO<,>13<,>RECARGA CELULAR TIGO;"
+ " 800153993-7<,>PROTOCOLO CLARO<,>426<,>PAQUECLARO 24HRS; "
+ "800153993-7<,>PROTOCOLO CLARO<,>7<,>PINES 2000; "
+ "900102005-1<,>GLOBAL TV TELECOMUNICACIONES<,>92<,>JOHATRUJILLO;";
String[] arrOfStr = str.split(";", 4);
List<String> list = new ArrayList<>();
for (String a : arrOfStr) {
list.add(a);
}
for (String data : list) {
String result2 = data.replaceAll("\\<,>", " ");
System.out.println(result2);
}
You can count how many ; exits in the String and then use str.split()
...
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ';') {
count++;
}
}
String[] arrOfStr = str.split(";", count);// instead of 4
...
This will solve you problem but there are better ways to do it, using a regular expression . Learn more here
Edit :
You also need to do the same thing to every attribute of your object but the counting is a little bit different :
...
count = 0;
for (int i = 1; i < arrOfStr[0].length()-1; i++) {
if (arrOfStr.charAt(i-1) == '<'arrOfStr.charAt(i) == ',' && arrOfStr.charAt(i+1) == '>') {
count++;
}
}
List<String> listOfObjectsFromSQL = new ArrayList<MyClass>();
String[] attributes = new String[count];
for (String strObj : arrOfStr) {
attributes = strObj.split("<,>", count);
//create you object
MyClass obj = new MyClass();
//fill your object with values from the query
obj.setNumber(attributes[0]);
obj.setText(attributes[1]);
obj.setNumber2(attributes[2]);
obj.setText2(attributes[3]);
//add them to your list to use them...
listOfObjectsFromSQL.add(obj);
}
...
The data is split with <,> and ; so you should easily be able to split the string and collect the data. Java has a String.split() method. First split the string object that contains all the data into an array of strings by splitting on ; and then loop over these and split them on <,>.
At this point you should be able to set your attributes according to the order of the data in the string (assuming these are ordered properly).

Java substring method giving IndexOutOfBoundsException

I am trying to separate String [] adr = {"Tel Iva +38712345", "Mail Iva ivag#gmail.com", "Tel Ana +12345678"} by looking at each of the element's first word. If the first word is Mail, it goes to String [] m, and if the first word is Tel, it goes to String [] t.
Here is my code:
public static void rep(String a, String []adr) {
int mail=0, tel=0;
for (int i=0; i<adr.length; i++) {
if(adr[i].substring(0, 3).equals("Mail")) {
mail++;
}
else tel++;
}
String [] m = new String [mail];
String [] t = new String [tel];
for(int i=0; i<adr.length; i++) {
if(adr[i].substring(0, 4).equals("Mail")) {
m[i]=adr[i].substring(5);
}
else t[i]=adr[i].substring(4);
System.out.println(adr[i].substring(0, 4));
}
}
But for some reason unknown to me, I get
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 1
which points at line m[i]=adr[i].substring(5). I really do not understand why. Any help would be appreciated.
Correct Solution. you need to two indices to track m and t array traversal.
public static void rep(String a, String []adr) {
int mail=0, tel=0;
for (int i=0; i<adr.length; i++)
{
if(adr[i].substring(0, 4).equals("Mail")) {
mail++;
}
else tel++;
}
String [] m = new String [mail];
String [] t = new String [tel];
int mIndex =0, tIndex = 0;
for(int i=0; i<adr.length; i++) {
if(adr[i].substring(0, 4).equals("Mail")) {
m[mIndex]=adr[i].substring(4);
mIndex++;
}
else
{
t[tIndex]=adr[i].substring(4);
tIndex++;
}
System.out.println(adr[i].substring(0, 4));
}
}
Well You can try this method, I once coded same type of problem when I was learning Java for the my academics. Well you can also try StringTokenizer method to do the same. Maybe they works better. I am expecting that you are going to insert the whole string not splitted one.
import java.util.*;
import java.lang.*;
import java.*;
public class stringtoken{
public static void main(String args[]){
List<String> m=new ArrayList<String>();
List<String> t=new ArrayList<String>();
String[] s={"Tel Iva +38712345", "Mail Iva ivag#gmail.com", "Tel Ana +12345678"};
for(int i=0;i<s.length;i++){
if(s[i].indexOf("Tel")==0){
t.add(s[i]);
}
else if(s[i].indexOf("Mail")==0){
m.add(s[i]);
}
}
for(int i=0;i<m.size();i++){
System.out.println(m.get(i));
}
for(int i=0;i<t.size();i++){
System.out.println(t.get(i));
}
}
}
Supposedly index you used in the substring method are correct and I will only talk about index of the array :
String [] adr = {"Tel Iva +38712345", "Mail Iva ivag#gmail.com", "Tel Ana +12345678"}
By this data,
mail array's size will be 1, max index can use for mail array is 0
tel array's size will be 2, max index can use for tel array is 1
for(int i=0; i<adr.length; i++) {
if(adr[i].substring(0, 4).equals("Mail")) {
m[i]=adr[i].substring(5);
}
else t[i]=adr[i].substring(4);
System.out.println(adr[i].substring(0, 4));
}
In this loop :
LOOP 1 : i = 0 -> t[0]=xxx; -> OK
LOOP 2 : i = 1 -> m[1]=xxx; -> ERROR, because size of m array is 1, index can only be 0
PS : you need to check the index used in substring method
suppose this sample address array (your parameter adr[])
adr[0] = Maila#a.com
adr[1] = Tele123456
adr[2] = Mailb#a.com
adr[3] = Tele123456
adr[4] = Mailc#a.com
After your first loop which is assign values to int mail and tel
mail = 3;
tel = 2
so your m and t array looks like below.
String [] m = new String [3];
String [] t = new String [2];
What happen is in your last for looping for adr (you parameter array) length which is 5.
and try to assign values to m or t, by index of adr array.
Ex : adr[3] = Tele123456
on your second loop when i = 3 your getting this value and try to assign this value to
t[3] = 123456
where actually t size is 2 and then it occur array out of bound exception.
Hope you understood the issue on your code.
Rather than array for m and t use List.
Consider below example.
public static void rep(String a, String []adr) {
List<String> mails = new ArrayList<>();
List<String> teles = new ArrayList<>();
for (int i=0; i<adr.length; i++) {
if(adr[i].substring(0, 3).equals("Mail")) {
mails.add(adr[i].substring(5));
} else {
mails.add(adr[i].substring(5));
}
}
}
**Note : please fix compile errors if there.

Use of array list and String comparison [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I need to read the names from a array list and compare them using loops and print the values from the array in the list
import java.io.*;
import java.util.*;
public class UniqueName {
public static void main(String args[]) throws IOException{
int wordcount = 0;
Scanner input = new Scanner(new FileReader("Names.txt"));
while (input.hasNextLine()) {
String line = input.nextLine();
String str [] = line.split((" "));
for ( int i = 0; i <str.length ; i ++) {
if (str [i].length() > 0) {
wordcount ++;
}
}
}
System.out.println(wordcount);
}
}
Here is what you want:
import java.io.*;
import java.util.*;
public class UniqueName {
public static void main(String args[]) throws IOException{
Scanner input = new Scanner(new FileReader("Names.txt"));
Set<String> uniqueNames = new HashSet<String>();
while (input.hasNextLine()) {
String line = input.nextLine();
String str [] = line.split((" "));
for ( int i = 0; i <str.length ; i ++) {
if (str [i].length() > 0) {
wordcount ++;
}
uniqueNames.add(str[i]);
}
}
System.out.println(wordcount);
System.out.println(uniqueNames);
}
}
Using a set, it only adds the value you pass if it doesn't already exist in it.
Then you can print it out with println(uniqueNames); which will print out each element like so: "[name1, name2, name3, ..., nameN]"
To get rid of the brackets and commas, you can use this:
String str = uniqueNames.toString();
str = str.replace('[', '');
str = str.replace(']', '');
str = str.replace(',', '');
If you want to get each one on a new line, you can change replace(',', '') to: replace(',', '\n');
here you go, try to learn something from it :)
public static void main(String args[]) throws IOException {
Scanner input = new Scanner(new FileReader("names.txt"));
// this is the arraylist to keep all the names from your file
ArrayList<String> names = new ArrayList<String>();
while (input.hasNextLine()) {
// since some of the names have spaces at the end, we pass them
// trough a cleanup method to remove the spaces
String line = clearSpaces(input.nextLine());
// add the cleaned up names to the arraylist
names.add(line);
}
// loop through all the names in the array for comparisson
for (int c = 0; c < names.size(); c++) {
// set each name to be unique until proven otherwise
boolean unique = true;
// take the name out of the array to test
String testString = names.get(c);
// loop through all the other names in the array for comparisson
for (int i = 0; i < names.size(); i++) {
// only if the indexes are different the comparisson makes sense
if (i != c) {
// take the name out of the array to test against
String tempString = names.get(i);
// test the names against each other
if (testString.equals(tempString)) {
// if they are the same then it's not unique
unique = false;
// break the loop cause we already know it's not unique
break;
}
}
}
// only if the unique boolean value is still true
// after testing against all other names
if (unique)
// print the name of that unique name
System.out.println(testString);
}
}
// returns a string clean of spaces
private static String clearSpaces(String withSpaces) {
// string builder for the string output
StringBuilder withoutSpaces = new StringBuilder();
char[] chars = withSpaces.toCharArray();
// loop the array of characters
for (char c : chars) {
// if it's not equal to 32 which corresponds to space char
if (c != 32) {
// append it to the string builder
withoutSpaces.append(c);
}
}
// return all the chars as string
return withoutSpaces.toString();
}

how to search for keywords in strings

I need to do some keywords search and print if true.
works fine if i am comparing in order. but i want to
compare the following cases and expect them to be true.
do some java programming = true
some java = true
do programming = true
and finally most importantly
programming java = true
programming java some do = true
I need to return true for all the cases mentioned above but so far it only works for case 1 and 2
public class Examples {
public static void main(String[] args) {
String[] given = new String[20];
given[0] = ("do some java programming");
given[1] = ("do some grocery shopping");
given[2] = ("play soccer at the west field");
String input = new String();
Scanner userInput = new Scanner(System.in);
System.out.println("Enter the string to compare");
input[0] = userInput.nextLine();
for (int i=0; i <20; i++){
if(given[i].contains(input))
{
System.out.println(given[i]);
}
else
{
//do nothing
}
}
}
}
Outline of one way to solve this:
Each string in given should be converted to a Set<String> that is a set of all the words in the string. Use split() on each string to get the words, then go through the list of words and add each word to the Set.
For each input string, use split() to split it into words, then create any kind of collection (a Set<String> will work, but creating a List<String> by using Arrays.asList works too.
You can then see if the collection of words from the input is a subset of the set of words in each given string by using a Set's containsAll method.
(Note that you'll have to make sure the input string isn't the empty set first. Also, if the input string has more than one occurrence of any word, this approach won't catch that, without some extra logic.)
For this Regex will be your friend.
Here's some working code to play with:
String[] matches = input[0].split(" ");
for (int i=0; i <3; i++){
for(String s: matches){
if(given[i].contains(s))
System.out.println(given[i]);
break;
}
}
}
Split the given lines and store it in a List.
Again split the input line and compare word by word.
Below is the code snippet
public class StringCompare
{
public static final String delimiter = " ";
public static void main( String[] args )
{
String[] given = new String[20];
given[ 0 ] = ( "do some java programming" );
given[ 1 ] = ( "do some grocery shopping" );
given[ 2 ] = ( "play soccer at the west field" );
List< List< String >> listLineAsWords = new ArrayList< List< String >>();
//split each line and store it as list.
for ( String line : given )
{
if ( line == null )
break;
listLineAsWords.add( Arrays.asList( line.split( delimiter ) ) );
}
//Write your own logic to get the input line
String inputLine = "programming java";
if ( compareLine( inputLine, listLineAsWords ) )
System.out.println( "The input line is part of given lines" );
}
private static boolean compareLine( String inputLine, List< List< String >> listLineAsWords )
{
if ( inputLine == null )
return false;
List< String > words = Arrays.asList( inputLine.split( delimiter ) );
for ( List< String > listOfWords : listLineAsWords )
{
boolean isPartOfLine = true;
for ( String word : words )
{
if ( !listOfWords.contains( word ) )
{
isPartOfLine = false;
break;
}
}
if(isPartOfLine)
return true;
}
return false;
}
}
Your code is almost right, yet it needs some changes
First, since in your sample code you have 3 case, it is best to define your given array length 3.
String[] given = new String[3];
Note: for more cases, you can define bigger array length; for example, if you will add other 2 cases, your array length is 5
For all reference types, the default value is null if you have array length more than you need.
read more about it here
Second, in your if statement, you want to check if input contains given element of array or not
if (input.contains(given[i])) {
code:
String[] given = new String[3];
given[0] = ("do some java programming");
given[1] = ("do some grocery shopping");
given[2] = ("play soccer at the west field");
Scanner userInput = new Scanner(System.in);
System.out.println("Enter the string to compare");
String input = userInput.nextLine();
for (int i = 0; i < given.length; i++) {
if (input.contains(given[i])) {
System.out.println(given[i]);
} else {
// System.out.println("do nothing");
}
}
output:
Modify as below assuming everything else is fine
//here initialize 'given' array
//get the user input in a string that is 'input[0]' in your case
int count = 0;
for (String s : given) {
if (s != null && s.matches(input[0])) {
//it matches and print it
} else {
//either it's not a match or the 'given' array has a null at this index
}
count++;
}
I must say, get the user input in a string. I don't understand why you have it in input array.

Split String To Array

I've been trying to split an string by a character and store each split value inside an array.
In C# it can be done by calling the .ToArray() method after the Split() but such method apparently doesn't exits in Java. So I've been trying to do this like this (rs is a string list with elements separated by #) :
String t[] = new String[10];
for (int i = 0; i < rs.size(); i++) {
t = null;
t = rs.get(i).split("#");
}
But the whole split line is passed to an index of the array like:
String x = "Hello#World" -> t[0] = "Hello World" (The string is split in one line, so the array will have only one index of 0)
My question is that how can store each spit element in an index of the array like :
t[0] = "Hello"
t[1] = "World"
It sounds like your trying to loop through a list, split them then add the arrays together? What your defining as the problem with the .split method is exactly what the split method does.
ArrayList<String> rs = new ArrayList<>();
rs.add("Hello#World");
rs.add("Foo#Bar#Beckom");
String [] t = new String[0];
for(int i=0;i<rs.size();i++) {
String [] newT = rs.get(i).split("#");
String [] result = new String[newT.length+t.length];
System.arraycopy(t, 0, result, 0, t.length);
System.arraycopy(newT, 0, result, t.length, newT.length);
t = result;
}
for(int i=0;i<t.length;i++) {
System.out.println(t[i]);
}
Works just find output is:
Hello
World
Foo
Bar
Beckom
public class Test {
public static void main(String[] args) {
String hw = "Hello#World";
String[] splitHW = hw.split("#");
for(String s: splitHW){
System.out.println(s);
}
}
}
This produced following output for me:
Hello
World
Try this way:
String string = "Hello#World"
String[] parts = string.split("#");
String part1 = parts[0]; // Hello
String part2 = parts[1]; // World
It is always good to test beforehand if the string contains a #(in this case), just use String#contains().
if (string.contains("#")) {
// Split it.
} else {
throw new IllegalArgumentException(message);
}
why are you using a loop when the problem is already solved in java..
try this
String x = "Hello#World";
String[] array = x.split("#", -1);
System.out.println(array[0]+" "+array[1]);

Categories