Java Unexpected type error [duplicate] - java

This question already has answers here:
Replace a character at a specific index in a string?
(9 answers)
Closed 6 years ago.
I am trying to create a method that will consume two Strings. It will Compare String 1 with String 2 and will replace all unfound chars with '_'. For example if String 1 = "Hello"; String 2 = "eo" then the method will return String 1 as "_e__o" Here is my code:
static String getRevealedChars (String s1, String s2)
{
for (int i = 0; i < s1.length(); i++)
{
for (int c = 0; c < s2.length(); c++)
{
if (s1.charAt(i) == s2.charAt(c))
{
break;
}
else
{
// this is where I get my Error
s1.charAt(i) = '_';
}
}
}
}
However, when I run this code I get a "unexpected type" error at s1.charAt(i) = '_';. I'm really new to java, thanks in advance.

Replace datatype of s1 and s2 from String to StringBuilder, then use setCharAt() instead of charAt() as follows:
StringBuilder s1 = new StringBuilder("hello");
StringBuilder s2 = new StringBuilder("eo");
static String getRevealedChars (StringBuilder s1, StringBuilder s2)
{
for (int i = 0; i < s1.length(); i++)
{
for (int c = 0; c < s2.length(); c++)
{
if (s1.charAt(i) == s2.charAt(c))
{
break;
}
else
{
// this is where I corrected Error
s1.setCharAt(i, '_');
}
}
}
}
Hope this helps. Good luck.

Related

How to ignore spaces while Sorting a string in java?

I tried to code a program to detect an anagram with 2 Strings given.
My approach is to convert both strings to char Arrays and then sort them before comparing them.
I know I could use the sort() function but I don't want to use any imports for training purposes.
The problem is i want my programm to ignore blanks while scanning for an anagram.
in the current version the ouput is like this:
(triangle, relating) ---> true
(tri angle, relating) ---> false
while it should be both true.
i would be thankful for any help!
heres my code, (please ignore my comments):
public static boolean anagramCheck(String a, String b) {
boolean r = true;
// In Char Arrays umwandeln /
char[] Ca = a.toCharArray();
char[] Cb = b.toCharArray();
// Laengen Abfrage
int L1 = Ca.length;
int L2 = Cb.length;
// Erste For-Schleife
for (int i = 0; i < L1; i++) {
for (int j = i + 1; j < L1; j++) {
if (Ca[j] < Ca[i]) {
char temp = Ca[i];
Ca[i] = Ca[j];
Ca[j] = temp;
}
}
}
// Zweite For-schleife
for (int i = 0; i < L2; i++) {
for (int j = i + 1; j < L2; j++) {
if (Cb[j] < Cb[i]) {
char temp = Cb[i];
Cb[i] = Cb[j];
Cb[j] = temp;
}
}
}
// Char Arrays zu Strings
String S1 = String.valueOf(Ca);
String S2 = String.valueOf(Cb);
// Vergleich und Ausgabe
if (S1.compareTo(S2) == 0) {
return r;
}
else {
r = false;
return r;
}
}
}
The String.replace(String, String) is the non-regexp replace method.
So remove all spaces:
String S1 = String.valueOf(Ca).replace(" ", "");
String S2 = String.valueOf(Cb).replace(" ", "");
It would be nicer to do this on a and b.
public static boolean isAnagram(String one, String two) {
char[] letters = new char[26];
for (int i = 0; i < one.length(); i++) {
char ch = Character.toLowerCase(one.charAt(i));
if (Character.isLetter(ch))
letters[ch - 'a']++;
}
for (int i = 0; i < two.length(); i++) {
char ch = Character.toLowerCase(two.charAt(i));
if (Character.isLetter(ch))
letters[ch - 'a']--;
}
for (int i = 0; i < letters.length; i++)
if (letters[i] != 0)
return false;
return true;
}
Generally, less code is better (if it’s readable). And learning a language means learning the built in libraries.
Here’s a method to return a String of sorted chars:
public static String sortChars(String str) {
return str.replace(" ", "").chars().sorted()
.mapToObj(c -> (char)c + "")
.collect(Collectors.joining(""));
}
With this method, your main method becomes:
public static boolean anagramCheck(String a, String b) {
return sortedChars(a).equals(sortedChars(b));
}
Refactoring like this, using well-named methods makes your code easier to understand, test, debug and maintain.
It’s worth noting that you don’t actually need a sorted String… a sorted array would serve equally well, and requires less code:
public static int[] sortChars(String str) {
return str.replace(" ", "").chars().sorted().toArray();
}
public static boolean anagramCheck(String a, String b) {
return Arrays.equal(sortedChars(a), sortedChars(b));
}
A frequency map could be created with the characters from String one incrementing and the characters from String two decrementing, then the resulting map should contain only 0 as values.
To skip non-letters, Character::isLetter can be used.
public static boolean isAnagram(String a, String b) {
Map<Character, Integer> frequencies = new HashMap<>();
for (int i = 0, na = a.length(), nb = b.length(), n = Math.max(na, nb); i < n; i++) {
if (i < na && Character.isLetter(a.charAt(i)))
frequencies.merge(Character.toLowerCase(a.charAt(i)), 1, Integer::sum);
if (i < nb && Character.isLetter(b.charAt(i)))
frequencies.merge(Character.toLowerCase(b.charAt(i)), -1, Integer::sum);
}
return frequencies.values().stream().allMatch(x -> x == 0);
}

