Java String Out of Bounds Exception - java

import java.util.*;
import java.lang.*;
public class pro19
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String word;
System.out.print("Enter word: ");
word = in.nextLine();
StringBuffer s = new StringBuffer(word);
int l = word.length();
for(int i = 1; i<=l; i++)
{
for(int j = i+1; j<=l; j++)
{
if(s.charAt(i)==s.charAt(j))
{
s = s.deleteCharAt(j);
l--;
}
else
continue;
}
}
System.out.println("Word after deletion of duplicate letters: "+s);
}
}
I wrote this program to delete duplicate characters as school homework.
But whenever I run it I get the following output(exercise being the input):
Enter word: exercise
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 8
at java.lang.StringBuffer.charAt(Unknown Source)
at pro19.main(pro19.java:19)
Please help and tell me where I am going wrong.

You Write
for(int i = 1; i<=l; i++)
You can Write like This
for(int i = 0; i<=l-1; i++)
{
for(int j = i+1; j<=l-1; j++)
{
if(s.charAt(i)==s.charAt(j))
{
s = s.deleteCharAt(j);
l--;
}
else
continue;
}

Correct your loop conditions :
for(int i = 1; i < l; i++)
{
for(int j = i+1; j < l; j++)
{

What about word.replaceAll("(.)\\1+", "$1") ?

Related

Sorting an array in a decreasing order in Java

I'm trying to code a program that will sort the given strings one by one first and then sorting all the strings both in decreasing order I managed to sort the string character by character but I am having trouble in sorting all the sorted (character by character) strings. I tried using the Array.sort() but it does not sort it decreasingly and it only sorts the first input not the already sorted array
package com.company;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static void sortString(String str)
{
char[] chArr = str.toCharArray();
String SortString = "";
for (int i = 0; i< chArr.length; i++)
{
for (int j = 0; j< chArr.length; j++)
{
if(chArr[i] > chArr[j])
{
char temp = chArr[i];
chArr[i] = chArr[j];
chArr[j] = temp;
}
}
}
String[] SortedString = new String[5];
for (int k = 0; k<chArr.length;k++)
{
SortString = SortString + chArr[k];
}
Arrays.sort(SortedString);
for (int counter = 0; counter<5; counter++)
{
System.out.println(SortedString[counter]);
}
}
public static void main(String[] args)
{
Scanner UserInput = new Scanner (System.in);
String[] names = new String[5];
for (int counter = 0; counter<5; counter++)
{
do
{
System.out.print("Input String #" + (counter+1) + ": ") ;
names[counter] = UserInput.next().toLowerCase();
}while(names[counter].length() > 25);
}
UserInput.close();
Arrays.sort(names);
for (int counter = 0; counter<5; counter++)
{
sortString(names[counter]);
}
}
}
static String sortString(String str)
{
char[] chArr = str.toCharArray();
for (int i = 0; i< chArr.length; i++)
{
for (int j = 0; j< chArr.length; j++)
{
if(chArr[i] > chArr[j])
{
char temp = chArr[i];
chArr[i] = chArr[j];
chArr[j] = temp;
}
}
}
return new String(chArr);
}
public static void main(String[] args)
{
Scanner UserInput = new Scanner (System.in);
String[] names = new String[5];
for (int counter = 0; counter<5; counter++)
{
do
{
System.out.print("Input String #" + (counter+1) + ": ") ;
names[counter] = UserInput.next().toLowerCase();
}while(names[counter].length() > 25);
}
UserInput.close();
// Arrays.sort(names); No point sorting here
String[] strings = new String[5];
for (int counter = 0; counter<5; counter++)
{
strings[counter] = sortString(names[counter]);
}
Arrays.sort(strings);
// increasing order:
for(String s : strings) {
System.out.println(s);
}
// decreasing order:
for(int i = 4; i >= 0; i--) {
System.out.println(strings[i]);
}
}

NZEC error on Hackerearth in java

I am getting NZEC exception in java for below code on hackerearth. Can anyone please help?
Added the try catch block as well
import java.util.HashMap;
import java.util.Scanner;
class TestClass {
public static void main(String args[]) throws Exception {
try {
Scanner sc = new Scanner(System.in);
String S = new String();
HashMap<Long, String> hm = new HashMap<>();
S = sc.nextLine();
int len = sc.nextInt();
long[] q = new long[len];
for (int i = 0; i < len; i++) {
q[i] = sc.nextLong();
}
Long key = (long) 1;
for (int i = 0; i < S.length(); i++) {
for (int j = i + 1; j <= S.length(); j++) {
hm.put(key++, S.substring(i, j));
}
}
for (int i = 0; i < len; i++) {
if (q[i] <= hm.size())
System.out.println(hm.get(q[i]));
else {
System.out.println(-1);
}
}
} catch (Exception e) {
}
}
}
It mostly occurs when negative array index is accesed or the program which we have written takes up more space than the allocated memory for our program to run.

Sorting strings alphabetically in an array. Java

I have to sort strings in an array for a school project. Our teacher won't allow us to use array,sort().
i have to use 2 sort methods but they aren't working too well.
The first one returns double of each value. ie John, jack, adam, tom will return adam,adam,jack,jack,john,john,tom,tom.
public static void sort() {
inputFileNames();//inputs list of names from a file.
for (int i = 0; i < size - 1; i++) {
for (int j = i + 1; j < size; j++) {
if (stArr[i].compareTo(stArr[j])>0) {
temp = stArr[i];
stArr[i] = stArr[j];
stArr[j] = temp;
}
}
}
display("The names are: ");// method to display array
System.out.println("");
}
the second sort doesn' run:
public static void bubbleSort() {
inputFileNames();
for (int i = size - 1; i >= 0; i--) {
for (int j = 0; j <= i; j++) {
if (stArr[j].compareTo(stArr[j+1])>0) {
temp = stArr[j];
stArr[j] = stArr[j + 1];
stArr[j + 1] = temp;
}
}
}
display("The names are: ");
System.out.println("");
}
input and display:
static void display(String heading) {
System.out.println(heading + "\n");
for (int i = 0; i < size; i++) {
System.out.println(stArr[i]);
}
}
static void inputFileNames() {
try {
Scanner scFile = new Scanner(new File("Names.txt"));
while (scFile.hasNext()) {
stArr[size] = scFile.nextLine();
size++;
}
} catch (FileNotFoundException ex) {
System.out.println("File not found.");
}
}
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{ Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i,j;
String[] stArr = new String[n];
for(i=0;i<n;i++)
{
stArr[i]=sc.next();
// System.out.println(stArr[i]);
}
//inputs list of names from a file.
for (i = 0; i < n ; i++) {
for (j = i+1 ; j < n; j++) {
if (stArr[i].compareTo(stArr[j])>0)
{
String temp = stArr[i];
stArr[i] = stArr[j];
stArr[j] = temp;
// System.out.println(stArr[i]);
// System.out.println(stArr[j]);
}
}
}
for(i=0;i<n;i++)
{
System.out.println(stArr[i]);
}
// your code goes here
}
}
This Is the answer for first code. I am not good in file handling so you have to use your input method. I know Scanner thats why i have used here.
In Your Second Example Your j loop is wrong it should be for ( j = 0; j <= i-1; j++). And Please Mark It as answer if your problem is solved

How to read values into 2 dimensional array in java

5
1,0,1,1,1
1,1,1,1,1
0,0,0,1,1
0,1,0,1,0
1,0,0,1,1
I am trying to store the above values into 2-d array. My code is for this problem is given below. I don't know why it doesn't stores the values.
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
System.out.println(n);
String[][] multi = new String[n][n];
int i=0;
int t=n;
while(t>0){
String s=scan.nextLine();
String b[]=s.split(",");
for(int j=0;j<b.length;j++){
//System.out.print(b[j]+" ");
multi[i][j]=b[j];
}
//System.out.println();
i++;
t--;
}
System.out.println(multi[0][0]);
for(int k=0;i<n;i++){
for(int j=0;j<n;j++){
System.out.print(multi[k][j]+" ");
System.out.println();
}
}
}
But it doesn't stores.Can any one help me to solve my problem.
Tell me how to do this.
Change
> for(int k=0;i<n;i++)
to
> for(int k=0;k<n;k++)
EDIT:
Change final for loop to:
for(int k=0;i<n;i++){
for(int j=0;j<n;j++){
System.out.print(multi[k][j]+" ");
}
System.out.println();
}
And your final code looks like:
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int n=Integer.parseInt(scan.nextLine());
String[][] multi = new String[n][n];
int i=0;
int t=0;
while(t<n){
String s=scan.nextLine();
String b[]=s.split("\\,");
for(int j=0;j<b.length;j++){
multi[i][j]=b[j];
}
i++;
t++;
}
System.out.println(multi[0][0]);
for(int k=0;k<n;k++){
for(int j=0;j<n;j++){
System.out.print(multi[k][j]+" ");
}
System.out.println();
}
}
Good Luck.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine());
String[][] multi = new String[n][n];
int i = 0;
int t = n;
while (t > 0) {
String s = scan.nextLine();
String b[] = s.split(",");
for (int j = 0; j < b.length; j++) {
multi[i][j] = b[j];
}
i++;
t--;
}
for (int k = 0; k < n; k++) {
for (int j = 0; j < n; j++) {
System.out.print(multi[k][j] + " ");
System.out.println();
}
}
}
Please replace
int n=scan.nextInt()
by int n=scan.nextLine()

