How to display an array of integers in a JTextArea? - java

for (int j =0; j < marks.size(); j++) {
analyzeTextArea.setText(j + marks.get(j));
}
The above code gives me the following error:
required: java.lang.String found: int

I guess marks.get(j) give you an Integer. So when you do j + marks.get(j) you add the value of marks.get(j) to the value of j.
So you end with an Integer as result of j + marks.get(j). But setText expect a String.
You have several possibilities now depending on you needs.
analyzeTextArea.setText(Integer.toString(j + marks.get(j)));
This case still make the addition then convert it to String in order to respect setText parameter type.
With this :
analyzeTextArea.setText("" + (j + marks.get(j)));
"" tells that the parameter will be a String and then you will concatenate j and marks.get(j). So, for example, for the first loop you will have something that start with 0
Now using setText in a loop don't really make sense because only the last value set in the loop will be used you probably should use JTextArea#append(String).

You need to do something like this:
analyzeTextArea.setText("" + (j + marks.get(j)));

analyzeTextArea.setText(Integer.toString(j + marks.get(j)));

Try this,
for (int j =0; j < marks.size(); j++) {
analyzeTextArea.setText(j + marks.get(j)+"");
}

That should work but instead of .setText(), you should use .append(). because .setText() deletes the previous contents and writes it. but .append() just adds on information

Related

Editing Unicode within a String

I wanted to have a List with Unicode Strings, but I wondered if I could use a for loop instead of adding 9 variables by hand. I tried the following code, but it didn't work.
List<String> reactions = new ArrayList<>();
for (int i = 1; i < 10; i++) {
reactions.add("\u003" + i + "\u20E3");
}
My IDEA gives me an 'illegal unicode escape' error.
Is there an other way to accomplish this?
The easiest way to convert a number to a character within a string is probably using a Formatter, via String.format:
List<String> reactions = new ArrayList<>();
for (int i = 1; i < 10; i++) {
reactions.add(String.format("%c\u20e3", 0x0030 + i));
}
Assuming you want to display the character \u003i, with ifrom 1 to 9, and \u20E3, remember a character is like a number and can be used in mathematical operation.
get the character \u0030: '\u0030'
add i : '\u0030' + i
concatenate the new character with the other one (as a string)
Then print the result:
System.out.println((char)('\u0030' + i) + "\u20E3");

Error in swapping characters in stringbuffer object

i am trying to sort a string in the alphabetical order, however i am facing an error in the line :
sb.charAt(j)=sb.charAt(j+1);
where the compiler shows an error as expected variable; found value
the rest of the code is as follows :
import java.util.Scanner;
class a
{
public static void main(String[] agrs)
{
Scanner sc = new Scanner(System.in);
String s = sc.next();
StringBuffer sb = new StringBuffer();
sb.append(s);
for(int i = 0; i< s.length(); i++)
{
for(int j = 0; j<s.length(); j++)
{
if(s.charAt(j)>s.charAt(j+1)){
char temp = s.charAt(j);
sb.charAt(j)=sb.charAt(j+1);
sb.charAt(j+1)=temp;
}
}
}}}
kindly help me out as i'm a beginner and i cannot figure out why this issue is occurring , thank you .
This looks like a homework assignment where the goal is to sort the characters of a text being entered, so if you enter gfedbca the result should be abcdefg.
You already got a comment telling you what the problem is: StringBuffer#charAt() is not returning a reference to StringBuffer's internal array that you can change the value of. Dependent on the actual assignment you can call StringBuffers setCharAt method or you can go another approach by converting the text to sort to a char array and do the sorting in there. There are actually helper-classes in the JVM, that do that for you, have a look e.g. at the class java.util.Arrays
As already answered by many, the issue is in charAt(index) you are using, as this returns the character at the given index rather than setting a char at the index position.
My answer is to divert your approach of sorting. For simpler solutions, where smaller data sets (like your problem) are used, you should use the predefined sorting algorithms, like Insertion Sort
You may get help for the algo from here: http://www.geeksforgeeks.org/insertion-sort/
StringBuffer's charAt returns just the value of the char at the index, if you want to swap two chars you need to use setter for that, so you possible want to do somtehing like:
for(int j = 0; j < s.length() - 1; j++) {
if(s.charAt(j) > s.charAt(j + 1)) {
char temp = s.charAt(j);
sb.setCharAt(j, sb.charAt(j + 1));
sb.setCharAt(j + 1, temp);
}
}
This method can only return values and can not set values, I guess you might want to use this method:
setCharAt()
It can meet your requirement

