• Post Reply Bookmark Topic Watch Topic
  • New Topic

Array problem.  RSS feed

 
Shiva Mohan
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have been struggling in this program for 2 days.I am new to programming.
please help me.


public static void operation1 (String[] dbcolumn1){

int s=Integer.parseInt( dbcolumn1[0]);
int s1=Integer.parseInt(dbcolumn1[2]);


if (dbcolumn1[1].equals("+")) {
dbcolumn1[2]=dbcolumn1[0] + dbcolumn1[2];
System.out.println(dbcolumn1[2]);

}
else if (dbcolumn1[1].equals("*")) {
dbcolumn1[2]= dbcolumn1[0] * dbcolumn1[2]; //1
}
else if (dbcolumn[1].equals("-")){
dbcolumn1[2]= dbcolumn1[0] * dbcolumn1[2]; //2
}
else if (dbcolumn1[1].equals("/")) {
dbcolumn1[2]= dbcolumn1[0] * dbcolumn1[2]; //3
}
}

Question 1)

In the above method,the display line
System.out.println(dbcolumn1[2]);
should not give 1+2 total 3.why?

Question 2)

lines 1,2,3 showng these operators should not apply to String

Please help me to find out what i am doing wrong?
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Java, the + operator is overloaded to handle String concatenation as well as numeric arithmetic.

Since dbcolumn1 is a String array, using the + operator on elements of dbcolumn1 results in concatenated Strings.

The other operators here (*, -, and /) are not overloaded to handle Strings, which is why you are getting the errors.

In general, if you want to perform numeric computations on these Strings, you will need to first parse them as ints (or whatever) and perform the operations on these.
 
Shiva Mohan
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Could you please show me an example of parsing related to the above program
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Shiva Mohan:
Could you please show me an example of parsing related to the above program

The first 2 lines in your above method should work just fine...

int s = Integer.parseInt(dbcolumn1[0]);
int s1 = Integer.parseInt(dbcolumn1[2]);

Now just perform your arithmetic on s and s1.
 
Shiva Mohan
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.I Got it.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!