Storing the value of one object in to the other - java

I am trying the following code:-
HashMap<Integer,Integer[]> possibleSeq = new HashMap<Integer,Integer[] >();
possibleSeq.put(0,new Integer[]{1,4,5});
possibleSeq.put(1,new Integer[]{0,4,5,2,6});
Integer[] store = possibleSeq.get(0);
for(int i=0;i<store.length;i++)
{
System.out.print(store[i] + ' ');
}
Output is :-
333637
But since i am equating the value when key is 0 to the store variable,I intend to get 1 4 5 as an output.So i deduced Integer[] store = possibleSeq.get(0);this is not the proper way to store elements of possibleSeq.get(0) in store.So how should i do it??

Your problem is that you're adding char ' '(which is converted to int 32) to store[i] which is int.
Use double quotes instead.
System.out.print(store[i] + " ");

System.out.print(store[i] + ' ');
As you are printing (store[i] + ' '), ' ' is char here which concatenating with the integer value and prints, so it become (1+32) as ascii value of space() is 32. which is 33 and so on...
try this -
System.out.print((store[i]) + " ");
It works -
1 4 5

System.out.print(store[i] + ' ');// take a look at this store[0]=1
and char ' ' is 32
Then (1+ 32) you will get.
So change your code
System.out.print(store[i] + " ");

You are using single quotes instead of double quotes.
Use this System.out.print(store[i] + " ");

Related

Mixing of two strings giving undesired output

I was just experimenting with the fusion of the strings in Java (I don't know what we call them so I'm saying fusion)
int sum = 11+13;
int sum2 = 12+4;
So then I started to print them with different fusion of strings like:
System.out.println( "Answer is " + sum + sum2 ); //Answer is 2416
System.out.println( "Answer is " + sum + ' ' + sum2 ); //Answer is 24 16
System.out.println( "Answer is " + (sum+sum2) ); //Answer is 40
System.out.println( "Answer is " + (sum + ' ' + sum2) ); //Answer is 24 16
It worked fine with the 1st, 2nd and 3rd statements. But in the 4, it's output was
Answer is 72
But why is it coming? I thought the output should be
Answer is 24 16
as first we are outputting the string "Answer is " and then we are outputting this- (sum + ' ' + sum2) and as there is a string between the sum and sum 2, they shall become a string too. But instead it's giving the output 72.
Also, I'm using IntelliJ to run this programm if it will help.
One last thing, this works perfectly fine if I replace the ' ' with " ", but why? It works fine with the 2nd statement.
Because ' ' in (sum + ' ' + sum2) is considered as a character code which is 32.
int b = ' ';
System.out.println( "Answer is " + b ); //Answer is 32
So, 24 + 32 + 16 = 72
Because ' '(space)is char, not String, and char is used in operations with int, often using ascii code, the ascii code of ' '(space) is 32, so 24 + 32 + 16 = 72. When you use System.out.println( "Answer is "+ (sum +" "+ sum2) ), you will get the answer "Answer is 24 16"
In addition to the already provided answers: The difference here is that when the subexpression x + ' ' is evaluated in the second case the x is of type String, while in the fourth case it is of type int. So in the second case the + means string concatenation, while in the fourth it is addition.
Parantheses + ASCII code gives the 72.
Parantheses makes the integers sum up. You're assuming that output should be 24 16 but within paranthese the values are not strings. sum and sum2 are int. So, all the values are added. As explained by others, space holds a value of 32. This ensures, that the output is 72.
Note: If you want to get 24 16, you'd have to use String.valueOf().
System.out.println("Answer is " + (String.valueOf(sum) + ' ' + String.valueOf(sum2)) );
Anything enclosed inside '' is considered as a character literal. The character literal space is dec 32.
On the other hand statement inside () is evaluated as an addition operation with values considered as 24 + 32 + 16, hence you get an answer as 72.
Similarly (sum + '!' + sum2) would have produced 73.

Strange result when trying to add a char after an integer and then print the result

I'm trying to create a simple calculator voor Ohm's law.
So the idea is that you can fill in 2 variables and then it will calculate the third variable.
When I was creating this program, I found a little problem and I don't understand how it happens and unfortunately I'm not able to find the answer.
I tried to print a String where the complete calculation is shown. So the 2 variables the user filled in and the answer. After the variable for Ohm ('R' in this example) the correct symbol should be printed aswell.
As shown in the example below, the only way I can add the symbol after the variable is by first adding an empty string(""). Otherwise the unicode wil be added to the variable?!
I've made a quick example to show my problem:
public class Main {
public static void main(String[] args) {
float R = 2.54f;
float U = 4.00f;
float I = R / U;
char ohm = '\u2126';
System.out.println(R + "" + ohm + " (R) / " + U + "V (U) = " + I + "A (I)");
System.out.println(R + ohm + " (R) / " + U + "V (U) = " + I + "A (I)");
}
}
Result in console:
2.54Ω (R) / 4.0V (U) = 0.635A (I)
8488.54 (R) / 4.0V (U) = 0.635A (I)
As you can see, the second print doesn't show the Ohm symbol, but adds a value to the variable 'R'. Hopefully I've made my question clear enough.
Thanks in advance.
R + ohm performs a numeric addition of a float and a char (which is an integral type). Therefore you see a float result instead of the String concatenation you expect. The float result you see is 8486 + 2.54 (since 8486 is the decimal value of the hexadecimal number 2126).
In your first println statement you avoid that by concatenating a String ("") to the float, which results in a String. Then the Ohm char is concatenated to that String.
You can also begin with the empty String to get the desired output:
System.out.println("" + R + ohm + " (R) / " + U + "V (U) = " + I + "A (I)");

