CH 5-6 Answers
CH 5-6 Answers
Question 1:
a) The Scanner class is used to take input from the user through the keyboard.
b) next() reads only one word (till space); nextLine() reads the entire line including
spaces.
c) 8.0, double
d) Use Math.ceil(x)
e)
89
15
Question 2:
a)
8.0
b) Output will be a random number between 1 to 10 (e.g., 6 – actual value may vary)
c)
7
7.0
8.0
d)
Java1020
e)
5
Question 3:
a)
import java.util.Scanner;
public class UserInfo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter name: ");
String name = sc.nextLine();
System.out.print("Enter age: ");
int age = sc.nextInt();
System.out.print("Enter marks (%): ");
double marks = sc.nextDouble();
System.out.println("Name: " + name + ", Age: " + age + ", Marks: " + marks + "%");
}
}
b)
import java.util.Scanner;
public class MathOps {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int sum = a + b;
int diff = a - b;
int max = Math.max(a, b);
System.out.println("Sum: " + sum);
System.out.println("Difference: " + diff);
System.out.println("Square Root of max: " + Math.sqrt(max));
}
}
c)
Question 4:
a)
Corrected:
b) It skips the next line. Fix it using sc.nextLine(); to consume leftover newline.
c)
d)
Math.ceil(5.2);
e)
import java.util.Scanner;
import java.lang.Math;
Question 5:
a)
import java.util.Scanner;
public class TempConverter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double c = sc.nextDouble();
double f = (c * 9/5) + 32;
System.out.println("Temperature in Fahrenheit: " + f);
}
}
b)
import java.util.Scanner;
public class NumberCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
if(num > 0)
System.out.println("Positive");
else if(num < 0)
System.out.println("Negative");
else
System.out.println("Zero");
System.out.println("Absolute value: " + Math.abs(num));
}
}
Question 6:
import java.util.Scanner;
public class ThreeNumberStats {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int max = Math.max(a, Math.max(b, c));
int min = Math.min(a, Math.min(b, c));
double avg = (a + b + c) / 3.0;
long roundedAvg = Math.round(avg);
System.out.println("Largest: " + max);
System.out.println("Smallest: " + min);
System.out.println("Average: " + avg);
System.out.println("Rounded Average: " + roundedAvg);
}
}