I'm trying to read from 2 dimensional arrays.
What this code does is that it first stores .txt file contents into 2d arrays, one line per element. It then compares user input to each array, looking for similarities. Any similarity will be stored in another array.
The thing here is that the comparing part doesn't work. Any hints as to why?
Thanks.
import java.awt.Point;
import java.io.File;
import java.util.Arrays;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
static int RowCheck =0;
static int C_Row = 0;
static int S_Row = 0;
static String lexicon[][] = new String[3000][10];
static String results[][] = new String[100][10];
private static String find2DIndex(Object[][] array, Object search) {
if (search == null || array == null) return null;
for (int rowIndex = 0; rowIndex < array.length; rowIndex++ ) {
Object[] row = array[rowIndex];
if (row != null) {
for (int columnIndex = 0; columnIndex < 2; columnIndex++) {
if (search.equals(row[columnIndex])) {
for(int i=0; i<2; i++)
for(int j=0; j<=10; j++)
lexicon[i][j]=results[i][j];
return Arrays.deepToString(results);
}
}
}
}
return null; // value not found in array
}
public static void main(String[] args) throws FileNotFoundException {
File testlex = new File("C:\\Users\\Harry\\Documents\\testlex.txt");
File testlex2 = new File("C:\\Users\\Harry\\Documents\\textlex2.txt");
Scanner cc = new Scanner(testlex2);
Scanner sc = new Scanner(testlex);
while (sc.hasNextLine()){
int column = 0;
String line = sc.nextLine();
sc.useDelimiter("/ *");
if (line.isEmpty())
continue;
C_Row = C_Row + 1;
column = 0;
String[] tokens = line.split("\\s");
for (String token : tokens) {
if (token.isEmpty())
continue;
lexicon[C_Row][column] = token;
column++;
}
}
while (cc.hasNextLine()){
int column = 0;
String line = cc.nextLine();
cc.useDelimiter("/ *");
if (line.isEmpty())
continue;
S_Row = S_Row + 1;
column = 0;
String[] tokens = line.split("\\s");
for (String token : tokens) {
if (token.isEmpty())
continue;
lexicon[S_Row][column] = token;
column++;
}
}
sc.close();
cc.close();
find2DIndex(lexicon, "abash");
System.out.println(C_Row);
}
}
This line will compare search and row[columnIndex] as objects of type Object.
if (search.equals(row[columnIndex]))
Therefore it will compare references. You seem to want to compare contents of String objects. There are 2 ways you can modify find2DIndex for this.
Change the signature to
private static String find2DIndex(String[][] array, String search)
and replace any occurrence of Object in the function with String
Turn it into a generic method
private static <T> String find2DIndex(T[][] array, T search)
and replace any occurrence of Object in the function with T
In both cases equals will now be the method of String.
Related
I am trying to print user inputs in another class in Java. I have made a chessboard which asks the user to input strings on the board, and then, when these strings are printed on screen, I would like the output to be "You have placed piece [name] at coordinate [coordinate]". I am trying to do this in another class rather in the main method, but what I have tried so far doesn't seem to work. Here's my code.
import java.util.Arrays;
import java.util.Scanner;
public class ChessBoard
{
public static void main(String[] args)
{
char rows = 'a';
String spot;
Scanner scanner = new Scanner(System.in);
String[][] grid = new String [8][8];
for(int i = 0; i < grid.length; i++, rows++)
{
for(int col = 0; col < grid[i].length; col++);
String input = null; // will be changed to a valid position
boolean validCoordinate = false; // will be true if position is valid
while ( ! validCoordinate) {
System.out.println("Enter a coordinate (for example, a5): ");
input = scanner.next();
validCoordinate = input.matches("[a-h][1-8]");
};
// now we now that the input is valid
int row = input.charAt(0) - 'a';
int col = input.charAt(1) - '1';
String temp = input + " - ";
System.out.println("Insert your piece:");
input = scanner.next();
grid[row][col] = temp + input;
}
System.out.println(Arrays.deepToString(grid));
}
}
So what I'd like to do is have a new class that uses that last print line to instead print the desired output that I mentioned earlier. Any help would be appreciated, thanks!
EDIT:
import java.util.Arrays;
import java.util.Scanner;
public class ChessBoard1
{
public static void main(String[] args)
{
userInputs input = new userInputs();
showInput show = new showInput();
String grid[][] = input.takeInput();
show.show(grid);
}
}
public class userInputs
{
public String[][] takeInput()
{
char rows = 'a';
String spot;
Scanner scanner = new Scanner(System.in);
String[][] grid = new String [8][8];
for(int i = 0; i < grid.length; i++, rows++) {
for (int col = 0; col < grid[i].length; col++) ;
String input = null; // will be changed to a valid position
boolean validCoordinate = false; // will be true if position is valid
while (!validCoordinate) {
System.out.println("Enter a coordinate (for example, a5): ");
input = scanner.next();
validCoordinate = input.matches("[a-h][1-8]");
}
;
// now we now that the input is valid
int row = input.charAt(0) - 'a';
int col = input.charAt(1) - '1';
String temp = input + " - ";
System.out.println("Insert your piece:");
input = scanner.next();
grid[row][col] = temp + input;
}
return grid;
}
}
public class showInput {
public void show(String [][] inputs)
{
for(int i=0 ; i<inputs.length ; i++){
for(int j=0 ; j < inputs[0].length ; j++)
{
System.out.println(Arrays.deepToString(grid));
}
}
}
}
I have 2 separate files userInputs and showInput but they it says that they should still be declared in a separate file?
It's wrong to write main Function in every class, the program uses the main function to start from it, So you should write it only in the main project class and call inside it the other classes.
Your code should be:
package com.company;
public class ChessBoard
{
public static void main(String[] args)
{
userInputs input = new userInputs();
showInput show = new showInput();
String grid[][] = input.takeInput();
show.show(grid);
}
}
and other classes in separate files like:
package com.company;
import java.util.Scanner;
public class userInputs
{
public String[][] takeInput()
{
char rows = 'a';
String spot;
Scanner scanner = new Scanner(System.in);
String[][] grid = new String [8][8];
for(int i = 0; i < grid.length; i++, rows++) {
for (int col = 0; col < grid[i].length; col++) ;
String input = null; // will be changed to a valid position
boolean validCoordinate = false; // will be true if position is valid
while (!validCoordinate) {
System.out.println("Enter a coordinate (for example, a5): ");
input = scanner.next();
validCoordinate = input.matches("[a-h][1-8]");
}
;
// now we now that the input is valid
int row = input.charAt(0) - 'a';
int col = input.charAt(1) - '1';
String temp = input + " - ";
System.out.println("Insert your piece:");
input = scanner.next();
grid[row][col] = temp + input;
}
return grid;
}
}
and another class to output:
package com.company;
public class showInput {
public void show(String [][] inputs)
{
for(int i=0 ; i<inputs.length ; i++){
for(int j=0 ; j < inputs[0].length ; j++)
{
//Print Your Data
}
}
}
}
Like #Atef Magdy said, You should have one class which holds all the data and functions
and a main class which executes the functions.
and the explanation for this error ( it states that using public int is an "illegal start" to the expression, and that it needs a ";" after it?) I have seen that you made the 2d Array of Type String?
String[] [] grid = new String [8][8];
and then returning it as a 1D Array of Type int?
public int[] getGrid(){
return grid.clone();
}
I should say that this is the source of this error. You should change the 'int[]' to 'string[][]'
if there is any error please reply to this answer!
First, for quick context, here's my post from yesterday:
How to work around a NullPointerException in Java?
So I'm getting this NullPointerException, which I now believe is occurring before I try to find the index of the first duplicate in the array of strings. Before I search for the index of the first duplicate, I double the size of the string array using this method:
static String[] upSizeArr( String[] fullArr )
{
int size = fullArr.length;
String[] newSizeArr = new String[(2 * size)];
for (int a = 0; a < size; a++) {
newSizeArr[a] = fullArr[a];
}
return newSizeArr;
}
and I then use that method in the context of this while loop:
static final int CAPACITY = 10;
int wordCount = 0;
BufferedReader wordFile = new BufferedReader( new FileReader(args[1]) );
String[] wordList = new String[CAPACITY];
while ( wordFile.ready() )
{ if ( wordCount == wordList.length )
wordList = upSizeArr( wordList );
wordList[wordCount++] = wordFile.readLine();
}
wordFile.close();
Is there any possible work around for this using the upSizeArr method? I would prefer the solution be basic and using only arrays with no other data structures. I am new to programming and am really trying to get a grasp of the fundamentals...been looking for a solution to this NullPointException for about a week or so now.
Here is the code in it's entirety:
import java.io.*;
import java.util.*;
public class Practice
{
static final int CAPACITY = 10;
static final int NOT_FOUND = -1;
public static void main (String[] args) throws Exception
{
if (args.length < 1 )
{
System.out.println("\nusage: C:\\> java Practice <words filename>\n\n"); // i.e. C:\> java Lab2 10Kints.txt 172822words.txt
System.exit(0);
}
String[] wordList = new String[CAPACITY];
int wordCount = 0;
BufferedReader wordFile = new BufferedReader( new FileReader(args[0]) );
while ( wordFile.ready() ) // i.e. while there is another line (word) in the file
{ if ( wordCount == wordList.length )
wordList = upSizeArr( wordList );
wordList[wordCount++] = wordFile.readLine();
} //END WHILE wordFile
wordFile.close();
System.out.format( "%s loaded into word array. size=%d, count=%d\n",args[0],wordList.length,wordCount );
int dupeIndex = indexOfFirstDupe( wordList, wordCount );
if ( dupeIndex == NOT_FOUND )
System.out.format("No duplicate values found in wordList\n");
else
System.out.format("First duplicate value in wordList found at index %d\n",dupeIndex);
} // END OF MAIN
// TWO METHODS
static String[] upSizeArr( String[] fullArr )
{
int size = fullArr.length; //find the length of the arrays
String[] newSizeArr = new String[(2 * size)]; // creates new array, doubled in size
for (int a = 0; a < size; a++) {
newSizeArr[a] = fullArr[a];
}
return newSizeArr;
}
static int indexOfFirstDupe( String[] arr, int count )
{
Arrays.sort(arr);
int size = arr.length;
int index = NOT_FOUND;
for (int x = 0; x < size; x++) {
for (int y = x + 1; y < size; y++) {
if (arr[x].equals(arr[y])) {
index = x;
break;
}
}
}
return index;
}
} // END OF PROGRAM
Also, the file that's being used as the argument is a txt file of strings.
I'm not sure if it's the cause of your problem, but it is very suspicious...
while ( wordFile.ready() ) {
//...
}
is not how you should be reading the file. Instead, you should be checking the return result of readLine, which will return null when it reaches the end of the file.
Maybe something more like....
try (BufferedReader wordFile = new BufferedReader(new FileReader(args[1]))) {
String[] wordList = new String[CAPACITY];
String text = null;
while ((text = wordFile.readLine()) != null) {
if (wordCount == wordList.length) {
wordList = upSizeArr(wordList);
}
wordList[wordCount++] = text;
}
} catch (IOException ex) {
ex.printStackTrace();
}
Your code also runs the risk of leaving the file resource open. The above example makes use of the try-with-resources statement to ensure that it is closed properly, regardless of the success of the operation.
Take a look at The try-with-resources Statement for more details.
Unless it's a specific requirement, I would also recommend using an ArrayList or System.arraycopy over rolling your own solution like this.
Maybe have a look at List Implementations for some more details
Update from runnable example...
After having a play without a runnable example of the code, when upSizeArr creates a new array, it's defaulting the new elements to null, which is expected, I'm surprised that Arrays.sort can't handle this.
"A" solution is to fill the unused space with a different non-default value...
static String[] upSizeArr(String[] fullArr) {
int size = fullArr.length; //find the length of the arrays
String[] newSizeArr = new String[(2 * size)]; // creates new array, doubled in size
for (int a = 0; a < size; a++) {
newSizeArr[a] = fullArr[a];
}
for (int a = size; a < newSizeArr.length; a++) {
newSizeArr[a] = "";
}
return newSizeArr;
}
"Another" solution might be to "downsize" the array to fit the available data...
static String[] downsizeToCapacity(String[] fullArr) {
int lastIndex = 0;
while (lastIndex < fullArr.length && fullArr[lastIndex] != null) {
lastIndex++;
}
if (lastIndex >= fullArr.length) {
return fullArr;
}
String[] downSized = new String[lastIndex];
System.arraycopy(fullArr, 0, downSized, 0, lastIndex);
return downSized;
}
All this tries to do is create a new array whose size is only large enough to contain all the none-null values and return that.
You could then use to something like...
System.out.format("%s loaded into word array. size=%d, count=%d\n", "words.txt", wordList.length, wordCount);
wordList = downsizeToCapacity(wordList);
System.out.format("%s loaded into word array. size=%d, count=%d\n", "words.txt", wordList.length, wordCount);
int dupeIndex = indexOfFirstDupe(wordList, wordCount);
Which, in my testing, outputs
words.txt loaded into word array. size=160, count=99
words.txt loaded into word array. size=99, count=99
No duplicate values found in wordList
Essentially, this code takes a file (which is a few paragraphs of text) and counts the amount of times each letter appears and prints it onto the console. While I've finished all the code in terms of calculation, I'm running into an exception. When I run this, it shows:
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at LetterCount.countOccurrences(LetterCount.java:29)
at LetterCount.main(LetterCount.java:20)
Here is my code:
// Document your class here
import java.util.Scanner;
import java.io.File;
import java.io.FileInputStream;
public class LetterCount {
public final static String FILENAME = "testFile.txt";
// Driver to test LetterInventory class
public static void main(String[] args) {
Scanner inputFile = null;
try {
inputFile = new Scanner(new File(FILENAME));
} catch (Exception e) {
System.out.println("File could not be opened: " + FILENAME);
System.exit(0);
}
int[] counts = countOccurrences(inputFile);
displayTable(counts);
resetTable(counts);
}
public static int[] countOccurrences (Scanner inputFile) {
int[]counts = new int[26];
char[] characters = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
while (inputFile.hasNextLine()) {
String theWord = inputFile.next();
theWord = theWord.toLowerCase();
for (int j = 0; j < theWord.length(); j++) {
for (int counter = 0; counter < 26; counter++) {
if (theWord.charAt(j) == characters[counter]) {
counts[counter] += 1;
}
}
}
}
return counts;
}
public static void displayTable (int[] counts) {
for (int index = 0; index < 26; index++) {
System.out.println((char)('a' + index) + ":\t" + counts[index]);
}
}
public static void resetTable (int[] counts) {
System.out.println();
for (int index = 0; index < 26; index++) {
System.out.println((char)('a' + index) + ":\t0");
}
}
}
When I clicked on the highlighted parts of NoSuchElementException, I saw that it was referring to the String I created. What am I doing wrong, and what can I do to fix it?
The method you use to read the data should be of the same type as the one you use to check if there is more data.
In your while statement, you use inputFile.hasNextLine(), so on the line after it, you should use inputFile.nextLine() (rather than inputFile.next() as you do now).
Alternatively, you can change the while statement to use inputFile.hasNext().
No guarantees, but try using inputFile.hasNext() in your while instead of inputFile.hasNextLine(). A next line being available is not necessarily the same thing as a next word being available.
You don't need the characters array (you can use the same math you have in display to perform the addition of counts). Also, you should be consistent with how you call Scanner.hasNextLine() and Scanner.next() (check for next with hasNext()). Something like,
public static int[] countOccurrences(Scanner inputFile) {
int[] counts = new int[26];
while (inputFile.hasNext()) {
String theWord = inputFile.next().toLowerCase();
for (char ch : theWord.toCharArray()) {
if (Character.isLetter(ch)) {
counts[ch - 'a']++;
}
}
}
return counts;
}
When I run the program, it prints out "After trim, wordList length: 0". Not sure why?
import java.io.*;
import java.util.*;
public class Project5 {
static final int INITIAL_CAPACITY = 10;
public static void main(String[] args) throws Exception {
if (args.length < 1)
die("You must type the dictionary filename on cmd line.\n");
// Here we have declared an int array, called 'histogram' with initial
// capacity of 0
// it is a freq counter to word lengths in the file
int[] histogram = new int[0];
// Here we have declared an array of String to read the dictionary file
// into. We use BufferedReader (not Scanner).
// With each word read in, examine it's length and update word length
// frequency histogram accordingly
String[] wordList = new String[INITIAL_CAPACITY];
int wordCount = 0;
BufferedReader infile = new BufferedReader(new FileReader(args[0]));
while (infile.ready()) // i.e. while there are more lines of text in the
// file
{
String word = infile.readLine();
// YOUR CODE HERE TO CHECK TO SEE IF WORDLIST IS FULL
// IF SO YOU MUST DO AN UPSIZE JUST LIKE LAB#6
if (word.length() >= histogram.length)
histogram = upSizeHisto(histogram, word.length() + 1);
// YOUR CODE HERE to add this word to your list
histogram[word.length()]++;
// YOUR CODE HERE TO LOOK AT THE LENGTH OF THE WORD AND UPDATE
// HISTOGRAM
// example if word.length() is 5 then histogram[5] gets increment
// BUT IF WORD LENGTH IS >= HISTORGRAM LENGTH
// THEN YOU NEED TO FIRST CALL upSizeHisto TO UPSIZE THE HISTOGRAM
// TO BE OF EXACTLY LENGTH word.length()+1
// SIMILAR TO HOW YOU HAD TO UPSIZE WORDLIST
} // END WHILE INFILE READY
infile.close();
wordList = trimArr(wordList, wordCount);
System.out.println("After trim, wordList length: " + wordList.length);
// PRINT WORD LENGTH FREQ HISTOGRAM
for (int i = 0; i < histogram.length; i++)
System.out.println("words of length " + i + ": " + histogram[i]);
} // END main
private static void die(String msg) {
System.out.println(msg);
System.exit(0);
}
private static String[] upSizeArr(String[] oldArr) {
int i = 0;
String[] newArr = new String[oldArr.length * 2];
for (i = 0; i < oldArr.length; i++) {
newArr[i] = oldArr[i];
}
return newArr; // replace with code from Lab6
}
private static String[] trimArr(String[] oldArr, int count) {
int i = 0;
String[] trimArr = new String[count];
for (i = 0; i < trimArr.length; i++) {
trimArr[i] = oldArr[i];
}
return trimArr; // replace with code from Lab6
}
private static int[] upSizeHisto(int[] oldArr, int newLength) {
int i = 0;
int upSizeHisto[] = new int[newLength];
for (i = 0; i < oldArr.length; i++) {
upSizeHisto[i] = oldArr[i];
}
return upSizeHisto; // change all this to upsize the int[] array
}
} // END CLASS PROJECT#5
Your code is working perfectly, the only problem is that you never increment wordCount or add your word to wordList. Just add this somewhere inside your while loop and you're good to go:
if (wordCount >= wordList.length) wordList = upSizeArr(wordList);
wordList[wordCount] = word;
wordCount++;
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
}