- Introduction
- Super Simple Formula
- Your First Program
- Variables, Methods and Parameters
- Variables in Programming and Algebra
-
Math and Comparison Operators - If Statement
- While and For Loops
- Loopy Thinking
-
Data Types - Booleans
- Logical Operators (and Booleans)
- Output and Printing
- Printing and Loops
-
Arrays - Arrays and Loops
- Array Loop Practice
-
What's Next? - Quick Reference
Quick Reference
Quickly lookup Java basics, and load code examples directly into editor.
int
), the method name (doStuff
), and the method's parameters (such as a
and b
). The method body follows, where you usually need to write code that returns a value at the end.
//method header: methodName(parameters)
static int doStuff(int a, int b){
//your code here - erase this comment and write your code!
return 1;
}
Syntax note: Every line of code in Java needs to end with a
;
or it will be considered part of the next line. Comments are marked with 2 backslashes //
and are ignored by the computer.%
operator returns the remainder after division.
int product = 4 * (1+2) / 2; //6.
int roughDivision = 8 / 3; //2
int remainder = 3 % 2; //1, the remainder of 3/2
booleans are used to store true/false values, such as the results of comparisons:
boolean check = false; //this will store result of comparison
int five = 5;
//the following are all true
check = (five == 5); //equals
check = (five != 3); //not equals
check = (five >= 5); //greater or equals
The logical operator AND &&
will return true if multiple conditions are all true, and OR ||
will return true if at least one condition is true.
//these pointless statements will both set check to true
check = (3>2 && 2>1); //AND
check = (3>2 || 1>3); //OR
if(condition){
//doSomething
}
The else statement will execute code if the condition was false. The while statement will repeatedly execute the same code while a condition is true.
public static void controlFlow(int number) {
//this if/else block will print out 1 statement for any number
if(number > 10){
System.out.println("big number");
}
else if(number > 5){
System.out.println("medium number");
}
else{
System.out.println("small number");
}
//this loop will print the numbers from 0 to 9
int i = 0;
while(i < 10){
System.out.println(i);
i = i + 1;
}
}
System.out.println("");
The above prints text and add a newline afterwards.
System.out.print
prints without a newline, but you can add in spaces " " to separate text.
System.out.println("hello"); //prints with newline
String word1 = "hello";
String word2 = "world";
System.out.print(word1 + " " + word2); //prints "hello world"
Arrays are used to store multiple items of one data type together. They are declared with the type they will hold and with brackets []
. This code creates an empty 5-cell array:
int[] ar1 = new int[5];
This shortcut creates an array with numbers 0 to 4:
int[] nums = {0,1,2,3,4};
You can use for-loop to print values of array:
for(int i=0; i < nums.length; i=i+1){
System.out.print(nums[i]+" ");
}
If Statement
Code is normally executed in order from top to bottom, but you can make it skip around with control-flow statements which execute code only when a condition is true.
If
The most basic control-flow statement is the if
statement. You can tell the computer to only run certain code when a condition is true. For example, you might want to give a bonus to a player who hits over 100 targets in a game:
if hits > 100 then
add 10 to score
In Java, an "if" statement has parentheses around the condition, followed by curly braces around the code:
if(condition){
//then do stuff here
}
Or, in the above example:
//...code before
if(hits > 100){
score = score + 10;
}
// continues with code after...
If then else
If you want some code to run when the condition is true, and other code to run when it is false, you can use an if-then-else statement by adding an else
after the if
.
if(hits > 100){
score = score + 10; //large bonus
}
else{
score = score +1; //small bonus
}
This can also be seen in flowchart form:
You can check many different conditions by combining if-else-then statements:
if(hits > 100){
score = score + 10;
}
else if( hits > 90){
score = score + 6 ;
}
else if(hits > 80){
score = score + 3;
}
else{
score = score +1;
}
//code continues
The computer will stop checking the remaining conditions once it 'meets' a true condition, since it only goes to else
when the if
condition is false. For example, if hits
is 92
, then score will increase by 6 and the code will then continue executing from //code continues
.
Challenge
You are working on the Collatz Conjecture, an unsolved problem in math.
You will be given one number a
as input. If a
is even, return half of a
(a / 2). If a
is odd, return 3 * a + 1.
For example, when given 5
return 16
, and when given 16
, return 8
.
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Comments
Kristin Sutton
Mar 19, 10:50 AMThis is really hard :/
Husnija Bećirin
Mar 28, 3:59 AMMeho the Wormcloack finds this easy
Marco
Jun 18, 3:54 AMThis is about the properties of int...
Stanley Mwangi
Jun 26, 4:40 PMCool problem, I like how you link it to a current problem that coding can be used to explore :D Keep up the good work guys! By the way, is / performing integer division?
Learneroo
Jun 26, 4:46 PM@Stanley, if both numbers are integers,
/
will lose the decimal place from the answer.Stanley Mwangi
Jun 26, 5:18 PMAh, I was a bit confused but now I realise that we only want integer outputs for the Collatz Conjecture anyway. Thanks for the help :D
Adhurim Esati
Jul 2, 11:35 AMpublic class Main {
I'm going to take a break, until I get a reply for this question.
This is what I tried doing here, btw the variable name "NrQift" is from my language(albanian) meaning "even nr".
So can someone help me out here ? I'm not trying to cheat, don't tell me the answer just help me out by explaining how do I do in the "if( How do I make the code know I want a even number as a condition for the code in the { } )
I also tried doing if(a % 2) but that didn't work either.
Tyvm
Adhurim Esati
Jul 2, 12:00 PMI figured it out already after giving a bit more thought on the "Hint" xD Ty anyway whoever was gonna reply :)
ArtTric
Aug 6, 7:15 PMPretty sure this should work...
if (a == a % 2) {
return a / 2;
}
else {
return (a * 3) + 1;
}
why not?
Gladys
Sep 7, 11:55 PM@ArtTric
That won't work because a%2 should equal 0 (meaning that there is no remainder and therefore the number is even) and not equal to a.
Ahmad
Jan 15, 8:43 AMSo simple...
int c=a%2; // take remainder of the input and save it
//in variable c.
Mitchell
Mar 20, 8:56 PMI've done some work on the Collatz Conjecture before, so I kinda knew the answer. This is simpler than what has been posted already:
if (a % 2 != 0) { // odd
return (a * 3) + 1; // a times 3 plus 1
} else { // even
return a / 2; // a divided by 2
}
Mitchell
Mar 20, 8:58 PM@mina the operation needs to be on the right side. Its just a programming rule. example :
if (x - 2 = 0) // error
if (x = 2) // correct
it wont work in this example but thats just the rule.
Spud
Apr 13, 12:39 PMWhy was I wrong?
if (a % 2 == 0) {
return a / 2;
}
else {
return (a * 3) + 1;
}
Tyler Bernstein
Apr 28, 11:40 AMthis is hard :/
Bernard Mitchell
May 14, 12:46 PMTook me a while but finally figured it out. One thing that kept tripping me up was =. I understand that the equal sign in Java is used to say that an expression is true right? When is it appropriate
to use the equal sign then. I kept trying to use it in my if statement , that's what was messing me up.
Learneroo
May 14, 1:07 PMSee Variables in Programming and Algebra for
=
vs.==
.Shivani Singh Atoliya
Jun 10, 3:00 PMThe solution is as straight-fwd as the problem, so apply simple maths and follow syntax.
thales
Jul 7, 7:12 AMI want to become a hacker, so i guess i have to learn all of this first :-)
Isaac Toth
Sep 21, 9:21 AMneeds more sauce
shubh800
Oct 21, 6:03 AMHow we are using doStuff method in main class ?
shubh800
Oct 21, 6:10 AMwhat is wrong in below mentioned code
package basicpgm;
import java.util.Scanner;
public class Main {
Poshy Data
Dec 18, 6:40 AMif ( (x & 1) == 0 ) { even... } else { odd... }
the low bit will always be set on an odd number.
Alok Chaudhary
Aug 18, 3:46 AMThis is so good I love this
Vivek
Nov 29, 9:33 AMimport java.util.Scanner;
public class Main {
} this is my code. The compiler is throwing a single error.
/usercode/Main.java:8: error: 'else' without 'if'
else{
^
1 error******* Cna somebody please help
Shandeep Kumar
Dec 23, 9:57 AMsheshadhree
Jun 5, 2:17 PMI have figured out:
import java.util.Scanner;
public class Main {
}
lucifer
Feb 12, 12:56 AMthis will do it
// this if/else block will give result for any number a
if (a%2>0){
return 3*a+1
}
else{
return a/2;
ALOK
Jul 16, 1:27 AMI do it.
Jolly
Aug 20, 8:25 PMya this is really confusing
Mike Grote
Mar 15, 10:51 AMthe only thing confusing about it is the use of the == vs the =. This concept is in most programming languages so if you program in other languages, this isn't confusing at all.
If (you == dont){
return str x = 'get used to it';
}