Java: Difference between +--i and +++i

Last day while programming, I mistakenly wrote something like this-
int i = 2;
int j = 3;
int a = i+++j;
And it did not shoot any error and I got-
a = 5
After detecting this coding error I was curious. So, I started playing with it. When I changed it a little-
int a = i+ ++j;
I got-
a = 6
With this-
int a = i+ + +j;
and this-
int a = i++ +j;
I again got-
a = 5
Similar situation was experienced here.
But here comes the weird part. There is no difference between a = i+--j & a = i+ --j. Both gives-
a = 4
Why is that? I completely understand what exactly is happening here. The thing I do not understand is- 'WHY?'. + and - are both operators, then why there is a difference?
For clarity, I wish to share another odd experience. This code works perfectly-
int i=0;
System.out.println("value: "+--i);
And outputs-
value: -1
But this-
System.out.println("value: "+++i);
Gives following error-
error: unexpected type
As #Bunti pointed out, your answer is in the Operator Precedence.
When you do,
int a = i+++j;
It's evaluated as int a = (i++) + j since Postfix has the highest precedence.
Now you know why you get a = 5 there. Print i along with a and you will see it's incremented.
Similarly, when you do System.out.println("value: "+++i);, it's evaluated to System.out.println(("value: "++) + i);
But postfix operations are not applicable to String. Hence the syntax error.
But when you do, System.out.println("value: "+--i);, this is evaluated to System.out.println("value: "+ (--i));. Hence it works just fine.
Operator precedence is only half of the answer, since the first thing to clarify is what the operators in your code are.
Basically i+++j could be interpreted as i ++ + j, as i + ++ j or as i + + + j.
However according to the lexical rules of Java (https://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.2) the interpretation is the same as if the expression was written as i ++ + j.
According to the operator precedence this is evaluated is (i++) + j, so that in int a = i++ + j; a is 5 (and i is 3!).
For i+--j the tokens are i + -- j (since the is no operator +-), which is according to operator precedence i + (--j), so that in int a = i + --j; a is 4 (and j is now 2).
Now comes the fun part:
What is int a = i + + + j;? This is the same as int a = i + (+(+j)); (+j being the unary plus operation on j), so this gives again 5 (but i is still 2 and j is still 3, which is different from the case i++ + j!)
And what is int a = i + - - j;? This is the same as int a = i + (-(-j)); (-j being the unary minus operation on j) which also gives 5 (and also does not modify i or j).
What is int a = i++++j;? This is not a valid Java expression (it will not compile), since this is equivalent to (i++) ++ j and since i++ cannot be converted to a variable this is illegal (https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.14.2) and then there is this dangling j too.
Adding more + without adding spaces does not make it legal, while i++ + ++j is perfectly legal...
Similarly, "SomeString"+++i is illegal, since this is read as ("SomeString"++)+i and you can't increment a String literal (and also not a String variable).
"SomeString"+--i is valid, since this is read as "SomeString"+(--i), which appends the result of --i to "SomeString".
Many of them have written answers for this. I would like to put it in different words.
i++ is post fix.
In post fix operation, value is incremented after the value is extracted.
Thus in case of i+++j, we have original value of i when expression is evaluated, and i is incremented after the evaluation is completed.
In case of ++j since its prefix value is incremented before evaluation.
This i+++j is equal to (i++)+j and i+ ++j is equivalent to i + (++j).
Hope this adds this helps adding to your understanding.
Hope this answers the behavior of arithmetic operation-
int i = 2;
int j = 3;
int a = i+++j;
a=5 as there is no space between the + symbol. Even if you put any more + symbols in between, the answer will remain the same. To explain its working, it is similar to any basic calculator we use, if i input a number and type + for any number of times, the second input when received will still give the sum of the 2 input-ed numbers. This is because the compiler is initializing the addition operation between the 2 numbers.
int a = i+ ++j;
Here in this case, you are adding the i to the incremented value of j. So it is like u are looking for an operation of 2+ ++3, which is 2+4 and hence the answer 6. the ++ operator is defined as an increment in the JRE.
int a = i+ + +j;
Here it behaves same as the 1st case as +j or i+ are not increment operators defined by JRE.
int a = i+--j;
In this interesting case, we are using 2 diff arithmetic operators i.e. + and --. As -- is defined, the decrement of j value happens and the change value of j is added to i.
int a = i+ --j;
As in above, since + and - are diff operations. the space between them or not doesn't matter.
int i=0;
System.out.println("value: "+--i);
In this case, we are printing a string and using +--i; so JRE treats it as printing out Value: decrement of i. As known in print statement, + is used to make system print multiple value at a time.
System.out.println("value: "+++i);
coming to this, the + in print function is defined to provide a way to print several variable that are separated by a + symbol and hence the conjunction of +++ is not defined for print function and hence gives an error.
May be the i+++j just is i+j, but the i+ ++j is i + ++j, there ++j change's , 'j=4'. So i[2] + j[4] = 6.
Java May not recognize three +++.

java.io.PrintStream display

I'm working on a java program using arrays and loops to create a table, however when the values print they are followed by "java.io.PrintStream#1909752" repeating over and over a number of times
The chunk of code causing the error is as follows, more specifically the "row +=" sections. Any help for how to get rid of the repeated part at the end would be appreciated.
for ( int i = starting; i <= ending; i+= 1){
row += System.out.format("%6d" + ": ", i);
for ( int j = 0; j <= 11; j+=1){
double answer = i*octaveArray[j];
row += System.out.format("%.0f ", answer );
}
System.out.printf(row);
System.out.println("");
}
From the documentation of PrintStream#format():
Writes a formatted string to this output stream using the specified format string and arguments.
That means that PrintStream#format() will write the values to the output stream but you then append its toString representation which looks like java.io.PrintStream#1909752 to the row variable which you then print out to the same output stream.
You should use String.format() instead if you wish to append the formatted result to a String variable.

convert object that holds a double to a string and then back to double

I have a two Dimensional Object array (Object[][] data) that holds pairs of products-prices.
I try to pass these values to a Map with the following way.
private String myPairs = "";
private String[] l, m;
for (int i=0; i<data.length; i++){
myPairs += (String)data[i][0] + ":" + String.valueOf(data[i][1]) + ",";
}
Map<String, Double> pairs = new java.util.HashMap<>();
l = myPairs.split(",");
for (int i=0; i<l.length; i++){
m = l[i].split(":");
pairs.put((String)m[0], Double.parseDouble((String)m[1]));
}
I get a java.lang.ArrayIndexOutOfBoundsException. What's the wrong I have done?
Try
for (int i=0; i<l.length-1; i++){
m = l[i].split(":");
pairs.put((String)m[0], Double.parseDouble((String)m[1]));
}
You problem is here:
pairs.put((String)m[0], Double.parseDouble((String)m[1]));
The first for loop creates a string that ends with a ,. For example "foo:0.1,bar:0.2,".
Then, you split by ,. So, the above example will return ["foo:0.1"; "bar:0.2"; ""]. Note the empty string value, due to the last , of the string.
Finally, for each value, you split by :. It works for the first two values (i.e. ["foo"; "0.1"] and ["bar"; "0.2"]), but the last one will be a 1-value array, containing an empty string: [""].
When trying to access the second value of the array (i.e. the index 1 since arrays are 0-based indexed), the ArrayIndexOutOfBoundsException get thrown.
Several solutions:
In the first loop, put a condition to add the , or not:
myPairs += (i == 0 ? "" : ",") + (String)data[i][0] + ":" + String.valueOf(data[i][1]);
OR Just after your first loop, remove the last char of the string:
myPairs = myPairs.substring(0, myPairs.length() - 1);
OR In the second loop, don't go until the last value, but only until the n-1 one:
for (int i=0; i<l.length - 1; i++)
OR even better, only if you don't need the string representation you're building in the first loop, replace all your code by:
for (int i=0; i<data.length; i++) {
pairs.put((String)data[i][0], Double.parseDouble((String)data[i][1]));
}
When the first for-loop ends, you have all the pairs separated with ',' and an extra ',' in the end. So, l.length is the number of pairs plus one. Though, this shouldn't produce an error so far.
The problem is that when you split every pair on ':', the last element of l is equal to a blank string.
So the splitting produces an 1-element-array, containing a blank string. The error occures because you ask for m[1].
Try not adding the ',' after the last element of the pairs, and the problem should be solved.
I hope this helps :)
The last element in the split of ,s is empty (because you say + "," on the last iteration of the first loop), so skip the last element in the second loop.
for (int i = 0; i < l.length-1; i++)
{
m = l[i].split(":");
pairs.put((String)m[0], Double.parseDouble((String)m[1]));
}
Also note that if the supplied strings contains :s or ,s, your algorithm would probably throw an exception too.
Note - A way better way (and to avoid the above) would just be to do it in the first loop, something like:
for (int i = 0; i < data.length; i++)
{
pairs.put((String)data[i][0], Double.parseDouble((String)data[i][1]));
}

Categories