• Post Reply Bookmark Topic Watch Topic
  • New Topic

Compliation error when using 'or' operator on learning website “Learneroo" (Java)  RSS feed

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My Java challenge on this codecademy style learning website 'Learneroo' is:

"You will be given an array ar with at least 3 elements. Find the sum of the following 3 elements in an ar:

The 2nd
The 2nd-to-last
The middle element. If ar has an even number of elements, the middle element is the last element in the 1st half.
If an element belongs to more than one category, it should only be counted once. For example, when given {1,2,3,4}, you should print 5, the sum of 2 and 3. (2 should not be double-counted even though its both the 2nd and middle element.)

Print each sum on its own line."

My attempt embedded inside this code:



The error code is:
/usercode/Main.java:4: error: cannot find symbol
sum = ar[1] + ar[ar.length/2] + ar[ar.length-2];
^
symbol: variable sum
location: class Main
/usercode/Main.java:5: error: bad operand types for binary operator '||'
if (ar[ar.length/2]==(ar[1]||ar[ar.length-2])){
^
first type: int
second type: int
/usercode/Main.java:6: error: cannot find symbol
sum = sum - ar[ar.length/2];
^
symbol: variable sum
location: class Main
/usercode/Main.java:6: error: cannot find symbol
sum = sum - ar[ar.length/2];
^
symbol: variable sum
location: class Main
/usercode/Main.java:9: error: cannot find symbol
System.out.println sum;
^
symbol: class out
location: class System
5 errors

Any help would be much appreciated!

Josh
 
Author and ninkuma
Marshal
Posts: 66307
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Where in your code is sum declared?
 
Saloon Keeper
Posts: 3330
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Logical OR (||) needs a boolean expression on either side of the ||, which is not what you have.
 
Bartender
Posts: 1840
10
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Unfortunately, you cannot always translate natural language directly into program code all the time.

So if I say "If x is 1 or 2" (meaning x has one of those two values) that doesn't translate into "if (x == (1 || 2))"

The "or" statement in programming as Carey pointed out requires boolean(true/false) expressions.
So natural language into computer language, you first have to modify the statement into: "If x is 1 or x is 2".
and THEN the computer might understand you.

Having said that, What should be the answer from input {2,2,2,2,2,2} ?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!