IndexOutOfBoundsException while loop executes-Java - java

package com.cp.javapractice;
import java.util.ArrayList;
import java.util.Scanner;
public class Cp {
public static void main(String args[]) {
ArrayList al = new ArrayList();
Scanner s = new Scanner(System.in);
String str = null;
str = new String();
System.out.println("Enter the string which you want to remove the duplicates");
str = s.nextLine();
String arr[] = str.split(" ");
for (int k = 0; k < arr.length; k++) {
al.add(arr[k]);
}
try {
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i].equalsIgnoreCase(arr[j])) {
al.remove(j);
}
}
}
System.out.println(al);
}
catch (Exception e) {
System.out.println(e);
}
}
}
I am going to replace the repeating words in particular given string from the user. So, I split the given string with space using split method and put in array as well as in arraylist.
After Iterate through array and checked the condition it is equal then I removed that in ArrayList. But While removing it shows Index out of bound Exception.
This code is working for small array size but shows exception while giving large number of array size.
I am having problem while I am giving the string with array size of 13 words.
Here is my full code.

for (int i = 0; i < al.size(); i++) {
for (int j = i + 1; j < al.size(); j++) {
if (al.get(i).equals(al.get(j)) {
al.remove(j);
}
}
}

The exception is because you are using arr.length instead of al.size(). For every removal, the size of the arraylist al decreases. So, you have to consider using size of arraylist instead of size of the array.
for (int i = 0; i < al.size(); i++) { // change arr.length to al.size()
for (int j = i + 1; j < al.size(); j++) { // change arr.length to al.size()
if (arr[i].equalsIgnoreCase(arr[j])) {
al.remove(j);
}
}
}
I would recommend you to check out HashSet and TreeSet which reduces your effort of removing duplicates.
Implementing in HashSet:
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Cp {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
String str = null;
str = new String();
System.out.println("Enter the string which you want to remove the duplicates");
str = s.nextLine();
String arr[] = str.split(" ");
Set<String> ts = new HashSet<String>(Arrays.asList(arr)); // -> added only this line
System.out.println(ts);
}
}

The Problem is your 2nd loop. Is Starts at i+1. But i is from 0 to length -1. So the Last ein will be j=length-1+1 which is beyond Array length.
So Change the 1st for loop to:
for(int i=0;i < arr.length-2;i++)

Related

Java Stdin Cannot convert from String[] to String, but inputs are String?

I am doing a programming assignment that takes all of its input from stdin. The first input is an int n to tell you how many strings will follow, and the next n inputs are strings of varying lengths. The goal is to find the longest string(s) and print them.
I thought this was easy, but for the life of me, I cannot get the stdin to work with me. The eclipse arguments entered are (separated by enter):
3
a2
b3c
7
Yet I run the program, and it tells me it cannot convert from String[] to String. I do not understand how any of the above are String[]. The code is below:
import java.util.Scanner;
public class A2P1 {
public static void main(String[] args) {
int size = Integer.parseInt(args[0]);
String[] str = new String[size];
Scanner sc = new Scanner(System.in);
for (int i=0; i < size; i++) {
str[i] = sc.nextLine().split(" "); // The error
//str[i] = sc.next(); This line and the line below throw
//str[i] = sc.nextLine(); no errors, but also gives no output.
}
String[] longest = new String[size];
String[] temp = new String[size];
longest[0] = str[0];
int numToBeat = str[0].length();
int k = 0;
for (int i=0; i < size; i++) {
if (str[i].length() > numToBeat) {
numToBeat = str[i].length();
k = 0;
longest = temp;
longest[k] = str[i];
k++;
}
else if (str[i].length() == numToBeat) {
longest[k] = str[i];
}
}
System.out.println("The longest input strings are:");
for (int i=0; i < k; i++) {
System.out.println(longest[i]);
}
sc.close();
}
}
Tried:
Changing str[i] = sc.nextLine().split(" "); to its other variations in the code
Changing input values
Googling stdin for the last hour trying to find any documentation that helps me
If you are using eclipse arguments separated by enter then your logic is wrong:
according to your logic get 1st element from the eclipse argument like args[0]
another Input is taken from the console.
if you need to take all elements from the eclipse argument follow the below code:
public class A2P1 {
public static void main(String[] args) {
int size = Integer.parseInt(args[0]);
String[] str = new String[size];
int length=0;
String loggestString="";
for (int i=1; i < size; i++) {
str[i] = args[i];
int strLen = str[i].length();
if(strLen>length) {
length=strLen;
loggestString=str[i];
}
}
System.out.println(loggestString);
}
}

Alphabetically sort contents of file using methods (Java)

