Print multiple char variables in one line? - java

So I was just wondering if there was a way to print out multiple char variables in one line that does not add the Unicode together that a traditional print statement does.
For example:
char a ='A';
char b ='B';
char c ='C';
System.out.println(a+b+c); <--- This spits out an integer of the sum of the characters

System.out.println(a+""+b+""+c);
or:
System.out.printf("%c%c%c\n", a, b, c);

You can use one of the String constructors, to build a string from an array of chars.
System.out.println(new String(new char[]{a,b,c}));

The println() method you invoked is one that accepts an int argument.
With variable of type char and a method that accepts int, the chars are widened to ints. They are added up before being returned as an int result.
You need to use the overloaded println() method that accepts a String. To achieve that you need to use String concatenation. Use the + operator with a String and any other type, char in this case.
System.out.println(a + " " + b + " " + c); // or whatever format

This will serve : System.out.println(String.valueOf(a) + String.valueOf(b) + String.valueOf(c));.

System.out.println(new StringBuilder(a).append(b).append(c).toString());

System.out.print(a);System.out.print(b);System.out.print(c) //without space

Related

Why is it necessary to put double quotes?

In the code line
editText.setText(firstnum + secondnum + "");
Can anyone explain to me why there are double quotes at the end?
firstnum and secondnum are both of type Float it seems so adding them will result in a Float, the setText() method takes a String not a Float, when adding + "" java will automatically convert the addition of the 2 Floats to a string, think if you had:
editText.setText(5 + " apples");
Then java will think you want to have a string "5 apples" that is why it convert the int before the string to a string representation then append it to " apples".
This is to enforce conversion of your integer value (result of firstnum + secondnum) to string, which is what setText() requires as argument. There's also setText() that accepts int (you are using floats so that's not the case anyway) but that int will be used as ID of string resource which is not what you want, hence need of conversion to string. It's also just less typing. It's basically equivalent of replacing:
editText.setText(firstnum + secondnum + "");
with:
editText.setText(String.valueOf(firstnum + secondnum));
The + is an overloaded operator
when it is between two numbers that it will add them
but adding the "" will make it in a string
setText wants a String.
if you want to get a String from an int you can use String.valueOf(i) or i+"".

Interger being passed but a Char value expected expected?

