1 Input and Output (Level 1)

Sample Code

 Escape Characters

Escape Sequence Character
\n newline
\t tab
\b backspace
\” double quote
\’ single quote
\\ backslash
\uDDDD Unicode character
public class uni
{
    public static void main (String args [])
    {
        System.out.println("\u0041");
    }
}

Simple Scanner

import java.util.Scanner;
public class Simpscan
{
    public static void main (String args [])
    {
        System.out.println("Enter your name");
        Scanner scan = new Scanner(System.in);
        String s = scan.next();
        System.out.println("Hello " + s);
    }
}

System.out.format

double pi = 3.1415;
System.out.format("Pi is %f to 4 d.p.%n", pi);

#+RESULTS

Pi is 3.141500 to 4 d.p.

Exercise

  1. Use the \t escape character to print out a noughts and crosses grid, as shown below in fig. 1
  2. Prompt the user to enter their (name). Print out “Hello” (name) “I hope you’re well”
  3. Use Math.sqrt() to print out the square root of 20
  4. Use Math.sqrt() to print out the square root of 20 to 2 decimal places
  5. Use Math.random() to print out a random integer between 5 and 10
  6. Use Math.pow() to print out 2 to the power of 8
  7. Prompt the user to enter a (number). Print out “The square root of ” (number) ” is ” (answer)
  8. Prompt the user to enter two numbers. Print out the average of those numbers.
  9. To work out your BMI, divide your weight in kilograms by your height in metres squared. In other words BMI = w / h*h. Write a program that prompts the user to input their weight and height, and then outputs their BMI.
Table 1: fig. 1
o x
x o
o x o

Leave a Comment