Download presentation
Presentation is loading. Please wait.
Published byDouglas Robertson Modified over 6 years ago
1
Exercise 1- I/O Write a Java program to input a value for mile and convert it to kilogram. 1 mile = 1.6 kg. import java.util.Scanner; public class MileToKg { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter mile: "); double mile = Double.parseDouble(input.nextLine()); double kg = mile/1.6; System.out.print(mile + " mile = " + kg + " kg"); }
2
Exercise 2 - Condition Write a Java program that asks user to input the weight of a package and compute the shipping cost based on the following function: If the weight is more than 20kg, display a message that “the package cannot be shipped.”
3
Exercise 2 - Condition import java.util.Scanner;
public class ShippingCost { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter the weight of your package: "); double weight = Double.parseDouble(input.nextLine()); if (weight > 0 && weight <=2) System.out.println("Shipping cost = RM2.50"); else if (weight > 2 && weight <=4) System.out.println("Shipping cost = RM4.50"); else if (weight > 4 && weight <=10) System.out.println("Shipping cost = RM7.50"); else if (weight > 10 && weight <=20) System.out.println("Shipping cost = RM10.50"); else System.out.println("The package cannot be shipped"); }
4
Exercise 3 - Iteration Write a Java program to compute the factorial of a number input by the user. import java.util.Scanner; public class Factorial { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter an integer: "); int n = Integer.parseInt(input.nextLine()); System.out.print(n + "! = "); int factorial = 1; while (n > 1) { factorial = factorial * n; n--; } System.out.print(factorial);
5
Exercise 4 - Array Enter numbers: 1 2 3 2 1 6 3 4 5 3
Write a Java program that reads ten integers and store the numbers in an array. Then compute and display the number of even numbers and odd numbers Here is the sample run of the program: Enter numbers: The number of odd numbers: 6 The number of even numbers: 4 .
6
Exercise 4 - Array import java.util.Scanner; public class OddEven {
public static void main(String[] args) { Scanner input = new Scanner(System.in); int[] num = new int[10]; System.out.println("Enter 10 integers: "); for (int i=0; i<10; i++) num[i] = Integer.parseInt(input.nextLine()); int odd=0, even=0; for (int i=0; i<10; i++) { if (num[i]%2==0) even++; else odd++; } System.out.println("The number of odd numbers: "+odd); System.out.println("The number of even numbers: "+even);
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.