The title might be a little misleading but I am writing a piece of code that has this as the contents of the text file:
04/26/16 Sega 3D Classics Collection
07/14/16 Batman: Arkham Underworld
06/24/16 Tokyo Mirage Sessions #FE
Essentially I want them to be in alphabetical order and it should make a brand new file that looks like this:
Batman: Arkham Underworld
Sega 3D Classics Collection
Tokyo Mirage Sessions #FE
What I have tried is to use the indexOf() method to extract only the names of the list of games from my existing text file. I have also tried to store them in a new array to avoid confusion for the computer. The problem is that when I try to store the indexOf of the info array into a new array, the line gives an error of "cannot convert from int to string" and I am not sure on how to fix the error.
This is my code below:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Main{
public static void main (String[]args) throws IOException{
File file = new File("releasedates.txt");
String []arr = input(file);
output(file,arr);
outputSort1(file, arr);
}
public static String[]input (File file) throws FileNotFoundException{
String[]arr = new String[3];
Scanner sc = new Scanner(file);
for(int i = 0; i < arr.length; i++){
arr[i] = sc.nextLine();
}
return arr;
}
public static void output(File file, String[] info) throws IOException{
FileWriter writer = new FileWriter("fileName.txt");
for(String aString:info){
writer.write(aString);
}
writer.close();
}
public static void sortByMonth(String[]info){
String temp;
for (int j = 0; j < info.length; j++) {
for (int i = j + 1; i < info.length; i++) {
if (info[i].compareTo(info[j]) < 0) {
temp = info[j];
info[j] = info[i];
info[i] = temp;
}
}
}
}
public static void outputSort1(File file,String[] info) throws IOException{
sortByMonth(info);
FileWriter writer = new FileWriter("fileNameSorted1.txt");
for(String aString:info){
writer.write(aString);
}
writer.close();
}
public static void sortByName(String[]info){
String[] names = new String[3];
for(int i = 0; i < info.length; i ++){
names[i] = info[i].indexOf(" " ,info.length);
}
String temp;
for (int j = 0; j < names.length; j++) {
for (int i = j + 1; i < names.length; i++) {
if (names[i].compareTo(names[j]) < 0) {
temp = names[j];
names[j] = names[i];
names[i] = temp;
}
}
}
}
}
You've declared names array as String[] so you can't assign integer to it. indexOf method returns integer.
public static void sortByName(String[]info) {
String[] names = new String[3]; //<-- declaration suggests store string
for (int i = 0; i < info.length; i++) {
names[i] = info[i].indexOf(" ", info.length);//<-you are assigning integer
}
I think what you are trying to do is like this:
names[i] = info[i].substring(info[i].indexOf(" "), info[i].length());
Use java.nio APIs for file implementations as java.io apis are outdated. Also, if you use Stream operations then the implementation becomes much easier:
public class Test {
public static void main(String[] args) throws Exception {
Path file = Path.of("e:\\releasedates.txt");
List<String> records = Files.readAllLines(file);
List<String> sortedByName = records.stream()
.map(s -> s.substring(s.indexOf(" "), s.length()))
.sorted(String::compareTo)
.collect(Collectors.toList());
System.out.println(sortedByName);
Files.write(Path.of("e:\\fileNameSorted.txt"), sortedByName);
List<String> sortedByDate = records.stream().sorted(Test::compareDates)
.map(s -> s.substring(s.indexOf(" "), s.length()))
.collect(Collectors.toList());
System.out.println(sortedByDate);
Files.write(Path.of("e:\\fileDateSorted.txt"), sortedByDate);
}
public static int compareDates(String d1, String d2) {
d1 = d1.substring(0, d1.indexOf(" "));
d2 = d2.substring(0, d2.indexOf(" "));
LocalDate ld1 = LocalDate.parse(d1,
DateTimeFormatter.ofPattern("MM/dd/yy"));
LocalDate ld2 = LocalDate.parse(d2,
DateTimeFormatter.ofPattern("MM/dd/yy"));
return ld1.compareTo(ld2);
}
}
Answer by #onkar ruikar is correct. indexOf returns int and you are trying to store it in String. I would like to extend his answer, where you can store the game/movie names in TreeSet instead of Array, so that by default it will be sorted in alphabetical order.
If you want to allow duplicate game/movie names, then you can use ArrayList and call Collections.sort(<array list>) method, which will sort the ArrayList in alphabetical order.
Here is the detailed answer of how can we sort Collections in Java: https://stackoverflow.com/a/8725470/3709922

Why is there no output getting displayed? Here I am trying to display two strings in alternate positions

In the below code I am trying to print two strings in a single char array in alternate positions, where second string should be stored in the reverse order.
For example: str1="happy" str2= "sadly" arr="hyalpdpays", where both strings should be of the same size.
import java.util.*;
//*class Main declaration done here*
class Main{
public static void main (String args[])
{
char[] arr=new char[100];
int flen=0;
Scanner sc=new Scanner(System.in);
String str1=sc.nextLine();
String str2=sc.nextLine();
if(str1.length()==str2.length())
{
flen = str1.length()+str2.length();
for(int i=0, j=flen, k=0; i<(flen/2) && j>=0 && k<flen; i=i+2 , j=j-2, k++)
{
arr[k]=str1.charAt(i);
k=k+1;
arr[k]=str2.charAt(i);
}
}
for(int i=0; i<flen; i++)
{
System.out.println(arr[i]);
}
}
}
I did some changes to your code this works fine with me
if(str1.length()==str2.length())
{
flen = str1.length()+str2.length();
int lastIndex = (str2.length()-1);
for(int i=0, j=lastIndex, k=0; i<flen; j--, k++,i++)
{
arr[i]=str1.charAt(k);
i++;
arr[i]=str2.charAt(j);
}
}
for(int i=0; i<flen; i++)
{
System.out.print(arr[i]);
}
so it would start in the index 0 of string 1 then the last index of string 2 and so on. the output will be as u mentioned "hyalpdpays".
You can do it simply as follows:
public class Main {
public static void main(String[] args) {
String str1 = "happy";
String str2 = "sadly";
StringBuilder sb = new StringBuilder();
if (str1.length() == str2.length()) {
for (int i = 0; i < str1.length(); i++) {
sb.append(str1.charAt(i));// Chars of str1 from beginning
sb.append(str2.charAt(str2.length() - i - 1));// Chars of str2 from end
}
} else {
System.out.println("Strings are of different lengths");
}
System.out.println(sb);
}
}
Output:
hyalpdpays

my code runs for 15mins but only white output?

I'm doing a stop word code for data cleaning. I followed a tutorial in YouTube: https://www.youtube.com/watch?v=ckQUlI7x7hI his code works and shows output but mine doesn't
I'm using english stop words, example of my stop words are "a", "an", "away", "keeps". the input will be "An apple a day keeps the doctor away" output should be "apple day the doctor".
this is the content of my file: https://ufile.io/gikev
Here is the code:
import java.io.FileInputStream;
import java.util.ArrayList;
public class DataCleaning {
public static void main(String[] args) {
ArrayList sw = new ArrayList<>();
try{
FileInputStream x = new FileInputStream("/Users/Dan/Desktop/DATA/stopwords.txt");
byte b[] = new byte[x.available()];
x.read(b);
x.close();
String data[] = new String(b).split("\n");
for(int i = 0; i < data.length; i++)
{
sw.add(data[i].trim());
}
FileInputStream xx = new FileInputStream("/Users/Dan/Desktop/DATA/cleandata.txt");
byte bb[] = new byte[xx.available()];
xx.read(bb);
xx.close();
String dataa[] = new String(bb).split("\n");
for(int i = 0; i < dataa.length; i++)
{
String file = "";
String s[] = dataa[i].split("\\s");
for(int j = 0; j < s.length; i++)
{
if(sw.contains(s[j].trim().toLowerCase()))
{
file=file + s[j] + " ";
}
}
System.out.println(file + "\n");
}
} catch(Exception a){
a.printStackTrace();
}
}
}
and when I run mine it only does this:
what should I do?
There are 3 issues with your code :
You are incrementing the wrong variable in the innermost loop thus
resulting in an infinite loop as j will always be lesser that
s.length and you are never incrementing j. Change this line :
for (int j = 0; j < s.length; i++) {
to
for (int j = 0; j < s.length; j++) {
To print words that are not stopwords you need to negate your if
condition as follows :
if (!sw.contains(s[j].trim().toLowerCase()))
Also, make sure the file stopwords.txt is separated by \n(new
line) because you are splitting it based on that and not like the
file in the link shared by you.
I recommend you to indent your code and also use meaningful names to name your variables. Debugging issues like this will be much simpler.

Java String Bubble Sorting

I need help sorting this array in alphabetical order using the bubble sort algorithm.
My code is:
public class Strings
{
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
String tempStr;
System.out.print("Enter the strings > ");
String s1 = new String(reader.nextLine());
String[] t1 = s1.split(", ");
for (int t=0; t<t1.length-1; t++)
{
for (int i = 0; i<t1.length -1; i++)
{
if(t1[i+1].compareTo(t1[1+1])>0)
{
tempStr = t1[i];
t1[i] = t1[i+1];
t1[i+1] = tempStr;
}
}
}
for(int i=0;i<t1.length;i++)
{
System.out.println(t1[i]);
}
}
}
The code compiles, but it does not sort alphabetical. Please help me.
You have three errors in your code.
The first error is in the inner for loop, in the place where you do the check statement, it should be i < t1.length - t -1 not i < t1.length -1. You subtract t because you do not want to loop through the whole array again, only the first part of it.
The second and third errors are in the if statement. You need to turn the greater than symbol into a lesser than symbol, because the way you have the compareTo method set up, it will return a negative number.
The other error in this line is that in the compareTo parameter you put 1 + 1 it actually should be just i, because you want one less than the object it is comparing to.
The fixed working code is below (Comments are what you originally had):
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String tempStr;
System.out.print("Enter the strings > ");
String s1 = new String(reader.nextLine());
String[] t1 = s1.split(", ");
for (int t = 0; t < t1.length - 1; t++) {
for (int i= 0; i < t1.length - t -1; i++) {
if(t1[i+1].compareTo(t1[i])<0) {
tempStr = t1[i];
t1[i] = t1[i + 1];
t1[i + 1] = tempStr;
}
}
}
for (int i = 0; i < t1.length; i++) {
System.out.println(t1[i]);
}
}
please change
String[] t1 = s1.split(", ");
to
String[] t1 = s1.split("");
This will solve the issue.

Categories