Java Notes

Hey Coders!

I said I would upload the java code we worked on Saturday, so here it is. Remember that the file name needs to be the same as the class name (So make sure to save this in Test.java!)

import java.util.Scanner;
 
public class Test
{
public static void main(String[] args)
{
int age;
float favouriteNumber;
String name;
 
//In class we used i = i + 1, i++ is the same thing!
for (int i = 0; i < 10; i++)
{
System.out.println("Hello World!");
}
 
//Scanner is a program built into java that lets you get input from the user
//through the keyboard.
Scanner scanner = new Scanner(System.in);
 
System.out.print("What is your age? ");
age = scanner.nextInt();
System.out.print("\nWhat is your favourite number? ");
favouriteNumber = scanner.nextFloat();
System.out.print("\nWhat is your name? ");
name = scanner.next();
 
//Finally we close the scanner. If we try to use it after we close it the program will crash!
scanner.close();
 
System.out.println("Your name is " + name + ", your age is " + age + " and your favourite number is " + favouriteNumber + "!");
/*Is the exact same thing as we had on screen:
System.out.println("Your name is "
+ name
+ ", your age is "
+ age
+ " and your favorite number is "
+ favouriteNumber
+ "!");*/
 
//Remember, the "//" means it's a comment and is ignored when the code is compiled.
/* This is a comment too but can go on for
more than one line! */
}
}

In 3 weeks we will be looking at how to make functions in java, and then we will be ready to start robocode!