Additive operator used with char values produces different results [duplicate] - java

This question already has answers here:
The concatenation of chars to form a string gives different results
(5 answers)
Closed 7 years ago.
I am getting a strange return for the below block of code (sets of integer values):
public String doubleChar(String str) {
String answer = "";
for (int i = 0; i < str.length(); i++) {
answer = answer + (str.charAt(i) + str.charAt(i));
}
return answer;
}
Opposed to the correct output value (a duplication of the strings chars) when I remove the parentheses enclosing the str.chatAt method calls in the first statement line of the loop:
answer = answer + str.charAt(i) + str.charAt(i);
Any help is appreciated, could not track down online.
Thanks

In Java char is an integral type. It appears you wanted String concatenation (that is String addition). You could use
public String doubleChar(String str) {
String answer = "";
for (int i = 0; i < str.length(); i++) {
answer = answer + String.valueOf(str.charAt(i))
+ String.valueOf(str.charAt(i));
}
return answer;
}
or (my preference) a StringBuilder like
public String doubleChar(String str) {
StringBuilder sb = new StringBuilder();
for (char ch : str.toCharArray()) {
sb.append(ch).append(ch);
}
return sb.toString();
}

Related

How do I add commas when converting from Int [] to String? [duplicate]

This question already has answers here:
How to remove last comma and space in array? Java [duplicate]
(3 answers)
Closed 5 months ago.
Hei
I'm a beginner in Java and I have homework and I spent all day trying to figure out the solution and I couldn't. I'm so frustrated
Can someone help me?
Converting from any table in Int [] to string for eksmpel : int [] a = { 1,2,3} to String s = [1,2,3]
I didn't know how to put the comma, it always shows a trailing comma at the end or at the beginning a trailing comma as well as parentheses.
This is my code :
public class Test11 {
public static String til(int[] tabell) {
String str = "";
String na1 = "[";
String na2 = "]";
String na3 = ",";
String str3 = "";
for (int i = 0; i < tabell.length; i++) {
str += "," + tabell[i];
}
return str;
}
public static void main(String[] args) {
int[] tab = { 1, 2, 3 };
System.out.println(til(tab));
}
}
You need to handle the first iteration through your loop as a special case, because you don't want to add a comma the first time around. There's something you can use to know that you're in the first iteration...the fact that the string you're building is empty because you haven't added anything to it yet.
This makes extra good sense because if the string is empty, then it doesn't yet contain a term that you want to separate from the next term with a comma.
Here's how you do this:
String str = "";
for (int i = 0; i < tabell.length; i++) {
if (str.length() > 0)
str += ",";
str += tabell[i];
}
Use a variable to keep track of whether or not you're on the first iteration. If you are, don't put a comma before it.
boolean isFirst = true;
for (int i = 0; i < tabell.length; i++) {
if (!isFirst) {
str += ",";
}
isFirst = false;
str += tabell[i];
}

Check if a given word is a palindrome [duplicate]

This question already has answers here:
Check string for palindrome
(42 answers)
Closed 1 year ago.
I am trying to write a method to check if a given word is a palindrome, but as of now it does not work. I suspect the error lies within the if-statement and the fact that you don't compare objects such as strings with == but instead with equals, is that right? However Java does not allow me to write: if (firstHalf.charAt(i).equals(secondHalf.charAt(j))), so what can I do to make it work? Are there other errors in the code?
public static boolean isPalindrome(String string) {
String firstHalf = string.substring(0, string.length() / 2);
String secondHalf = string.substring(string.length() / 2, string.length());
for (int i = 0; i <= firstHalf.length(); i++) {
for (int j = secondHalf.length(); j <= 0; j--) {
if (firstHalf.charAt(i) == secondHalf.charAt(j)) {
return true;
}
}
}
return false;
}
Why not do it this way?
public static boolean isPalindrome(String string){
StringBuilder sb = new StringBuilder(string);
sb.reverse();
return sb.toString().equals(string);
}
Your character test was backwards. All of the comparisons have to be equal for the String to be a palindrome.
Also, splitting the String is unnecessary. You can logically split the String with two indices.
Try this code.
public static boolean isPalindrome(String string) {
int frontIndex = 0;
int backIndex = string.length() - 1;
while (frontIndex < backIndex) {
if (string.charAt(frontIndex++) != string.charAt(backIndex--)) {
return false;
}
}
return true;
}
you can make each character a String like so
String s1 = "" + c1;
and then compare them with .equals(s1, s2)
Or you can use the Character class which is a wrapper around primitive character.
That would also enable you to use c1.equals(c2)