Why does the expression x+x not print the same result in the two places it appears? [duplicate]

This question already has answers here:
Java: sum of two integers being printed as concatenation of the two
(10 answers)
Closed 7 years ago.
Why does the expression x+x not print the same result in the two places it appears?
String s = args[0];
System.out.println("Hello "+s);
int x = 40;
System.out.println(x);
System.out.println(x+x);
System.out.println(s+" "+x+x);
The result of this code is when I execute in cmd java EG1 kaan
Hello kaan
40
80
kaan4040
why is the last result of the print displaying kaan4040 and not kaan80?
Because of automatic conversion to String.
On this line you "start printing" an integer, so adding another integer to it will again produce integer that is then converted to String and printed out:
System.out.println(x + x); // integer + integer
However on this line you "start printing" a String, so all other values you add to it are at first converted to String and then concatenated together:
System.out.println(s + " " + x + x); // String + String + integer + integer
If you want the two integers to be added together before the concatenation is done, you need to put brackets around it to give it a higher priority:
System.out.println(s + " " + (x + x)); // String + String + integer
In your last print statement, you are doing a string concatenation instead of an arithmetic addition.
Change System.out.println(s+" "+x+x) to System.out.println(s+" "+(x+x)).
Make changes System.out.println(s+" "+x+x); to System.out.println(s+" "+(x+x)); Because it need to add the value and then string concatenation
Because java does some work with your code. When you do System.out.println(x+x);, it sees x+x as an expression with two ints and evaluates it (which is 80). When you do ""+x+x, it sees 3 String, and thus evaluates this expression as a String concatenation.
(btw, by it, I mean javac, and "sees", I mean, well "reads")
Or change print code to System.out.println(x +x+" " +s );
You are performing concatenation instead of addition
Whenever you append anything to string then it will result to string only. You have appended x+x to " " which will append 40 after name. You can use System.out.println(s+" "+(x+x)).
On the last print statement:
System.out.println(s+" "+x+x);
s is a string and is concatenated with " ", from left to right the expression formed by concatenation with s and " ", is then concatenated with x and then ( s + " " + x ) is concatenated with x, yielding kaan4040.
If the + operator is used with:
2 Strings, concatenation occurs
1 String and 1 int, concatenation occurs
2 ints, arithmetic addition
Consider the following scenario:
System.out.println(x + x + " " + "hello");
In this example 80Kaan is printed as arithmetic addition occurs between x and x, then the resulting value (80) is concatenated with the space and hello.
Read from left to right.
int x = 40;
System.out.println(x);
System.out.println(x + x);
System.out.println("" + x + x);
40
80
4040
40 is int 40
80 is int 40 + int 40 (Maths)
4040 is String 40 concat String 40 (because add "" String)
String s = args[0];
System.out.println("Hello "+s);
int x = 40;
System.out.println(x); //1st statement
System.out.println(x+x); //2nd statement
System.out.println(s+" "+x+x); //3rd statement
The first statement simply converts x into String
The second satatement added the numbers because there aren't strings, the compiler thinks of plus sign as addition of two numbers.
the third one sees that there is a string so the compiler thinks like:
print the value of s, add space(" "), add the value of x (convert x into string), add the value of x (convert x into string ).
Hence, Kaan4040.
If you want to print 80, you can do it in two ways:
int sum = x+x;
System.out.println(s+" "+sum); //more readable code
or
System.out.println(s+" "+ (x+x) ); //may confuse you
the compiler will think of x+x as integers since it doesn't find any string inside the parenthesis. I prefer the first one though. :)
why is the last result of the print displaying kaan4040 and not kaan80?
This is because this is how String behaves when used with the + symbol. and it can mean differently when used in a println method.
It means String concatenation when you use it with a String
The 5 even though being an integer will be implicitly converted to String.
E.g:
System.out.println("Hello" + 5); //Output: Hello5
It become mathematical operation:plus when used within a pair of brackets because the brackets will be operated first (add first), then convert to String.
The 1st + is concatenation, and 2nd + is add (Refer to codes below).
E.g:
System.out.println("Hello" + (5+7)); //Output: Hello12
If any one of the '+' operator operand is string, then java internally create 'StringBuilder' and append those operands to that builder. for example:
String s = "a" + 3 + "c";
it's like
String s = new StringBuilder("a").append(3).append("c").toString(); //java internally do this