Code detects string as having duplicate letters, even when it does not

I wrote a program to check whether a word does not have any duplicate letters. There are two problems I am having:
1 - I wrote this in object oriented code and I am having an issue calling my main method.
2- When I had the code in one method - not broken up into pieces - the Boolean was not changing base on my checkLetters method. The output was the same - no matter what the test value was.
I am a java beginner and I would appreciate any advice.
Thank you!
import java.util.Scanner;
public class uniqueLetters
{
boolean isUnique;
char temp;
int i = 0;
String str;
char[] letters;
public static void main(String[] args)
{
testWord testing = new testWord();
}
private void testWord()
{
getArray();
checkLetters();
getStatement();
}
private void getArray()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter your word:");
str = keyboard.nextLine();
letters = str.toCharArray();
}
private boolean checkLetters()
{
boolean isUnique = true;
for (i = 0; i < letters.length; i++)
{
for (int j = 0; j < letters.length; j++)
{
if (letters[i] == letters[j])
isUnique = false;
}
}
return isUnique;
}
private void getStatement()
{
if (checkLetters())
System.out.print("This word has all unique letters");
else
System.out.print("This word has duplicate letters");
}
}
In you loop you do
for (i = 0; i < letters.length; i++)
{
for (int j = 0; j < letters.length; j++)
{
if (letters[i] == letters[j])
isUnique = false;
break;
}
}
but as the second loop is also starting at 0, then it will always find a duplicate.
try
for (i = 0; i < letters.length; i++)
{
for (int j = i + 1; j < letters.length; j++)
{
if (letters[i] == letters[j])
isUnique = false;
}
}
Also, as you are calling checkLetters from getStatement then you do not need to call it from the testWord method.
Also as testWorld is a method not a class, you should not instantiate it, just call it.

Categories

Resources