how to merge two strings into one by using chartAt() and arrays technique

as mentioned in the title, I got an error in each line inside for loop which says (variable expected) and this is my code
String s = "ABC";
String t = "DEFGH";
String merge = "";
// merge should looks like "ADBECFGH"
int i = 0;
for (; i < s.length(); i=i+2) {
merge.charAt(i) = s.charAt(i/2);
merge.charAt(i+1) = t.charAt(i/2);
}
for (; i < t.length()+s.length() ; i++) {
merge.charAt(i) = t.charAt(i-s.length());
}
am trying to use same technique with arrays which I think its very effective.
If you like take one letter from first string and then from other try this:
for (int i = 0; i < s.length() || i < t.length(); i++) {
if (i < s.length()) {
merge += String.valueOf(s.charAt(i));
}
if (i < t.length()) {
merge += String.valueOf(t.charAt(i));
}
}
This is condition that let you iterate till longer String finish
i < s.length() || i < t.length()
Another one, since you are manipulating Strings inside a loop, it is better to use StringBuilder instead of String.
String s = "ABC";
String t = "DEFGH";
StringBuilder merge = new StringBuilder();
for (int i = 0; i < s.length() || i < t.length(); i++) {
if (i < s.length()) {
merge.append(s.charAt(i));
}
if (i < t.length()) {
merge.append(t.charAt(i));
}
}
System.out.println(merge.toString());
The method charAt(int index) returns the character at the specified index(IT IS A GETTER NOT A SETTER). You cannot use it as
merge.charAt(i) = s.charAt(i/2)
one of the easiest ways to perform such operation is to use string operation such as concatination as shown in the below example
s="abc";
t="def";
System.out.print(s.concat(t));
You could simply use the .concact() method without using the for loop:
so your code would look like:
merge = s.concat(t);
try this : concatenate two string without inbuilt method and without + operator.
public static void main(String[] args) {
String s = "ABC";
String s1 = "DEF";
String merge = "";
char[]ch = new char[120];
for(int i=0;i<s.length();i++) {
ch[i] = s.charAt(i);
}
for(int i = 0;i<s1.length();i++) {
ch[s.length()+i] = s1.charAt(i);
}
System.out.println(ch);
}
CharacterIterator a = new StringCharacterIterator("haaaaallo");
CharacterIterator b = new StringCharacterIterator("12345");
StringBuilder output = new StringBuilder();
if(a.getEndIndex() < b.getEndIndex()) { //true -> swap a and b
CharacterIterator holder = a;
a = b;
b = holder;
}
while (a.current() != CharacterIterator.DONE) {
output.append(a.current());
while (b.current() != CharacterIterator.DONE) {
output.append(b.current());
break;
}
a.next();
b.next();
}
System.out.println(output.toString()); //h1a2a3a4a5allo
To show "the manual way". The used Strings can be any size.
I would go with #Bartek's answer its simple and easy to remember..
the complicated way to achieve this would be
String a = "abcdefgh";
String b = "ijklmnopqrst";
int i = 0;
StringBuilder merge = new StringBuilder();
for (; i < a.length() && i < b.length(); i++) {
merge.append(a.charAt(i)).append(b.charAt(i));
}
if (i < a.length())
merge.append(a.substring(i));
if (i < b.length())
merge.append(b.substring(i));
Only to avoid having if conditions inside the for loop.. (optimal only in case of large strings, strings of vastly different lengths)