Hi im trying to make a letter guessing game with 3 random letters, when i try to get a value using the below code it always a returns as an int to the other program bellow im trying to receive it as a letter but can't figure it out.
import java.util.Random;
public class CodeLetter {
private char letterValue;
int count = 8;
Random rnd = new Random ();
public char codeLetter(){
letterValue = (char)(rnd.nextInt(5)+'A');
System.out.println(letterValue);
return letterValue;
}
}
The code that calls the above code using line
letter1 = codeLetter.codeLetter();
but once it is printed to screen it still holds an int value, not the char.
This program requires both classes as requirments
public class CodeBreaker {
private char letter1;
private char letter2;
private char letter3;
CodeLetter codeLetter = new CodeLetter();
public void CodeBreaker(){
//Welcome Screen
System.out.println("Welcome to CODEBREAKER ");
System.out.println("you have 6 tries to guess the secret 3 letter code.");
System.out.println("The letters Range from A to E");
System.out.println("Goodluck");
System.out.println("The code has no repeat letters");
//end
letter1 = codeLetter.codeLetter();
letter2 = codeLetter.codeLetter();
letter3 = codeLetter.codeLetter();
System.out.println(letter1 + letter2 + letter3);
}
/*public boolean done(){
}
/*private boolean isValid*char){
//- Is the given letter valid?
}*/
public void getGuess(/*int*/){
//- Get guess #
}
public void checkGuess(){
//- Verify the guess
}
public void display(){
//- Display the secret code
}
}
I have run your program. Bellow output I have found.
Welcome to CODEBREAKER
you have 6 tries to guess the secret 3 letter code.
The letters Range from A to E
Goodluck
The code has no repeat letters
B
B
C
199
If I understand you correctly You have problem with that 199. I assume, you want BBC instead of 199. It is because you use + sign with the char type that will implicitly converted into integer and do arithmetic operation. So you have problem with the following line System.out.println(letter1 + letter2 + letter3);. You can print separately those different char.
BTW, your codeletter() method return char as expected. Also for this kind of language behavior you can researh on Strongly vs Weakly type
The + operator is either a numeric additive operator or a string concatenation operator.
The Java Language Specification, §15.18. Additive Operators, say:
If the type of either operand of a + operator is String, then the operation is string concatenation.
Otherwise, the type of each of the operands of the + operator must be a type that is convertible (§5.1.8) to a primitive numeric type, [...]
Your code (letter1 + letter2 + letter3) is a char + char + char expression, and since none of them are String values, it's a numeric add expression.
You have many choices for fixing that:
Create a String directly from a char[]:
new String(new char[] { letter1, letter2, letter3 })
This is the most efficient way, both performance-wise and memory-wise.
I recommend doing it this way.
Convert the first letter to a String, so the + operator becomes a string concatenation operator:
String.valueOf(letter1) + letter2 + letter3
This is shorter to write, but is less efficient, since it first creates a temporary string, then have to perform a string concatenation to build the final string.
Another way to convert the first letter to a String:
Character.toString(letter1) + letter2 + letter3
Internally, Character.toString() calls String.valueOf() (Java 8), so it's really the same, and you can use whichever you like best.
Perform the string concatenation directly, so you don't need to create the initial temporary string:
new StringBuilder().append(letter1).append(letter2).append(letter3).toString()
Very verbose.
Start with an empty string:
"" + letter1 + letter2 + letter3
This is the most terse way to write it. A lot of people like this way because of the terseness, and I believe the minimal overhead of the extra string will even be eliminated in Java 9.
What you are looking for is Character.forDigit()

In Java, why the output of int a=('a'+'b'+'c'); are different form System.out.println('a'+'b'+'c'+"")

the original question is like this.
public class test {
public static void main(String[] args){
int i = '1' + '2' + '3' + "";
System.out.println(i);
}
}
and this gives me an error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from String to int
then I changed the code like this:
public class test {
public static void main(String[] args){
int i = '1' + '2' + '3';
System.out.println(i);
}
}
the out put is 150.
but when I write my code like this:
public class test {
public static void main(String[] args){
System.out.println('a'+'b'+'c'+"");
}
}
the output become 294.
I wonder why.
The first one does not compile, because you concatenate a String at the end which cause the value to be a String which can't be converted directly to int.
The output of the second one is 150, because ASCII value for character 1,2,3 are 49,50,51 which return 150 when doing the addition.
The output of the last one is 294, because you are doing an addition of char values in the ASCII table (97+98+99)
You can verify the values here for a,b and c (or any other character).
Edit : To explain why the last one output the correct value instead of throwing an error, you first sum all the values as explained before, then convert it to a String adding "" to the sum of the ASCII values of the chars. However, the println method expect a String which is why it does not throw any error.
The first one would work if you would do Integer.parseInt('1' + '2' + '3' + "");
When you do this
int i = '1' + '2' + '3';
the JVM sums the ASCII codes of the given numbers. The result is 150.
When you add the empty String, you are trying to sum an int/char with a String. This is not possible. You can implicitly convert char to int and vice versa because they are primitive types. You cannot do this with String objects because they are not primitives but references. That's why you get an error.
When you do the println the primitive values are firstly summed and the automatically boxed into reference type so the sum is boxed into a Character object. The empty String is converted to a Character and then is added to the first one. So the result is a Character object that has an ASCII code 294. Then the toString method of the Character is called because that's what the println(Object) method does. And the result is 294
I hope this will help you to understand what is happening :)
The first is impossible because you can't convert String to int this way.
The second works because chars are kind of numbers, so adding chars is adding the numbers they really are. Char '1' is the number 49 (see ASCII table), so the sum is 49+50+51 which is 150.
The third works this way because + is a left parenthesized operator, which means that 'a'+'b'+'c'+"" should be read as (('a'+'b')+'c')+"". 'a' has ASCII code 97, so you have 294+"". Then Java knows that is should convert the value to a String to be able to catenate the two strings. At the end you have the the string 294. Modify your last code to the following System.out.println('a'+'b'+('c'+"")); and you will see that the result will be 195c.
You must note that System.out.println is a method that is used to convert values (of different types) to their String representation. This is always possible as every int can be converted to a String representation of it, but not the converse; not every String is a representation of an int (so Java will not let you do it so simply).
First: [int i = '1' + '2' + '3' + "";]
If you concat an empty string value, you convert it to a String object, and then String objects can't convert to int.
Second: [int i = '1' + '2' + '3';]
The binary arithmetic operations on char promote to int. It's equal to:
[int i = 49 + 50 + 51] - total: 150.
Third: [System.out.println('a'+'b'+'c'+"");]
At this case you convert 'a' + 'b' + 'c' (that is 294) to String (+"") and then print the result like a String value and that works ok.