How to fix "char cannot be converted to java.lang.String" in Caesar Cipher Program [duplicate]

This question already has answers here:
error: incompatible types: char cannot be converted to String - Java [duplicate]
(4 answers)
Closed 3 years ago.
I'm just a starter at java, and I'm trying to figure out the codingbat "Ceaser Cipher" problem. The questions says to "Develop a method that accepts as input a shift value and a message. The shift value will be no less than -25 and no greater than 25. Any character that occurs in the message and that is not an upper case letter should be encoded as itself." The program already applies the message and value.
For example, if the message is "ABCDE" and the shift is 1, it should print "BCDEF".
Eveyrtime I try to run my code, I get a "char cannot be converted to java.lang.String line:9" error. Does anyone know how to fix this?
public String CaesarCipher(int shift, String message) {
for (int i = 0;i < message.length(); i++){
char letter = message.charAt(i);
if (Character.isUpperCase(letter)){
int ascii = (int)letter;
ascii += shift;
char newMsg = (char)ascii;
return newMsg;
}
else{
return letter;
}
}
}
That is because you're trying to return a char while the return type of your CaesarCipher function is String. In Java char and String are different data types, meaning that they are not interchangeable, the same goes for all the data types. You'd get a warning if you were using an IDE, so I'd suggest you write your code in an IDE before pasting it to Coding Bat.
This might help: How to convert ASCII to String
I believe this is what you need:
public String CaesarCipher(int shift, String message) {
String result = "";
for (int i = 0; i < message.length(); i++) {
char letter = message.charAt(i);
if (Character.isUpperCase(letter)) {
int ascii = (int) letter;
ascii += shift;
result += Character.toString((char)ascii);
} else {
result += Character.toString(letter);
}
}
return result;
}
That error code implies that return statement is not giving right type of variable. Your method wants String back but is getting char. This is easily solved by changing your char to String with String.valueOf(newMsg).
public static String CaesarCipher(int shift, String message) {
for (int i = 0;i < message.length(); i++){
char letter = message.charAt(i);
if (Character.isUpperCase(letter)){
int ascii = (int)letter;
ascii += shift;
char newMsg = (char)ascii;
return String.valueOf(newMsg);
}
else{
return String.valueOf(letter);
}
}
//should not come to this
return "a";
}
Your code doesn't work as you expect. First iteration of the for loop will always exit because return statement. There are also redundant variables and casts. Even a free Java IDE like IntelliJ IDEA Community will highlight these problems so please consider installing one.
What you want to do is to build the result with a StringBuilder and return it after the loop completes:
public static String caesarCipher(int shift, String message) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < message.length(); i++) {
char letter = message.charAt(i);
if (Character.isUpperCase(letter)) {
char shiftLetter = (char) (letter + shift);
builder.append(shiftLetter);
}
}
return builder.toString();
}
You are trying to return a Character when the method requires you to return a String. Instead of returning newMsg or letter, you want to create a new string at the beginning of the method and set the next character the string to that value, like this:
public String CaeserCipher(int shift, String message) {
String updated_message = "";
for (int i = 0; i < message.length(); i++) {
...
char newMsg = (char)ascii;
updated_message += newMsg;
...
updated_message += letter;
} // end for
return updated_message;
}

Ouput of Reversing words of String does not come as expected [duplicate]