How should I deal with space character when using split

So apparently when I am using S.split(" ") and I have " " (space) in my code file, it gets ignored. I was wondering if there's a way to overcome that. What I had in mind and is written in the following code doesn't work however it works for every other character.
String codeArr[] =code.split("\\r?\\n");
int k=0;
while (k<codeArr.length-1)
{
String[] tmpCode=codeArr[k].split(" ");
if (tmpCode.length!=2)
HuffCodeToCh.put(tmpCode[0]," ");
else
HuffCodeToCh.put(tmpCode[1],tmpCode[0]);
k+=1;
}
My input is of the following type (in a file):
i 000
r 001
e 01
s 100
n 101
. 110000
" 110001
E 1100100
k 11001010
H 11001011
f 110011
t 1101
1110
a 111100
I want to save the character as well as its binary code in a hashMap as shown in the code. However the code I have written above doesn't save " " in the hashmap. I am not sure how to fix it.
try this:
codeArr[k].split(" (?=\\S)");
so that
x 100 -> {"x","100"}
100 -> {" ","100"}
11 -> {" ", "11"} (two spaces)
Use String.substring.
String c = codeArr[k].substring(0, 1);
String b = codeArr[k].substring(2);
Specifically, your whole loop is simply:
for (String line : code.split("\\r?\\n"))
HuffCodeToCh.put("" + line.charAt(0), line.substr(2));
On a largely unrelated note, your variable HuffCodeToCh does not follow Java naming conventions, which strongly suggest that initial capitals be reserved for types.

Reversing the order of a string

So I'm still shaky on how basic java works, and here is a method I wrote but don't fully understand how it works anyone care to explain?
It's supposed to take a value of s in and return it in its reverse order.
Edit: Mainly the for loop is what is confusing me.
So say I input "12345" I would want my output to be "54321"
Public string reverse(String s){
String r = "";
for(int i=0; i<s.length(); i++){
r = s.charAt(i) + r;
}
return r;
}
We do a for loop to the last index of String a , add tha carater of index i to the String s , add here is a concatenation :
Example
String z="hello";
String x="world";
==> x+z="world hello" #different to z+x ="hello world"
for your case :
String s="";
String a="1234";
s=a.charAt(0)+s ==> s= "1" + "" = "1" ( + : concatenation )
s=a.charAt(1)+s ==> s='2'+"1" = "21" ( + : concatenation )
s=a.charAt(2)+s ==> s='3'+"21" = "321" ( + : concatenation )
s=a.charAt(3)+s ==> s='3'+"321" = "4321" ( + : concatenation )
etc..
public String reverse(String s){
String r = ""; //this is the ouput , initialized to " "
for(int i=0; i<s.length(); i++){
r = s.charAt(i) + r; //add to String r , the caracter of index i
}
return r;
}
What this code does is the following
Create a new variable r="";
then looping for the string in input lenght it adds at the beginning of r the current character of the loop.
i=0) r="1"
i=1) r="21"
i=2) r="321"
i=3) r="4321"
i=4) r="54321"
When you enter the loop you are having empty string in r.
Now r=""
In 1st iteration, you are taking first character (i=0) and appending r to it.
r = "1" + "";
Now r=1
In 2nd iteration, you are taking second character (i=1) and appending r to it
r = "2" + "1";
Now r=21
You can trace execution on a paper like this, then you will easily understand what is happening.
What the method is doing is taking the each character from the string s and putting it at the front of the new string r. Renaming the variables may help illustrate this.
public String reverse(String s){
String alreadyReversed = "";
for(int i=0; i<s.length(); i++){
//perform the following until count i is as long as string s
char thisCharacterInTheString = s.charAt(i); // for i==0 returns first
// character in passed String
alreadyReversed = thisCharacterInTheString + alreadyReversed;
}
return alreadyReversed;
}
So in the first iteration of the for loop alreadyReversed equals 1 + itself (an empty string).
In the second iteration alreadyReversed equals 2 + itself (1).
Then 3 + itself (21).
Then 4 + 321.
Then 5 + 4321.
GO back to your problem statement (take an input string and produce an output string in reverse order). Then consider how you would do this (not how to write Java code to do this).
You would probably come up with two alternatives:
Starting at the back of the input string, get one character at a time and form a new string (thus reversing its order).
Starting at the front of the string, get a character. Then for each next character, put it in front of all the characters you have created so far.
Your pseudo code results might be like the following
Option 1
let l = the length of the input string
set the output string to ""
while l > 0
add the "lth" character of the input string to the output string
subtract 1 from l
Option 2 left as an exercise for the questioner.
Then you would consider how to write Java to handle your algorithm. You will find that there are several ways to get the "lth" character of a string. First, in Java a string of length l has characters in position 0 through l-1. You can use string.charAt(loc) or string.substring(loc,loc+1) to get the character at position loc

Categories