string to char array, showing silly characters

It is a really simple question but I need an another eye to look at my code:
String strtr = "iNo:";
char[] queryNo = strtr.toCharArray();
System.out.println(queryNo + " =this is no");
and the output is:
[C#177b4d3 =this is no
What are these characters, do you have any idea?
That's how toString() is implemented for arrays.
The [C denotes that is a char array, 177b4d3 is its hashcode.
You may want to look at
System.out.println(Arrays.toString(queryNo) + " =this is no");
if you want to see your original String again, you need this:
System.out.println((new String(queryNo)) + " =this is no");
Arrays do not override toString(), it is inherited from Object.toString as
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
you are printing the object
queryno, as queryno is a character array of on dimension and java is an object oriented language which holds every thing in the form of classes it gives the class name [C to your array where [ denotes total dimension and C denotes character type of array, Rest is the hashcode of the object.
You are trying to print the array and that is the reason you get gibberish. Try using Arrays.toString(queryNo) and you will see what you expected.

Why does concatenated characters print a number?

I have the following class:
public class Go {
public static void main(String args[]) {
System.out.println("G" + "o");
System.out.println('G' + 'o');
}
}
And this is compile result;
Go
182
Why my output contain a number?
In the second case it adds the unicode codes of the two characters (G - 71 and o - 111) and prints the sum. This is because char is considered as a numeric type, so the + operator is the usual summation in this case.
+ operator with character constant 'G' + 'o' prints addition of charCode and string concatenation operator with "G" + "o" will prints Go.
The plus in Java adds two numbers, unless one of the summands is a String, in which case it does string concatenation.
In your second case, you don't have Strings (you have char, and their Unicode code points will be added).
System.out.println("G" + "o");
System.out.println('G' + 'o');
First one + is acted as a concat operater and concat the two strings. But in 2nd case it acts as an addition operator and adds the ASCII (or you cane say UNICODE) values of those two characters.
This previous SO question should shed some light on the subject, in your case you basically end up adding their ASCII values (71 for G) + (111 for o) = 182, you can check the values here).
You will have to use the String.valueOf(char c) to convert that character back to a string.
The "+" operator is defined for both int and String:
int + int = int
String + String = String
When adding char + char, the best match will be :
(char->int) + (char->int) = int
But ""+'a'+'b' will give you ab:
( (String) + (char->String) ) + (char->String) = String
+ is always use for sum(purpose of adding two numbers) if it's number except String and if it is String then use for concatenation purpose of two String.
and we know that char in java is always represent a numeric.
that's why in your case it actually computes the sum of two numbers as (71+111)=182 and not concatenation of characters as g+o=go
If you change one of them as String then it'll concatenate the two
such as System.out.println('G' + "o")
it will print Go as you expect.

Categories

Resources