This question already has answers here:
Reverse a given sentence in Java
(14 answers)
Closed 7 years ago.
Given a String with words.Reverse words of String.
Sample Input 1
Hello World
Sample Output
World Hello
MyApproach
To reverse words I first counted how many spaces are there.After that I stored their space index in an array.Using lastIndex, I printed the last elements of the array.After that I printed the last 2 words of the array.
static String reverseWords(String inputString)
{
int l1=inputString.length();
int count=1;
for(int i=0;i<l1;i++)
{
char ch=inputString.charAt(i);
if(ch==' ')
{
count++;
}
}
int k=0;
int[] spaceindex=new int[count];
spaceindex[0]=0;
k++;
for(int i=0;i<l1;i++)
{
char ch=inputString.charAt(i);
if(ch==' ')
{
spaceindex[k++]=i+1;
}
}
int p=spaceindex.length-1;
String strnew="";
for(int j=spaceindex[p];j<l1;j++)
{
char c=inputString.charAt(j);
strnew=strnew+c;
}
p--;
while(p>=0)
{
for(int j=spaceindex[p];;j++)
{
char c=inputString.charAt(j);
if(c==' ')
{
break;
}
strnew=strnew+c;
}
}
return strnew;
}
InputParameters ActualOutput Expected Output
Hello World WorldHelloWorldHello(Infinite loop) WorldHello
#Edit I asked Why the code I wrote is wrong.I tried without using any inbuilt functions(which was necessary for me).In that way I think It is not Duplicate Ans according to me.
Can anyone guide me what went wrong in my code.
The issue within your code was the while loop:
while(p>=0) {
strnew = strnew + " ";
for(int j=spaceindex[p];;j++) {
char c=inputString.charAt(j);
if(c==' '){
break;
}
strnew=strnew+c;
}
p--;
}
Adding the p-- will prevent the loop for occurring infinitely. Also inserting the strnew = strnew + " "; after the while loop ensures a space in between each word.
It's possible without using another arrays, splits or any additional strucure.
Having array of characters ( convert if needed as String is immutable), first reverse all characters in the array. Secondly loop over spaces and for each word reverse characters in the word.
Simple solution :
public static void main(String[] args) {
String x = "Hello World";
String[] xArray = x.split(" ");
String result = "";
for (int i = xArray.length - 1; i >= 0; i--) {
result += xArray[i] + " ";
}
System.out.println(result.trim()); // World Hello
}
You can use a StringTokenizer to convert the string into tokens or String.split function. You can push this collection into a Stack and extract the elements in a reverse order. To join the strings back you could use a StringBuilder or a StringBuffer.
To do this more efficiently you could convert the string to a character array and StringBuilders
String myString = "Here is the String";
char[] myChars = myString.toCharArray();
StringBuilder word = new StringBuilder();
StringBuilder newString = new StringBuilder();
for(int i = myChars.length - 1; --i >= 0;) {
char c = myChars[i];
if(c == ' ') {
newString.append(c);
newString.append(word);
word = new StringBuilder();
} else {
word.append(c);
}
}
I would base an implementation on String.lastIndexOf(int) and String.substring(int, int). I'd got with a StringBuilder to construct the output "sentence" and a while loop to iterate the words in reverse order. Something like,
static String reverseWords(String in) {
StringBuilder sb = new StringBuilder(in.length());
int space;
while ((space = in.lastIndexOf(' ')) > 0) {
sb.append(in.substring(space + 1, in.length())).append(' ');
in = in.substring(0, space);
}
sb.append(in);
return sb.toString();
}
Which I tested with your provided sample
public static void main(String[] args) {
System.out.println(reverseWords("Hello World"));
}
Getting (as expected)
World Hello

Remove Adjacent duplicate from a string keeping only one instance: java [duplicate]

This question already has answers here:
Java String Manipulation : Comparing adjacent Characters in Java
(12 answers)
Closed 7 years ago.
It is difficult to say in words so i ll use examples. Consider following inputs:-
Input String = AABBSTUUUX
Output String = ABSTUX
How to achieve this in java.
This should do it
String word = "AABBSTUUUX";
for (int i = 0; i < word.length() - 1; i++) {
if (word.charAt(i) == word.charAt(i + 1)) {
word.deleteCharAt(i + 1);
}
}
System.out.println(word);
Steps:
Scan the String from first to last
Add each character in in a char type variable temp
Compare each character to the temp except for the first (marked by index 0) character and delete the duplicate
An implementation similar to #Razib's solution above:
public String removeDupes(String in) {
if (in == null || in.length() <= 1) {
return in;
}
char lastLetter = in.charAt(0);
String out = String.valueOf(lastLetter);
for (int i = 1; i < in.length(); i++) {
char nextLetter = in.charAt(i);
if (nextLetter != lastLetter) {
out += nextLetter;
}
lastLetter = nextLetter;
}
return out;
}
Obviously, this is case-sensitive and will remove duplicate non-word characters as well.

Categories

Resources