I'm writing a program that will print the unique character in a string (entered through a scanner). I've created a method that tries to accomplish this but I keep getting characters that are not repeats, instead of a character (or characters) that is unique to the string. I want the unique letters only.
Here's my code:
import java.util.Scanner;
public class Sameness{
public static void main (String[]args){
Scanner kb = new Scanner (System.in);
String word = "";
System.out.println("Enter a word: ");
word = kb.nextLine();
uniqueCharacters(word);
}
public static void uniqueCharacters(String test){
String temp = "";
for (int i = 0; i < test.length(); i++){
if (temp.indexOf(test.charAt(i)) == - 1){
temp = temp + test.charAt(i);
}
}
System.out.println(temp + " ");
}
}
And here's sample output with the above code:
Enter a word:
nreena
nrea
The expected output would be: ra
Based on your desired output, you have to replace a character that initially has been already added when it has a duplicated later, so:
public static void uniqueCharacters(String test){
String temp = "";
for (int i = 0; i < test.length(); i++){
char current = test.charAt(i);
if (temp.indexOf(current) < 0){
temp = temp + current;
} else {
temp = temp.replace(String.valueOf(current), "");
}
}
System.out.println(temp + " ");
}
How about applying the KISS principle:
public static void uniqueCharacters(String test) {
System.out.println(test.chars().distinct().mapToObj(c -> String.valueOf((char)c)).collect(Collectors.joining()));
}
The accepted answer will not pass all the test case for example
input -"aaabcdd"
desired output-"bc"
but the accepted answer will give -abc
because the character a present odd number of times.
Here I have used ConcurrentHasMap to store character and the number of occurrences of character then removed the character if the occurrences is more than one time.
import java.util.concurrent.ConcurrentHashMap;
public class RemoveConductive {
public static void main(String[] args) {
String s="aabcddkkbghff";
String[] cvrtar=s.trim().split("");
ConcurrentHashMap<String,Integer> hm=new ConcurrentHashMap<>();
for(int i=0;i<cvrtar.length;i++){
if(!hm.containsKey(cvrtar[i])){
hm.put(cvrtar[i],1);
}
else{
hm.put(cvrtar[i],hm.get(cvrtar[i])+1);
}
}
for(String ele:hm.keySet()){
if(hm.get(ele)>1){
hm.remove(ele);
}
}
for(String key:hm.keySet()){
System.out.print(key);
}
}
}
Though to approach a solution I would suggest you to try and use a better data structure and not just string. Yet, you can simply modify your logic to delete already existing duplicates using an else as follows :
public static void uniqueCharacters(String test) {
String temp = "";
for (int i = 0; i < test.length(); i++) {
char ch = test.charAt(i);
if (temp.indexOf(ch) == -1) {
temp = temp + ch;
} else {
temp.replace(String.valueOf(ch),""); // added this to your existing code
}
}
System.out.println(temp + " ");
}
This is an interview question. Find Out all the unique characters of a string.
Here is the complete solution. The code itself is self explanatory.
public class Test12 {
public static void main(String[] args) {
String a = "ProtijayiGiniGina";
allunique(a);
}
private static void allunique(String a) {
int[] count = new int[256];// taking count of characters
for (int i = 0; i < a.length(); i++) {
char ch = a.charAt(i);
count[ch]++;
}
for (int i = 0; i < a.length(); i++) {
char chh = a.charAt(i);
// character which has arrived only one time in the string will be printed out
if (count[chh] == 1) {
System.out.println("index => " + i + " and unique character => " + a.charAt(i));
}
}
}// unique
}
In Python :
def firstUniqChar(a):
count = [0] *256
for i in a: count[ord(i)] += 1
element = ""
for item in a:
if (count[ord(item)] == 1):
element = item;
break;
return element
a = "GiniGinaProtijayi";
print(firstUniqChar(a)) # output is P
public static String input = "10 5 5 10 6 6 2 3 1 3 4 5 3";
public static void uniqueValue (String numbers) {
String [] str = input.split(" ");
Set <String> unique = new HashSet <String> (Arrays.asList(str));
System.out.println(unique);
for (String value:unique) {
int count = 0;
for ( int i= 0; i<str.length; i++) {
if (value.equals(str[i])) {
count++;
}
}
System.out.println(value+"\t"+count);
}
}
public static void main(String [] args) {
uniqueValue(input);
}
Step1: To find the unique characters in a string, I have first taken the string from user.
Step2: Converted the input string to charArray using built in function in java.
Step3: Considered two HashSet (set1 for storing all characters even if it is getting repeated, set2 for storing only unique characters.
Step4 : Run for loop over the array and check that if particular character is not there in set1 then add it to both set1 and set2. if that particular character is already there in set1 then add it to set1 again but remove it from set2.( This else part is useful when particular character is getting repeated odd number of times).
Step5 : Now set2 will have only unique characters. Hence, just print that set2.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String str = input.next();
char arr[] = str.toCharArray();
HashSet<Character> set1=new HashSet<Character>();
HashSet<Character> set2=new HashSet<Character>();
for(char i:arr)
{
if(set1.contains(i))
{
set1.add(i);
set2.remove(i);
}
else
{
set1.add(i);
set2.add(i);
}
}
System.out.println(set2);
}
I would store all the characters of the string in an array that you will loop through to check if the current characters appears there more than once. If it doesn't, then add it to temp.
public static void uniqueCharacters(String test) {
String temp = "";
char[] array = test.toCharArray();
int count; //keep track of how many times the character exists in the string
outerloop: for (int i = 0; i < test.length(); i++) {
count = 0; //reset the count for every new letter
for(int j = 0; j < array.length; j++) {
if(test.charAt(i) == array[j])
count++;
if(count == 2){
count = 0;
continue outerloop; //move on to the next letter in the string; this will skip the next two lines below
}
}
temp += test.charAt(i);
System.out.println("Adding.");
}
System.out.println(temp);
}
I have added comments for some more detail.
import java.util.*;
import java.lang.*;
class Demo
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter String");
String s1=sc.nextLine();
try{
HashSet<Object> h=new HashSet<Object>();
for(int i=0;i<s1.length();i++)
{
h.add(s1.charAt(i));
}
Iterator<Object> itr=h.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
catch(Exception e)
{
System.out.println("error");
}
}
}
If you don't want to use additional space:
String abc="developer";
System.out.println("The unique characters are-");
for(int i=0;i<abc.length();i++)
{
for(int j=i+1;j<abc.length();j++)
{
if(abc.charAt(i)==abc.charAt(j))
abc=abc.replace(String.valueOf(abc.charAt(j))," ");
}
}
System.out.println(abc);
Time complexity O(n^2) and no space.
This String algorithm is used to print unique characters in a string.It runs in O(n) runtime where n is the length of the string.It supports ASCII characters only.
static String printUniqChar(String s) {
StringBuilder buildUniq = new StringBuilder();
boolean[] uniqCheck = new boolean[128];
for (int i = 0; i < s.length(); i++) {
if (!uniqCheck[s.charAt(i)]) {
uniqCheck[s.charAt(i)] = true;
if (uniqCheck[s.charAt(i)])
buildUniq.append(s.charAt(i));
}
}
public class UniqueCharactersInString {
public static void main(String []args){
String input = "aabbcc";
String output = uniqueString(input);
System.out.println(output);
}
public static String uniqueString(String s){
HashSet<Character> uniques = new HashSet<>();
uniques.add(s.charAt(0));
String out = "";
out += s.charAt(0);
for(int i =1; i < s.length(); i++){
if(!uniques.contains(s.charAt(i))){
uniques.add(s.charAt(i));
out += s.charAt(i);
}
}
return out;
}
}
What would be the inneficiencies of this answer? How does it compare to other answers?
Based on your desired output you can replace each character already present with a blank character.
public static void uniqueCharacters(String test){
String temp = "";
for(int i = 0; i < test.length(); i++){
if (temp.indexOf(test.charAt(i)) == - 1){
temp = temp + test.charAt(i);
} else {
temp.replace(String.valueOf(temp.charAt(i)), "");
}
}
System.out.println(temp + " ");
}
public void uniq(String inputString) {
String result = "";
int inputStringLen = inputStr.length();
int[] repeatedCharacters = new int[inputStringLen];
char inputTmpChar;
char tmpChar;
for (int i = 0; i < inputStringLen; i++) {
inputTmpChar = inputStr.charAt(i);
for (int j = 0; j < inputStringLen; j++) {
tmpChar = inputStr.charAt(j);
if (inputTmpChar == tmpChar)
repeatedCharacters[i]++;
}
}
for (int k = 0; k < inputStringLen; k++) {
inputTmpChar = inputStr.charAt(k);
if (repeatedCharacters[k] == 1)
result = result + inputTmpChar + " ";
}
System.out.println ("Unique characters: " + result);
}
In first for loop I count the number of times the character repeats in the string. In the second line I am looking for characters repetitive once.
how about this :)
for (int i=0; i< input.length();i++)
if(input.indexOf(input.charAt(i)) == input.lastIndexOf(input.charAt(i)))
System.out.println(input.charAt(i) + " is unique");
package extra;
public class TempClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
String abcString="hsfj'pwue2hsu38bf74sa';fwe'rwe34hrfafnosdfoasq7433qweid";
char[] myCharArray=abcString.toCharArray();
TempClass mClass=new TempClass();
mClass.countUnique(myCharArray);
mClass.countEach(myCharArray);
}
/**
* This is the program to find unique characters in array.
* #add This is nice.
* */
public void countUnique(char[] myCharArray) {
int arrayLength=myCharArray.length;
System.out.println("Array Length is: "+arrayLength);
char[] uniqueValues=new char[myCharArray.length];
int uniqueValueIndex=0;
int count=0;
for(int i=0;i<arrayLength;i++) {
for(int j=0;j<arrayLength;j++) {
if (myCharArray[i]==myCharArray[j] && i!=j) {
count=count+1;
}
}
if (count==0) {
uniqueValues[uniqueValueIndex]=myCharArray[i];
uniqueValueIndex=uniqueValueIndex+1;
count=0;
}
count=0;
}
for(char a:uniqueValues) {
System.out.println(a);
}
}
/**
* This is the program to find count each characters in array.
* #add This is nice.
* */
public void countEach(char[] myCharArray) {
}
}
Here str will be your string to find the unique characters.
function getUniqueChars(str){
let uniqueChars = '';
for(let i = 0; i< str.length; i++){
for(let j= 0; j< str.length; j++) {
if(str.indexOf(str[i]) === str.lastIndexOf(str[j])) {
uniqueChars += str[i];
}
}
}
return uniqueChars;
}
public static void main(String[] args) {
String s = "aaabcdd";
char a[] = s.toCharArray();
List duplicates = new ArrayList();
List uniqueElements = new ArrayList();
for (int i = 0; i < a.length; i++) {
uniqueElements.add(a[i]);
for (int j = i + 1; j < a.length; j++) {
if (a[i] == a[j]) {
duplicates.add(a[i]);
break;
}
}
}
uniqueElements.removeAll(duplicates);
System.out.println(uniqueElements);
System.out.println("First Unique : "+uniqueElements.get(0));
}
Output :
[b, c]
First Unique : b
import java.util.*;
public class Sameness{
public static void main (String[]args){
Scanner kb = new Scanner (System.in);
String word = "";
System.out.println("Enter a word: ");
word = kb.nextLine();
uniqueCharacters(word);
}
public static void uniqueCharacters(String test){
for(int i=0;i<test.length();i++){
if(test.lastIndexOf(test.charAt(i))!=i)
test=test.replaceAll(String.valueOf(test.charAt(i)),"");
}
System.out.println(test);
}
}
public class Program02
{
public static void main(String[] args)
{
String inputString = "abhilasha";
for (int i = 0; i < inputString.length(); i++)
{
for (int j = i + 1; j < inputString.length(); j++)
{
if(inputString.toCharArray()[i] == inputString.toCharArray()[j])
{
inputString = inputString.replace(String.valueOf(inputString.charAt(j)), "");
}
}
}
System.out.println(inputString);
}
}
I am trying to create a dictionary out of a .txt file.The problem I think is in my addToDict method. I am trying to resize th array when its full because I am reading from a text file of unknown size but I can only use arrays. I get an out of bounds exception when I am printing the array. I have no idea whats wrong and I have been working on the project for days now. I am also having trouble with my else statement in my addToDict method. It is also and out of bounds exception
import java.io.*;
import java.util.Scanner;
import java.util.regex.*;
public class BuildDict {
static String dict[] = new String[20];
static int index = 0;
public static void main(String args[]) {
readIn();
}
public static void readIn() {
File inFile = new File("alice.txt");
try {
Scanner scan = new Scanner(inFile);
while (scan.hasNext()) {
String word = scan.next();
if (!Character.isUpperCase(word.charAt(0))) {
checkRegex(word);
}
}
scan.close();
} catch (IOException e) {
System.out.println("Error");
}
}
public static void addToDict(String word) {
if (index == dict.length) {
String newAr[] = new String[index * 2];
for (int i = 0; i < index; i++) {
newAr[i] = dict[i];
}
newAr[index] = word;
index++;
dict = newAr;
for (int j = 0; j < index; j++) {
System.out.println(newAr[j]);
}
} else {
dict[index] = word;
index++;
}
}
public static void checkRegex(String word) {
String regex = ("[^A-Za-z]");
Pattern check = Pattern.compile(regex);
Matcher regexMatcher = check.matcher(word);
if (!regexMatcher.find()) {
addToDict(word);
}
}
}
You haven't assigned the new array to dict.
if (index == dict.length) {
for (int i = 0; i < index; i++) {
newAr[i] = dict[i];
}
newAr[index] = word;
index++;
for (int j = 0; j < index; j++) {
System.out.println(newAr[j]);
}
// Assign dict to the new array.
dict = newAr;
} else {
dict[index] = word;
index++;
}
The value of index is 0 when the following statement is executed.
String newAr[] = new String[index*2];
Try revisiting your logic. index should be given a positive value before this method is called. That's why you are getting OutOfBounds.
EDIT: Did you mean to write index+2?
You have
static int index = 0;
You need to change the value of this variable, based on your file, otherwise you will always have an error in this line
String newAr[] = new String[index*2];
Instead of using a array use a arraylist for when you don't know the size of your array. It will save you a lot of trouble. I find they are much easier to work with in general then normal arrays.
ArrayList<String> dict = new ArrayList<>();
dict.add(word);
//displaying values
for( int i = 0; i < dict.size(); i++ ){
System.out.println(dict.get(i));
}
I've made a 12 by 12 table that runs in the same program, but i'd like to make it OO so that i can put the "public static void main" in another "testfile" and it will still run properly..i'm having some problems with the OO approach and i really need help...This is what my code looks like:
import java.util.Scanner;
import java.util.Arrays;
import java.util.Random;
public class PlayingArea {
public static void main(String[] args) {
Random r = new Random();
Scanner input = new Scanner(System.in);
System.out.println("How many regions would you like (2- 4)");
int region = input.nextInt();
String letters = "";
while(letters.length() < 2) {
if (region == 4) {
letters= "EFGH";
}
if (region == 3) {
letters= "EFG";
} else if (region == 2) {
letters= "EF";
} else if (region < 2) {
System.out.println("You inputed a wrong value, try again...");
}
}
int N = letters.length();
char [][] letter = new char[12][12];
for (int j = 0; j < letter.length; j++) {
for(int i=0; i < letter.length; i++) {
letter[i][j] = letters.charAt(r.nextInt(N)) ;
}
}
for (char[] letterRow : letter)
System.out.println(Arrays.toString(letterRow));
}
}
if you're relatively new to java then you're doing quite well. Be aware there is an infinite loop in your program (fixed below) if you enter a number outside of 2-4.
Firstly, your class PlayingArea needs some member variables to represent state.
The first one is the String letters (EF or EFG or EFGH), which is initialized via a constructor in the code below.
The second one is the char[][] grid (renamed from letter in your code) which is assigned a value in the populate() method, which puts letters into the grid.
The other method, gridAsString() does just that.
The public static void main can easily now be moved to another class, if you like.
Have fun.
public class PlayingArea {
private String letters;
private char[][] grid;
public PlayingArea(String letters) {
this.letters = letters;
}
public void populate() {
int n = letters.length();
grid = new char[12][12];
Random r = new Random();
for (int j = 0; j < grid.length; j++) {
for (int i = 0; i < grid.length; i++) {
grid[i][j] = letters.charAt(r.nextInt(n));
}
}
}
public String gridAsString() {
StringBuilder sb = new StringBuilder();
for (char[] letterRow : grid) {
sb.append(Arrays.toString(letterRow)).append('\n');
}
return sb.toString();
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many regions would you like (2- 4)");
String letters = "";
while (letters.length() < 2) {
int region = input.nextInt();
if (region == 4) {
letters = "EFGH";
} else if (region == 3) {
letters = "EFG";
} else if (region == 2) {
letters = "EF";
} else {
System.out.println("You inputed a wrong value, try again...");
}
}
PlayingArea playingArea = new PlayingArea(letters);
playingArea.populate();
System.out.println(playingArea.gridAsString());
}
}
I have this program but i have a few problems:
This is the place where i do the calcs.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class MorseCode {
public MorseCode()
{
}//end default constructor
public String[] translateHere(String s)throws IOException
{
String compare = s, codedLine = ""; //userInput toUpperCase
int length = compare.length(); //length of userInput
String line, file = "C:\\APCS Course B\\Unit 4\\Unit 4 Documents\\morse.txt";// variable holding file name and variable for each letter/number
char code;
//Constants
final int MAX = 36;
//Arrays
char[] morseLetter = new char[MAX];
String[] morseCode = new String[MAX];
String[] newMessage = new String[length];
//putting user input in a character array;
char[] userLetters = compare.toCharArray();
//object creation
File openFile = new File(file);
Scanner inFile = new Scanner(openFile);
int counter = 0;
while(inFile.hasNext())
{
line = inFile.next();
code = (char)line.charAt(0);
//System.out.println(code);
morseLetter[counter] = code;
morseCode[counter] = inFile.next();
counter++;
}//end nested while loop
for(int j = 0; j < length; j++)
{
for(int k = 0; k < MAX; k++)
{
if(userLetters[j] == morseLetter[k])
{
newMessage[j] = morseCode[k];
}
}//end nested for loop
}//end for loop
return newMessage;
}//end method that completes translateion
public String toString(String a, String[] b)
{
System.out.println("Input: " + a);
System.out.println("Output:");
String output = "";
for(int i = 0; i < b.length; i++)
{
output = output + b[i];
}
return output;
}//end toString method
}//end Translate Class
The main methods:
import javax.swing.JOptionPane;
import java.io.*;
import java.util.Scanner;
public class MorseCodeTester
{
public static void main(String[] args)throws IOException
{
String userInput;
final String SENTINEL = "0";//for exiting program when entered
//object creation
MorseCode text = new MorseCode();
//getting user input to be translated
do
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter what you wish to translte to Morse code (no punctuation): ");
userInput = in.nextLine();
String compare = userInput.toUpperCase();
String[] codedText = new String[compare.length()];
codedText = text.translateHere(compare);
text.toString(userInput, codedText);
}while(!userInput.equals(SENTINEL));
}//end main
}//end class
So my program is when I put in a input the output shows black even tho in the main methods i did the calculation that would convert it to Morse Code. Also is there any suggestions on if i could use the static identifier in any of my methods.
Here is the text file:
1 .----
2 ..---
3 ...--
4 ....-
5 .....
6 -....
7 --...
8 ---..
9 ----.
0 -----
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 --..
Your code should use a hashmap to key the morse code by letter, this makes your code much simpler.
Getting the morsecode for a letter is then a simple lookup.
Also you could just load the data once, maybe in the Constructor of MorseCode.
But to get at your question, you are just not printing the output. Just returning it and not showing it on the console.
if you change your toString method to look like this, it should print out something.
public String toString(String a, String[] b) {
System.out.println("Input: " + a);
System.out.print("Output:"); // changed to a print, to avoid newline
String output = "";
for (int i = 0; i < b.length; i++) {
output = output + b[i];
}
System.out.println(output); // this was missing
return output;
}//end toString method
So I have a method that reads a file and assigns classes to elements of an array. How do I assign a special character for each class that I am giving to my array?
The array is of the class "Element" that has 3 attributes (int, int, char)
and those classes (Fantasma, which is a subclass of "Element").
public void ReadFile() throws FileNotFoundException
{
Scanner scan = new Scanner(new File("inicio.txt"));
while (scan.hasNext())
{
String line = scan.next();
if (line.equals("Pared"))
{
int i = scan.nextInt();
int j = scan.nextInt();
_mundo = new Pared[i][j];
}
else if (line.equals("Fantasma"))
{
int i = scan.nextInt();
int j = scan.nextInt();
_mundo = new Fantasma[i][j];
}
}
}
It's not good style to update global variables like your _mundo. You should have your method return an array.
I'm not sure why you would want to duplicate the i / j information as locations in your array and as arguments to your element constructor. It would make more sense to do something like this:
// untested!
abstract class Element {
private char character;
public char getChar() {
return character;
}
Element(char c) {
character = c;
}
}
class Fantasma extends Element {
Fantasma() {
super('F');
}
}
class Pared extends Element {
Pared() {
super('P');
}
}
class Vacio extends Element {
Vacio() {
super(' ');
}
}
public Element[][] readFile() throws FileNotFoundException {
Scanner scan = new Scanner(new File("inicio.txt"));
Element[][] res = new Element[10][10]; // insert your dimensions here
while (scan.hasNext()) {
String line = scan.next();
if (line.equals("Pared") || line.equals("Fantasma")) {
int i = scan.nextInt();
int j = scan.nextInt();
if(line.equals("Pared"))
res[i][j] = new Pared();
else
res[i][j] = new Fantasma();
}
}
// add spaces so we're not left with any null references
for (int i = 0; i < res.length; i++)
for (int j = 0; j < res[i].length; j++)
if (res[i][j] == null)
res[i][j] = new Vacio();
return res;
}
Then you can for example print it out with
Element[][] grid = readFile();
for (Element[] ea : grid) {
for (Element e : ea)
System.out.print(e.getChar());
System.out.println();
}