public class ArrayIntro
{
public static void main(String[] args)
{
int[] a;
a=new int[10];
Scanner sc =new Scanner(System.in);
for(int i=0;i<10;i++)
{
a[i]=sc.nextInt();
}
for(int e:a)
{
System.out.print(e+' ');
}
}
}
Input:1 2 3 4 5 6 7 8 9 10
Output:33343536373839404142
Its mean it added 32 to each number
Just try with below code.
As you are printing sout inside for loop, it's printing sum of number and Space( ' '). And space have ASCII value of 32, so you are able to see every element with added value of 32.
For ASCII Or Unicode you can refer this link, it will help you.
Simply you put something like this System.out.print(new Integer(' '));, it will print 32.
If you want to add space only then go with double quote.
System.out.print(e+" ");.
Single quote consider as character and charater added with Integer will summing up with their ASCII code.
public static void main(String[] args)
{
int[] a;
a=new int[10];
Scanner sc =new Scanner(System.in);
for(int i=0;i<10;i++)
{
a[i]=sc.nextInt();
}
for(int e:a)
{
System.out.print(e+" ");
}
}
To put it simply, ' ' is a character in ASCII and the value of it is 32. So, as far as I know, you might want it the just print directly so you can just replace ' ' with " ". Always remember that single quotes are for characters and double quotes are for strings.
For your answer you can just do this:System.out.print(e+" ");
Instead of this: System.out.print(e+' ');
In short, to fix your program, you need to use " " (with double quotes) instead of ' '.
The issue is that the + operator has two different meanings in Java.
If either of the operands is a String, then + means "concatenate these two operands together". If the other operand is not a String, then it will have to be converted somehow, and there are some rules around how to do this.
If neither operand is a String, then + means "add these two operands together" - that is, they are treated as numbers. They can be added as double values, float values, long values or int values, depending on the data types. But if they are short, byte or char, they will be treated as int. This is called binary numeric promotion, and is explained in detail in the Java Language Specification.
Now in Java, single quotes are used to delimit a char literal. So when you write e + ' ', you're adding an int to a char. This is addition - the char is treated as an int, and the operands are added as numbers. The number corresponding to is 32, since that's the numeric value in the character encoding that Java uses, which is something like UTF-16. Contrary to some other answers on this page, it's not ASCII.
Double quotes are used to delimit a String literal. So if you write e + " ", the operands are an int and a String. That means you're not adding any more, but concatenating. The int is converted to a String first, then concatenated to " ", which will give you the result you're expecting.
Related
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()
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.
Got the error "Unclosed Character Literal" , using BlueJ, when writing:
class abc
{
public static void main(String args[])
{
String y;
y = 'hello';
System.out.println(y);
}
}
But I can't figure out what is wrong.
Any idea?
Thanks.
In Java, single quotes can only take one character, with escape if necessary. You need to use full quotation marks as follows for strings:
y = "hello";
You also used
System.out.println(g);
which I assume should be
System.out.println(y);
Note: When making char values (you'll likely use them later) you need single quotes. For example:
char foo='m';
Java uses double quotes for "String" and single quotes for 'C'haracters.
I'd like to give a small addition to the existing answers.
You get the same "Unclosed Character Literal error", if you give value to a char with incorrect unicode form.
Like when you write:
char HI = '\3072';
You have to use the correct form which is:
char HI = '\u3072';
'' encloses single char, while "" encloses a String.
Change
y = 'hello';
-->
y = "hello";
String y = "hello";
would work (note the double quotes).
char y = 'h';
this will work for chars (note the single quotes)
but the type is the key: '' (single quotes) for one char, "" (double quotes) for string.
There are 8 primitive datatypes in Java.
char is one of them. When compiler sees a char datatype is defined. It allocates 1 Bytes of memory from JVM heap and expects a value after = symbol with two conditions.
value enclosed inside ' (single quotes).
value to be single character long. It can be either a single character or valid code corresponding single character, which you can't type using English Keyboard.
In the same way, a datatype of String type should be enclosed with "(double quotes) and can have any length characters sequence.
In the given example you have mixed concepts of both char and String datatype. the compiler clearly saying:
Unclosed Character Literal
Means, you started with ' single quote, so compiler just expects a single character after opening ' and then a closing '. Hence, the character literal is considered unclosed and you see the error.
So, either you use char data type and ' single quotes to enclose single character.
Or use String datatype and " double quotes to enclose any length of character sequence.
So, correct way is:
String y = "hello";
System.out.println(y);
Use double quotes symbol as I mention below
Your y data type is String, and it should double quotes symbol
class abc
{
public static void main(String args[])
{
String y;
y = "hello";
System.out.println(y);
}
}
Character only takes one value dude! like:
char y = 'h';
and maybe you typed like char y = 'hello'; or smthg. good luck. for the question asked above the answer is pretty simple u have to use DOUBLE QUOTES to give a string value. easy enough;)
First time posting so please inform me of how to improve.
I'm working on a program to convert infix notation to postfix and then evaluate. My conversion to postfix went well, but I'm having some trouble with my evaluation. In the code below, when I try to convert the operands into a double variable 'number' they don't maintain their value (see runtime output below). Here is part of the method in question (the print statements are for debugging only).
public boolean evaluatePostfix(StringBuffer postfix)
{
Stack <Double> operand = new Stack <Double>();//stack to hold operand values
double answer = 0; //variable to hold result of expression
boolean error = false; //tests for input error
int pos = 0; //temp veraible stores position in postfix expression
double number = 0; //temp variable to convert char to double. also stores that value for reference
double val1 = 0; //first value for operations
double val2 = 0; //second value for operations
double val3 = 0; //answer for val1 and val2
while (!error && pos < postfix.length())
{
System.out.println(postfix.charAt(pos));
if (postfix.charAt(pos) == ' ')
; //do nothing
else if (Character.isDigit(postfix.charAt(pos)))
{
number = Double.parseDouble(postfix.substring(pos));
System.out.printf ("number = %f", number);
operand.push(number);
}
else
{
val1 = operand.pop();
val2 = operand.pop();
System.out.printf ("val1: %f\tval2: %f\n", val1, val2);
---At runtime--- 1
number = 49.000000
8
number = 56.000000
+
val1: 56.000000
val2: 49.000000
val3 = 105.000000
105.0
You are taking the ASCII value of each character e.g. '1' => 49 and pushing it on to the stack.
Most likely what you want is to use a Scanner to read numbers converted from the text you input.
Replace:
number = postfix.charAt(pos);
with:
number = Double.parseDouble(Character.toString(postfix.charAt(pos)));
The Double.parseDouble method converts the string in double:
Returns a new double initialized to the value represented by the
specified String, as performed by the valueOf method of class Double.
(from Javadoc)
If you split the String with postfix.toString.split(" ") and then iterate on the string[] you will be able to parse also double values (like "8.4567"):
String[] sa = postfix.toString().split(" ");
for (String string : sa) {
.... omissis ...
otherwise your code will be correct only parsing single digit integer values.
Parsing an expression may not be a trivial task. In more complex cases using a parser generator is the only reasonable approach.
In your case, you might do without one:
What are your 'tokens'?
How do you detect the start and end of each token?
Once you have your tokens extracted from the input, what do you do with each of them?
Your tokens appear to be (decimal) numbers and arithmetic operators. - How can you determine the start and end of each? Whitespaces " " between them may make a sufficient delimiter.
Then you can cleanly parse your tokens one at a time: Use Double.parseDouble(...) to parse the numerical tokens and process the operators accordingly.
You may want to have a look at Java's Tokenizer for support in extracting the tokens from the input.
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.