# 1 – Input and Output Answers

1) Use the \t escape character to print out a noughts and crosses grid, as shown below in fig. 1
System.out.println("|\to\t|\t \t|\tx\t|");
System.out.println("|\t \t|\tx\t|\to\t|");
System.out.println("|\to\t|\tx\t|\to\t|");


2) Prompt the user to enter their (name). Print out “Hello” (name) “I hope you’re well”

Scanner scan = new Scanner(System.in);
String name = scan.nextLine();
System.out.println("Hello " + name + ". I hope you're well.");


3) Use Math.sqrt() to print out the square root of 20

System.out.println(Math.sqrt(20));


4) Use Math.sqrt() to print out the square root of 20 to 2 decimal places

double root = Math.round(Math.sqrt(20)*100)/100d;
System.out.println(root);


5) Use Math.random() to print out a random integer between 5 and 10

System.out.println((int)(Math.random()*5)+5);


6) Use Math.pow() to print out 2 to the power of 8

System.out.println(Math.pow(2,8));


7) Prompt the user to enter a (number). Print out “The square root of ” (number) ” is ” (answer)

Scanner scan = new Scanner(System.in);
System.out.println("Emter a number");
double num = scan.nextDouble();
System.out.println("The square root of " + num + " is " + Math.sqrt(num));


or

Scanner scan = new Scanner(System.in);
System.out.println("Emter a number");
double num = scan.nextDouble();
System.out.format("The square root of %f is %f%n", num, Math.sqrt(num));


8) Prompt the user to enter two numbers. Print out the average of those numbers.

Scanner scan = new Scanner(System.in);
System.out.println("Emter a number");
double num1 = scan.nextDouble();
System.out.println("Enter another number");
double num2 = scan.nextDouble();
double average = (num1 + num2)/2;
System.out.println("The average of " + num1 + " and " + num2 + " is " + average);


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.

Scanner scan = new Scanner(System.in);
double weight = scan.nextDouble();
double height = scan.nextDouble();
double BMI = weight/(height*height);
System.out.println("Your BMI is " + BMI);


This site uses Akismet to reduce spam. Learn how your comment data is processed.