I am getting ArrayIndexOutOfBoundsException while running below code. I am trying to calculate total number of non-duplicate sub string values in a string. I added try catch to stop this exception. Mostly i am getting in line s2[j]=s2[k];.
public class SubStrLen2 {
public static int StrLen1(String s) {
int n = s.length();
int count=0, flag=0;
char[] s1 = s.toCharArray();
char[] s2 = s1;
// char[] s3;
for(int i=0; i<=n;i++)
{
for(int j =0;j<i; j++)
{
if(s1[i] == s2[j])
{
if(i!=j) {
flag = 1;
for(int k=j+1;k<=n;k++,j++)
{
s2[j]=s2[k];
}
break;
}
}
}
if(flag==0)
{
//s3[i]=s1[i];
count ++;
}
flag =0;
}
return count;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String sc = "GreekGods";
try {
System.out.println("Length of the Sub str"+ StrLen1(sc));
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Error in Array");
}
}
}
There are multiple observation, a loop index start with 0 should end at total length -1, so If n is your length of Array you code be should be
for(int i=0; i<n;i++)
the same problem is at
for(int k=j+1;k<=n;k++,j++)
here you are not only using = sign which will cause ArrayIndexOutOfBoundsException, but you are also incrementing j, which is part of parent loop unless it is intended, you might not get the desired result.
Related
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
In my program, the user enters a string, and it first finds the largest mode of characters in the string. Next, my program is supposed to remove all duplicates of a character in a string, (user input: aabc, program prints: abc) which I'm not entirely certain on how to do. I can get it to remove duplicates from some strings, but not all. For example, when the user puts "aabc" it will print "abc", but if the user puts "aabbhh", it will print "abbhh." Also, before I added the removeDup method to my program, it would only print the maxMode once, but after I added the removeDup method, it began to print the maxMode twice. How do I keep it from printing it twice?
Note: I cannot convert the strings to an array.
import java.util.Scanner;
public class JavaApplication3 {
static class MyStrings {
String s;
void setMyStrings(String str) {
s = str;
}
int getMode() {
int i;
int j;
int count = 0;
int maxMode = 0, maxCount = 1;
for (i = 0; i< s.length(); i++) {
maxCount = count;
count = 0;
for (j = s.length()-1; j >= 0; j--) {
if (s.charAt(j) == s.charAt(i))
count++;
if (count > maxCount){
maxCount = count;
maxMode = i;
}
}
}
System.out.println(s.charAt(maxMode)+" = largest mode");
return maxMode;
}
String removeDup() {
getMode();
int i;
int j;
String rdup = "";
for (i = 0; i< s.length(); i++) {
int count = 1;
for (j = 0; j < rdup.length(); j++) {
if (s.charAt(i) == s.charAt(j)){
count++;
}
}
if (count == 1){
rdup += s.charAt(i);
}
}
System.out.print(rdup);
System.out.println();
return rdup;
}
}
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
MyStrings setS = new MyStrings();
String s;
System.out.print("Enter string:");
s = in.nextLine();
setS.setMyStrings(s);
setS.getMode();
setS.removeDup();
}
}
Try this method...should work fine!
String removeDup()
{
getMode();
int i;
int j;
String rdup = "";
for (i = 0; i< s.length(); i++) {
int count = 1;
for (j = i+1; j < s.length(); j++) {
if (s.charAt(i) == s.charAt(j)) {
count++;
}
}
if (count == 1){
rdup += s.charAt(i);
}
}
// System.out.print(rdup);
System.out.println();
return rdup;
}
Welcome to StackOverflow!
You're calling getMode() both outside and inside of removeDup(), which is why it's printing it twice.
In order to remove all duplicates, you'll have to call removeDup() over and over until all the duplicates are gone from your string. Right now you're only calling it once.
How might you do that? Think about how you're detecting duplicates, and use that as the end condition for a while loop or similar.
Happy coding!
Shouldn't this be an easier way? Also, i'm still learning.
import java.util.*;
public class First {
public static void main(String arg[])
{
Scanner sc= new Scanner(System.in);
StringBuilder s=new StringBuilder(sc.nextLine());
//String s=new String();
for(int i=0;i<s.length();i++){
String a=s.substring(i, i+1);
while(s.indexOf(a)!=s.lastIndexOf(a)){s.deleteCharAt(s.lastIndexOf(a));}
}
System.out.println(s.toString());
}
}
You can do this:
public static void main(String[] args) {
String str = new String("PINEAPPLE");
Set <Character> letters = new <Character>HashSet();
for (int i = 0; i < str.length(); i++) {
letters.add(str.charAt(i));
}
System.out.println(letters);
}
I think an optimized version which supports ASCII codes can be like this:
public static void main(String[] args) {
System.out.println(removeDups("*PqQpa abbBBaaAAzzK zUyz112235KKIIppP!!QpP^^*Www5W38".toCharArray()));
}
public static String removeDups(char []input){
long ocr1=0l,ocr2=0l,ocr3=0;
int index=0;
for(int i=0;i<input.length;i++){
int val=input[i]-(char)0;
long ocr=val<126?val<63?ocr1:ocr2:ocr3;
if((ocr& (1l<<val))==0){//not duplicate
input[index]=input[i];
index++;
}
if(val<63)
ocr1|=(1l<<val);
else if(val<126)
ocr2|=(1l<<val);
else
ocr3|=(1l<<val);
}
return new String(input,0,index);
}
please keep in mind that each of orc(s) represent a mapping of a range of ASCII characters and each java long variable can grow as big as (2^63) and since we have 128 characters in ASCII so we need three ocr(s) which basically maps the occurrences of the character to a long number.
ocr1: (char)0 to (char)62
ocr2: (char)63 to (char)125
ocr3: (char)126 to (char)128
Now if a duplicate was found the
(ocr& (1l<<val))
will be greater than zero and we skip that char and finally we can create a new string with the size of index which shows last non duplicate items index.
You can define more orc(s) and support other character-sets if you want.
Can use HashSet as well as normal for loops:
public class RemoveDupliBuffer
{
public static String checkDuplicateNoHash(String myStr)
{
if(myStr == null)
return null;
if(myStr.length() <= 1)
return myStr;
char[] myStrChar = myStr.toCharArray();
HashSet myHash = new HashSet(myStrChar.length);
myStr = "";
for(int i=0; i < myStrChar.length ; i++)
{
if(! myHash.add(myStrChar[i]))
{
}else{
myStr += myStrChar[i];
}
}
return myStr;
}
public static String checkDuplicateNo(String myStr)
{
// null check
if (myStr == null)
return null;
if (myStr.length() <= 1)
return myStr;
char[] myChar = myStr.toCharArray();
myStr = "";
int tail = 0;
int j = 0;
for (int i = 0; i < myChar.length; i++)
{
for (j = 0; j < tail; j++)
{
if (myChar[i] == myChar[j])
{
break;
}
}
if (j == tail)
{
myStr += myChar[i];
tail++;
}
}
return myStr;
}
public static void main(String[] args) {
String myStr = "This is your String";
myStr = checkDuplicateNo(myStr);
System.out.println(myStr);
}
Try this simple answer- works well for simple character string accepted as user input:
import java.util.Scanner;
public class string_duplicate_char {
String final_string = "";
public void inputString() {
//accept string input from user
Scanner user_input = new Scanner(System.in);
System.out.println("Enter a String to remove duplicate Characters : \t");
String input = user_input.next();
user_input.close();
//convert string to char array
char[] StringArray = input.toCharArray();
int StringArray_length = StringArray.length;
if (StringArray_length < 2) {
System.out.println("\nThe string with no duplicates is: "
+ StringArray[1] + "\n");
} else {
//iterate over all elements in the array
for (int i = 0; i < StringArray_length; i++) {
for (int j = i + 1; j < StringArray_length; j++) {
if (StringArray[i] == StringArray[j]) {
int temp = j;//set duplicate element index
//delete the duplicate element by copying the adjacent elements by one place
for (int k = temp; k < StringArray_length - 1; k++) {
StringArray[k] = StringArray[k + 1];
}
j++;
StringArray_length--;//reduce char array length
}
}
}
}
System.out.println("\nThe string with no duplicates is: \t");
//print the resultant string with no duplicates
for (int x = 0; x < StringArray_length; x++) {
String temp= new StringBuilder().append(StringArray[x]).toString();
final_string=final_string+temp;
}
System.out.println(final_string);
}
public static void main(String args[]) {
string_duplicate_char object = new string_duplicate_char();
object.inputString();
}
}
Another easy solution to clip the duplicate elements in a string using HashSet and ArrayList :
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
public class sample_work {
public static void main(String args[]) {
String input = "";
System.out.println("Enter string to remove duplicates: \t");
Scanner in = new Scanner(System.in);
input = in.next();
in.close();
ArrayList<Character> String_array = new ArrayList<Character>();
for (char element : input.toCharArray()) {
String_array.add(element);
}
HashSet<Character> charset = new HashSet<Character>();
int array_len = String_array.size();
System.out.println("\nLength of array = " + array_len);
if (String_array != null && array_len > 0) {
Iterator<Character> itr = String_array.iterator();
while (itr.hasNext()) {
Character c = (Character) itr.next();
if (charset.add(c)) {
} else {
itr.remove();
array_len--;
}
}
}
System.out.println("\nThe new string with no duplicates: \t");
for (int i = 0; i < array_len; i++) {
System.out.println(String_array.get(i).toString());
}
}
}
your can use this simple code and understand how to remove duplicates values from string.I think this is the simplest way to understand this problem.
class RemoveDup
{
static int l;
public String dup(String str)
{
l=str.length();
System.out.println("length"+l);
char[] c=str.toCharArray();
for(int i=0;i<l;i++)
{
for(int j=0;j<l;j++)
{
if(i!=j)
{
if(c[i]==c[j])
{
l--;
for(int k=j;k<l;k++)
{
c[k]=c[k+1];
}
j--;
}
}
}
}
System.out.println("after concatination lenght:"+l);
StringBuilder sd=new StringBuilder();
for(int i=0;i<l;i++)
{
sd.append(c[i]);
}
str=sd.toString();
return str;
}
public static void main(String[] ar)
{
RemoveDup obj=new RemoveDup();
Scanner sc=new Scanner(System.in);
String st,t;
System.out.println("enter name:");
st=sc.nextLine();
sc.close();
t=obj.dup(st);
System.out.println(t);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication26;
import java.util.*;
/**
*
* #author THENNARASU
*/
public class JavaApplication26 {
public static void main(String[] args) {
int i,j,k=0,count=0,m;
char a[]=new char[10];
char b[]=new char[10];
Scanner ob=new Scanner(System.in);
String str;
str=ob.next();
a=str.toCharArray();
int c=str.length();
for(j=0;j<c;j++)
{
for(i=0;i<j;i++)
{
if(a[i]==a[j])
{
count=1;
}
}
if(count==0)
{
b[k++]=a[i];
}
count=0;
}
for(m=0;b[m]!='\0';m++)
{
System.out.println(b[m]);
}
}
}
i wrote this program. Am using 2 char arrays instead. You can define the number of duplicate chars you want to eliminate from the original string and also shows the number of occurances of each character in the string.
public String removeMultipleOcuranceOfChar(String string, int numberOfChars){
char[] word1 = string.toCharArray();
char[] word2 = string.toCharArray();
int count=0;
StringBuilder builderNoDups = new StringBuilder();
StringBuilder builderDups = new StringBuilder();
for(char x: word1){
for(char y : word2){
if (x==y){
count++;
}//end if
}//end inner loop
System.out.println(x + " occurance: " + count );
if (count ==numberOfChars){
builderNoDups.append(x);
}else{
builderDups.append(x);
}//end if else
count = 0;
}//end outer loop
return String.format("Number of identical chars to be in or out of input string: "
+ "%d\nOriginal word: %s\nWith only %d identical chars: %s\n"
+ "without %d identical chars: %s",
numberOfChars,string,numberOfChars, builderNoDups.toString(),numberOfChars,builderDups.toString());
}
Try this simple solution for REMOVING DUPLICATE CHARACTERS/LETTERS FROM GIVEN STRING
import java.util.Scanner;
public class RemoveDuplicateLetters {
public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
System.out.println("enter a String:");
String s=scn.nextLine();
String ans="";
while(s.length()>0)
{
char ch = s.charAt(0);
ans+= ch;
s = s.replace(ch+"",""); //Replacing all occurrence of the current character by a spaces
}
System.out.println("after removing all duplicate letters:"+ans);
}
}
In Java 8 we can do that using
private void removeduplicatecharactersfromstring() {
String myString = "aabcd eeffff ghjkjkl";
StringBuilder builder = new StringBuilder();
Arrays.asList(myString.split(" "))
.forEach(s -> {
builder.append(Stream.of(s.split(""))
.distinct().collect(Collectors.joining()).concat(" "));
});
System.out.println(builder); // abcd ef ghjkl
}
Make the user enter 5 integer values into the array in the main method. Pass array into a separate function. There, check for duplicated values in the array. If duplicates are found, eliminate the duplicate integer and replace it with -1.
Print the processed array back in the main method.. i think i know how to replace the value with -1 but how do I return the array to the main back again. The code is:
package methods;
import java.util.*;
public class remdup {
public static void main (String[]args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter 5 integers: ");
int [] x= new int [5];
for (int i=0; i<5; i++) {
x[i]=in.nextInt();
}
check(x);
// Insert method here
}
//Method check starts here...
public static void check(int []y) {
// int pos = y[0];
int len=y.length;
int i=0;
int j = i+1;
for (i=0; i<len-1; i++) {
for (j=i+1; j<len-1;j++ ) {
if (y[i]==y[j]) {
//how to replace numbers???
y[i]=-1;
System.out.println("Duplicate found");
}
}
}
}
}
use a Set to keep track of the numbers you already have. Iterate over your array and check if the set contains the number at your current position. if yes: replace it with -1. if no: add the number to the set...
public static void check(int []y) {
Set<Integer> foundNumbers = new HashSet<Integer>();
for(int index = 0; index < y.length; index++) {
if(foundNumbers.contains(y[index]) {
y[index] = -1;
} else {
foundNumbers.add(y[index]);
}
}
}
you replace number in the array like this:
y[i] = -1;
but your check function will not work this way.
Since this is homework, I will not go into details however, if you look at your check function:
public static void check(int []y) {
// int pos = y[0];
int len=y.length;
int i=0;
int j = i+1;
for (i=0; i<len-1; i++) {
if (y[i]==y[j]) {
//how to replace numbers???
System.out.println("Duplicate found");
}
}
}
You will notice that you are initially setting j to 1, but you are never updating its value. So in your for loop, you need to update the value of j at the end of each iteration.
You also need to include an extra loop, one which holds the current number and another one which checks the rest. Lastly, to overwrite the value you have, simply write to the array like so: y[i] = -1.
Change your whole like this way
import java.util.*;
public class test1 {
public static void main (String[]args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter 5 integers: ");
int [] x= new int [5];
for (int i=0; i<5; i++) {
x[i]=in.nextInt();
}
int z[]=check(x);
for(int o=0;o<z.length;o++)
{
System.out.println(z[o]);
}
// Insert method here
}
//Method check starts here...
public static int[] check(int []y) {
// int pos = y[0];
int len=y.length;
int i=0;
//int j = i+1;
for (i=0; i<len; i++) {
for(int j=0;j<i;j++)
{
if (y[i]==y[j]) {
//how to replace numbers???
y[i]=-1;
// System.out.println("Duplicate found");
}
} }
for(int k=0;k<len;k++)
{
//System.out.println(y[k]);
}
return y;
}
}
This will work for you.
public static void main(String[] args){
Scanner in = new Scanner (System.in);
System.out.println("Enter 5 integers: ");
Map<Integer,Integer> map=new HashMap<>();
int [] x= new int [5];
for (int i=0; i<5; i++) {
int val=in.nextInt();
x[i]=val;
Integer iniVal=map.get(val);
if(iniVal==null){
iniVal=0;
}
map.put(val,iniVal+1);
}
int[] y=getNewArr(x,map);
for (int i=0;i<y.length;i++){
System.out.println(y[i]);
}
}
public static int[] getNewArr(int[] x,Map<Integer,Integer> map){
for(int i=0;i<x.length;i++){
int numElement=map.get(x[i]);
if(numElement!=1){
for(int j=0;j<i;j++){
if(x[i]==x[j]){
x[i]=-1;
}
}
}
}
return x;
}
input array: {1,4,5,1,2}
Output array: {1,4,5,-1,2}
Though this is a very old post I think there is an error in the accepted answer. We should be adding the replaced number back to the array. However in the accepted answer we are replacing it with -1 but we are never adding it back to SET.
Below is my corrected solution :
public static Set<Integer> check(int []y) {
Set<Integer> foundNumbers = new HashSet<Integer>();
for(int index = 0; index < y.length; index++) {
if(foundNumbers.contains(y[index])){
y[index] = -1;
}
foundNumbers.add(y[index]);
}
return foundNumbers;
}
The problem states the following: given a string and a character by the user find the number of times the character (given by the user) repeats itself in the string (also given by the user).
I have this piece of code
public int repeticion (int s){
int return = 0;
int cont = 0;
Scanner in = new Scanner(System.in);
System.out.println("Write a string: ");
String chain = in.next();
System.out.println("Write the character: ");
String character = in.next();
if (chain.contains(character)) {
cont = cont + 1;
}
System.out.println("The character repeats itself "+cont+"times");
return return;
But as you can see the .contains only counts the character once, not the number of times it appears in the string.
.contains() only says that a character exists within a string, not how many. You need to iterate over each character of a string to check if it equals the character you are searching for.
String chain = "your string";
int cont = 0;
for(int i=0; i<chain.length(); i++) {
if(chain.charAt(i) == character) {
cont++;
}
}
You could also repeatedly check that the character is in the string, get that index, then check the substring from after that index to the end of the string. I recommend the following:
int index = 0;
int count = 0;
while (chain.indexof(character, index) != -1 && index < chain.length()-1) {
index = chain.indexof(character, index) + 1;
count++;
}
Contains will simply tell you if the character is present. To actually count the number of times that character would appear, you'll need to iterate over the string and count the number of times the selected character appears. This method will work:
public countACharacter(char thecharacter, String stringtocountcharactersin) {
int count = 0;
for(int i = 0; i < stringtocountcharactersin.length(); i++) {
if(stringtocountcharactersin.charAt(i) == thecharacter) {
count++;
}
}
return count;
}
import java.io.*;
public class Duplicate {
public static void main(String[] args) throws IOException {
int distinct = 0;
int i = 0, j = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter STRING : -");
String s = br.readLine();
try {
for (i = 0; i < s.length(); i++) {
while (s != null) {
s = s.trim();
for (j = 0; j < s.length(); j++) {
if (s.charAt(i) == s.charAt(j)) {
distinct++;
}
}
System.out.println(s.charAt(i) + "--" + distinct);
String d = String.valueOf(s.charAt(i));
s = s.replaceAll(d, " ");
distinct = 0;
}
}
} catch (Exception e) {}
}
}
public static void chars( String a, char k)
{
String z=""+k;
int s=0;
for(int i=0;i<a.length();i++)
{
if(z.equals(a.substring(i,i+1)))
s++;
}
System.out.println(s);
}
you can achieve your goal this way you're taking the integer s without any reason and what you're doing wrong is you are using .contains() method instead of that you should compare the given char with each char of the string and use a counter for maintaining number of times of the character or you can do it this way by converting the char into a string by concatenating it with an empty string("") and then use .equals method like i have used in my code.
//With out string methods.
public static void main(String[] args) {
String ss="rajesh kumar";
Field value = null;
try {
value = String.class.getDeclaredField("value");
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// It's private so we need to explicitly make it accessible.
value.setAccessible(true);
try {
char[] values = (char[])value.get(ss);
//String is converted to char array with out string functions
for (int i = 0; i < values.length; i++) {
int count=0;
for(int j=0;j<values.length;j++)
{
if(values[i]== values[j])
{
count++;
}
}
System.out.println("\n Count of :"+values[i] +"="+count);
}
System.out.println("Values "+values[1]);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I'm trying to get the longest method to take the user-inputted array of strings, then return the element number of the longest string in that array. I got it to the point where I was able to return the number of chars in the longest string, but I don't believe that will work for what I need. My problem is that I keep getting incompatible type errors when trying to figure this out. I don't understand the whole data type thing with strings yet. It's confusing me how I go about return a number of the array yet the array is of strings. The main method is fine, I got stuck on the ???? part.
public static void main(String [] args)
{
Scanner inp = new Scanner( System.in );
String [] responseArr= new String[4];
for (int i=0; i<4; i++)
{
System.out.println("Enter string "+(i+1));
responseArr[i] = inp.nextLine();
}
int highest=longestS(responseArr);
}
public static int longestS(String[] values)
{
int largest=0
for( int i = 1; i < values.length; i++ )
{
if ( ????? )
}
return largest;
}
for (int i = 0; i < values.length; i++)
{
if (values[i].length() > largest)
{
largest = values[i].length();
index = i;
}
}
return index;
Note: initialize the int i with 0 - array index is 0-based.
Back in your main, you could then do System.out.println("Longest: " + responseArr[highest]); etc.
Here's how I'd write it:
public static int findIndexOfLongestString(String[] values)
{
int index = -1;
if ((values != null) && (values.length > 0))
{
index = 0;
String longest = values[0];
for (int i = 1; i < values.length; ++i)
{
if (values[i].length() > longest.length())
{
longest = values[i];
index = i;
}
}
}
return index;
}
You will want to store two things in your longestS method: the largest length so far, and the array index of the largest length. Also keep in mind that array indices start at 0 in Java. A for loop initialised with int i = 1 is actually going to start at the second index.
My solution:
public class JavaApplication3
{
public static void main(String[] args)
{
String[] big={"one","two","three"};
String bigstring=null;
int maxlength=0;
for(String max:big)
{
if(maxlength<max.length())
{
maxlength=max.length();
bigstring=max;
}
}
System.out.println(bigstring);
}
}