How to merge two String into one String in java

Suppose:
String s1="13579";
String s2="2468";
then output would be 123456789
Here my code :
public class JoinString {
public static void main(String[] args) {
String s1 = "13579";
String s2 = "2468";
for (int i = 0; i < s1.length(); i++) {
for (int j = i; j < s2.length(); j++) {
System.out.print(s1.charAt(i) + "" + s2.charAt(j));
break;
}
}
}
}
StringBuilder buf = new StringBuilder();
for (int i = 0; i < Math.max(s1.length(), s2.length()); i++) {
if (i < s1.length()) {
buf.append(s1.charAt(i));
}
if (i < s2.length()) {
buf.append(s2.charAt(i));
}
}
final String result = buf.toString();
You only need one loop. Also, you can use a StringBuilder class to build your string character by character.
How about this little trick:
String s1 = "13579";
String s2 = "2468";
String s3 = (s1 + s2).codePoints() // stream of code points
.sorted()
// collect into StringBuilder
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
System.out.println(s3); // 123456789
A simple way to achieve that is by doing something like this:
String s1 = "13579";
String s2 = "2468";
char[]result = (s1+s2).toCharArray();
Arrays.sort(result);
System.out.println(result);
Output:
123456789
You just need to combine the logic of the two loops like this (and use StringBuilder if you want to build a string this way).
String s1 = "13579";
String s2 = "2468";
int length = Math.max(s1.length(), s2.length());
for (int i = 0; i < length; i++) {
if(i < s1.length())
System.out.print(s1.charAt(i));
if(i < s2.length())
System.out.print(s2.charAt(i));
}
Similar to #Roman Puchovskiy, here is a way to do it without the StringBuilder.
String s1 = "abcde";
String s2 = "defgh";
String combined = "";
int length = s1.length() > s2.length() ? s1.length() : s2.length(); //Finds the longest length of the two, to ensure no chars go missing
for(int i = 0 ; i < length ; i++) {
if(i < s1.length()) { // Make sure there is a char in s1 where we're looking.
combined += s1.charAt(i);
}
if(i < s2.length()) { // Same with s2.
combined += s2.charAt(i);
}
}
Where combined becomes the combined string. ("adbecfdgeh").
Hope this helps!
Similar way as merge method in merge sort.
Also it's better if you convert string to char array so that random access to element is in constant time.
Because charAt has O(n) time complexity.
public class JoinString {
public static void main( String[] args ) {
String s1 = "13579";
String s2 = "2468";
final char[] str1 = s1.toCharArray();
final char[] str2 = s2.toCharArray();
int i;
for ( i = 0; i < str1.length && i < str2.length; i++ ) {
System.out.print( str1[i] + "" + str2[i] );
}
while ( i < str1.length ) {
System.out.print( str1[i] + "" );
i++;
}
while ( i < str2.length ) {
System.out.print( str2[i] + "" );
i++;
}
}
}

how to combine or merge two strings in java? [duplicate]

