i'am new injava , in this problem i will insert a numbers of strings in a array , but the compiler give me this probleme :
PhoneNumber.java:29: error: incompatible types: String cannot be converted to boolean
while(test[i][j])
^
1 error
public class PhoneNumber{
public static void check_number(String[][] numbers, int n)
{
int i,j;
for(i = 0; i < n; i++)
{
for(j = 0; j < numbers[i].length; j++)
{
if(numbers[i][j] == "4" || numbers[i][j] == "5")
{
System.out.println("Done");
}
}
}
}
public static void main(String[] args)
{
String[][] test = new String[100][100];
Scanner number = new Scanner(System.in);
int n,i,j;
System.out.println("enter the number of numbers");
n = number.nextInt();
for(i = 0 ; i < n; i++)
{
System.out.println("enter the number " + i + 1);
j = 0;
while(test[i][j])
{
test[i][j] = number.nextLine();
j++;
}
}
check_number(test,n);
}
}
Here's the basic approach for a 1D String array with notes included:
import java.util.Scanner;
public class PhoneNumber{
public static void check_number(String[] numbers, int n)
{
for(int i = 0; i < n; i++)
{
System.out.println(numbers[i]);
//the String class method equals is best for comparison:
if(numbers[i].equals("4") || numbers[i].equals("5"))
{
System.out.println("Done");
}
}
}
public static void main(String[] args)
{
Scanner number = new Scanner(System.in);
int n;
System.out.println("enter the number of numbers");
n = number.nextInt();
//clean the scanner buffer after input especially with Int -> Line
number.nextLine();
//size your array after getting user input
String[] test = new String[n];
for(int i = 0 ; i < n; i++)
{
//parenthesis needed to get correct output for i + 1
System.out.println("enter the number " + (i + 1));
test[i] = number.nextLine();
}
check_number(test,n);
}
}
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 built a tic tac toe game using java but I just have one issue. I want my code to bounce back and forth from the validPlayerOneInput and validPlayerTwoInput methods. As you can see in my main, I'm calling both methods procedurally which be incorrect as it just stops after the method is called. I want this to keep running until a winner is determined.
How do I do so?
import java.util.*;
public class tictactoe {
private static char board[][] = {{1,2,3}, {4,5,6}, {7,8,9}};
char p1Sym, p2Sym;
public tictactoe() {
p1Sym ='X';
p2Sym = 'O';
boardFill();
}
void boardFill() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(board[i][j]);
System.out.print(" | ");
}
System.out.println();
}
}
void validInputPlayerOne() {
boolean isSet = true;
int player1Input, player1CorrectedInput;
System.out.println("Player 1, enter a number between 1-9: ");
Scanner player1 = new Scanner(System.in);
player1Input = player1.nextInt();
Scanner correctedInput = new Scanner(System.in);
while(player1Input < 1 || player1Input >= 10) {
System.out.println("This isn't a number between 1-9, try again: ");
player1CorrectedInput = correctedInput.nextInt();
player1Input = player1CorrectedInput;
}
// or
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == player1Input) {
// set new value
board[i][j] = p1Sym;
// set
isSet = true;
}
}
}
if (!isSet) {
System.out.println("not found");
}
}
void validInputPlayerTwo() {
boolean isSet = true;
int player2Input, player2CorrectedInput;
System.out.println("Player 2, enter a number between 1-9: ");
Scanner player2 = new Scanner(System.in);
player2Input = player2.nextInt();
Scanner correctedInput = new Scanner(System.in);
while(player2Input < 1 || player2Input >= 10) {
System.out.println("This isn't a number between 1-9, try again: ");
player2CorrectedInput = correctedInput.nextInt();
player2Input = player2CorrectedInput;
}
// or
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == player2Input){
board[i][j] = p2Sym;
isSet = true;
}
}
}
if (!isSet) {
System.out.println("not found");
}
}
public static void main(String[] args) {
tictactoe t = new tictactoe();
t.validInputPlayerOne();
t.boardFill();
t.validInputPlayerTwo();
t.boardFill();
}
}
You could do something like:
int turn = 0;
while (t.noWinner()) {
if (turn % 2 == 0) t.validInputPlayerOne();
else t.validInputPlayerTwo();
t.boardFill();
turn += 1;
}
Of course, now you have to actually write the noWinner function.
Answering your question directly, you could have a boolean that toggles on each move:
boolean firstPlayer = true;
while (t.gameIsNotFinished()) {
if (firstPlayer)
t.validInputPlayerOne();
else
t.validInputPlayerTwo();
firstPlayer = !firstPlayer;
}
However you have a lot of other issues with your code that you need to address. For example if a player enters an invalid value then it goes to the next player rather than asking for them to reenter the value.
You should also try to have a single validInputPlayer method that works for both players with the firstPlayer variable passed in. At the moment you have a lot of repeated code in those methods.
so I have being doing this program to verify if the word "bob" is in a string that the user enters. Example: "asddbobasd" -> "here is bob". Also, if there is one character between the bs it should print out "here is bob". Otherwise, it should print "here isn't bob".
tl dr: bxb = here is bob .bob = here is bob. bok = here isn't bob. When I'm executing the program, netbeans throws me an (!) at the if statement of (yed=='b' && zed=='b')
package lab;
import java.util.Scanner;
public class Lab {
public static void main(String[] args) {
char yed,zed;
Scanner sc = new Scanner (System.in);
String x;
System.out.println("Word");
x = sc.nextLine().toLowerCase();
int m=0;
for (int i = 0; i<=x.length(); i++) {
yed = x.charAt(i);
int j=i+2;
zed = x.charAt(j);
if (yed=='b' && zed=='b')
m++;
}
if (m>0){
System.out.println("here is bob");
}
if (m==0) {
System.out.println("here isn't bob");
}
}
}
Try to replace this:
for (int i = 0; i<=x.length(); i++) {
With using i<x.length()-2 instead of i<=x.length():
for (int i = 0; i<x.length()-2; i++) {
Okay so I know there are other Morse code answers out there, but I have looked at many, but none of them worked. For my assignment I was to read a file, Morse.txt, into parallel arrays. Instead I just made two files, Morse.txt and Alphabet.txt one with code and the other with numbers and alphabet. I am supposed to use a class I made to do the translating part and when called in main it should translate user input. I can't seem to get this working. I've tried so many things from using a toString in the class or getter, but the return is not found when I put in the loop which I think has to be there(if that makes sense)..anyway here is my code for main:
import java.util.*;
import java.util.Scanner;
import java.io.*;
public class redo
{
public static void main(String[]args) throws IOException
{
String line2, file2 = "Morse.txt";
String line, file = "Alphabet.txt";
File openFile = new File(file);
File openFile2 = new File(file2);
Scanner inFile = new Scanner(openFile);
Scanner inFile2 = new Scanner(openFile2);
int index = 36;
char[] charArray = new char[index];
String[] code = new String[index];
for(index = 0; index < 36; index++)
{
while(inFile.hasNext())
{
line = inFile.nextLine();
charArray = line.toCharArray();
//System.out.println(charArray[index]);
}
}
for(index = 0; index < 36; index++)
{
while(inFile2.hasNext())
{
code[index] = inFile2.nextLine();
//System.out.println(code[index]);
}
}
Scanner keyboard = new Scanner(System.in);
String userInput;
System.out.println("Enter something to translate: ");
userInput= keyboard.nextLine();
Translate inputTranslate = new Translate(userInput);
inputTranslate.setInput(userInput);
inputTranslate.setAlph(charArray);
inputTranslate.setCode(code);
inFile.close();
}
}
and here is my class Translate(some things are commented out):
public class Translate
{
String input;
String code[];
char alph[];
public Translate(String input)
{
this.input = input;
}
public void setInput(String input)
{
this.input = input;
}
public void setAlph(char[] alph)
{
this.alph = alph;
}
public void setCode(String[] code)
{
this.code = code;
}
public String getInput()
{
return input;
}
// public String getTranslate()
// {
// for(int i = 0; i < input.length(); i++)
// {
// for(int index = 0; index < alph.length; index++)
// {
// if(input.charAt(i) == alph[index])
// {
// String output = code[index];
// }
// }
// }
// return output;
// }
}
Morse.txt:
.----
..---
...--
....-
.....
-....
--...
---..
----.
.-
-...
-.-.
-..
.
..-.
--.
....
..
.---
-.-
.-..
-.
.--.
--.-
.-.
...
..-
...-
.--
-..-
-.--
--..
Alphabet.txt:
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
The problem is your return can't reach "output", you need to declare "output" above the loops and initialise it to output = null;
Even then it'll only send one string. So I did this;
public String getTranslate()
{
String output = null;
String[] translated = new String[input.length()];
for(int i = 0; i < input.length(); i++)
{
for(int index = 0; index < alph.length; index++)
{
if(input.charAt(i) == alph[index])
{
output = code[index];
translated[i] = output;
}
}
}
for (int j = 1; j < translated.length; j++) {
output = translated[0].concat(translated[j]);
}
return output;
}
This basically sticks all the codes together giving you your desired outcome.