If you plan on continuing with programming after grade 11, you will probably want to make a document where you can write down useful and clever algorithms.
making a counter You'll need to do this at various places to count things
int counter = 0; counter++;
keeping a total This is just the basic part. You'll have to put it in the correct place
int total = 0; total += number;
Exchanging two variables here they are two ints called a and b
Sometimes one needs to do this, especially when sorting data. You can't just say a=b and b=a because both variables end up being the same number (b). You have to make a temporary variable to store one of the numbers so that it doesn't get overwritten.
int temp = a; a = b b = temp;
Checking range of inputThis assumes that we're using Scanner for input, but it works with other methods too.
//check to see if it's between 1 and 10
int num = sc.nextInt();
while (num < 1 || num > 10) {
System.out.println("num must be from 1 to 10");
num = sc.nextInt();
}
Getting a certain data type. This will prevent the Scanner from crashing the program if someone types in a word instead of a number
This is complicated enough, that it's probably worth making a whole class for things like this.
Call it Utility class (or something similar, but not "util") and add useful things to it.
/* Usage: In your main program, you can type: int x = Utility.getInt(); or add a message to be printed: int x = Utility.getInt("Enter your mark"); and double speed = Utility.getDouble(); */ import java.util.Scanner; public class Utility { static int getInt() { return getInt(""); } static int getInt(String s) { Scanner sc = new Scanner(System.in); if (s.length() == 0) s = "Please enter an integer: "; System.out.print(s); while(! sc.hasNextInt()){ System.out.println("Integer required"); System.out.print(s); sc.nextLine(); //cleans up crap } return sc.nextInt(); } static double getDouble() { return getDouble(""); } static double getDouble(String s) { Scanner sc = new Scanner(System.in); if (s.length() == 0) s = "Please enter a double: "; System.out.print(s); while(! sc.hasNextDouble()){ System.out.println("Double required"); System.out.print(s); sc.nextLine(); //cleans up crap } return sc.nextDouble(); } }