This question already has answers here:
How do I concatenate two strings in Java?
(23 answers)
Closed 5 years ago.
Below is my code I'm expecting the output as "afbgchde" and not "abcdefgh" but ending up with out of index error, Hope there is a better way to get this..Please help..!!
String str1 = "abcde";
//char[] a = str1.toCharArray();
//System.out.println(a);
String str2 = "fgh";
char[] b = str2.toCharArray();
//System.out.println(b);
int i,j=0;
try
{
for(i=0;i<str1.length();i++)
{
char c = str1.charAt(i);
System.out.print(c);
if(j==i)
{
char d = str2.charAt(j);
System.out.print(d);
j++;
}
}
}
catch(Exception e)
{
System.out.println(e);
}
Simple:
char d = str2.charAt(j);
System.out.print(d);
j++;
You are accessing chars in your second string; but you never bother to check if j is still < str2.length().
Meaning: your for-loop for i contains that check; and prevents going beyond the length of str ... but then you forget to do that on your other string! So your merge only works when str and str2 happen to have the same size.
So a solution would more look like:
StringBuilder builder = new StringBuilder();
int j = 0;
for (int i=0; i < str.length(); i++) {
builder.append(str.charAt(i));
if (j < str2.length()) {
builder.append(str2.charAt(j));
j++;
}
}
// if str2 has more chars than str
if (j < str2.length()) {
// append ALL chars starting from index j
builder.append(str2.substring(j));
}
String merged = builder.toString();
Complete Code for your combiner.
public class StringCombiner {
public static void main(String[] args){
System.out.println(combine("Hello", "World"));
System.out.println(combine("He", "World"));
System.out.println(combine("Hello", "Wo"));
}
public static String combine(String str1, String str2){
StringBuilder output = new StringBuilder();
int i =0;
for(; i< str1.length(); ++i){
output.append(str1.charAt(i));
if(i < str2.length()){
output.append(str2.charAt(i));
}
}
if(i < str2.length()){
for(; i<str2.length(); ++i){
output.append(str2.charAt(i));
}
}
return output.toString();
}
}
Output:
HWeolrllod
HWeorld
HWeollo
Hope this helps.
Okay. Lets try this
String str1 = "abcde";
String str2 = "fgh";
int bigLength = str1.length()>str2.length()?str1.length():str2.length();
for(int i = 0; i<bigLength; i++){
if(i<str1.length())
System.out.print(str1.charAt(i))
if(i<str2.length())
System.out.print(str2.charAt(i))
}
Hope this will work for you.
just use StringBuilder class man
if you want to change a value of a String object
String class is an object that is unchangeable or can't be change when it is initialized
StringBuilder class is the best solution for any String that you want to have a change while the application is running
e.g. add a String or change value of a String or even shorten a String
that is the power of StringBuilder class
`

Check if a string has all the characters of another string [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
String one = "This is a test";
String two = "This is a simple test";
I want to check if two contains all the characters that are in one, and ignore the fact it has extra characters.
The fastest thing would probably be to break them up to HashSets and then apply containsAll
public static Set<Character> stringToCharacterSet(String s) {
Set<Character> set = new HashSet<>();
for (char c : s.toCharArray()) {
set.add(c);
}
return set;
}
public static boolean containsAllChars
(String container, String containee) {
return stringToCharacterSet(container).containsAll
(stringToCharacterSet(containee));
}
public static void main(String[] args) {
String one = "This is a test";
String two = "This is a simple test";
System.out.println (containsAllChars(one, two));
}
static boolean stringContains(String longer, String shorter) {
int i = 0;
for (char c : shorter.toCharArray()) {
i = longer.indexOf(c, i) + 1;
if (i <= 0) { return false; }
}
return true;
}
Using a simple loop over the set of the characters in the first string:
String s1 = "This is a test";
String s2 = "This is a simple test";
Set<Character> chars = new HashSet<Character>();
for(int i = 0; i < s1.length(); i++) {
chars.add(s1.charAt(i));
}
for (Iterator<Character> iterator = chars.iterator(); iterator.hasNext();) {
Character character = iterator.next();
if(!s2.contains(character.toString())) {
// break and mark as not contained
break;
}
}
If words are meant to be checked, then you could split the string around whitespaces into a list of words:
String[] words1 = s1.split("\\s");
String[] words2 = s2.split("\\s");
List<String> wordList1 = Arrays.asList(words1);
List<String> wordList2 = Arrays.asList(words2);
System.out.println(wordList2.containsAll(wordList1));
two.startsWith(one)
If you aren't sure about the start position (the above assumes 0), try using the following API
startsWith(String, offset)
Try this. I know it's long but it works
public static void main(String[] args)
{
String String1,String2;
int i, j, count1, count2;
count1 = 0;
count2 = 0;
String1 = "This is a test";
String2 = "This is a simple test";
char[] list1 = new char[String2.length()];
char[] list2 = new char[String2.length()];
char[] list3 = new char[String2.length()];
for (i = 0; i <= String1.length() - 1; i++)
{
list1[i] = String1.charAt(i);
for (j = 0; j <= String2.length() - 1; j++)
{
list2[j] = String2.charAt(j);
if (list1[i] == list2[j])
{
i++;
count1++;
}
}
}
for (i = 0; i <= String1.length() - 1; i++)
{
list1[i] = String1.charAt(i);
for (j = 0; j <= String1.length() - 1; j++)
{
list3[j] = String1.charAt(j);
if (list1[i] == list3[j])
{
i++;
count2++;
}
}
}
if (count1 >= count2)
System.out.println(true);
else
System.out.println(false);
}

Categories

Resources