110 likes | 229 Views
Computer Programming. Lab(7). Exercise 1. (Decimal to hex) Write a program that prompts the user to enter an integer between 0 and 15 and displays its corresponding hex number. Here are some sample runs :. Source code:. import java.util.Scanner ; public class lab7_1 {
E N D
Computer Programming Lab(7)
Exercise 1 (Decimal to hex) Write a program that prompts the user to enter an integer between 0and 15and displays its corresponding hex number. Here are some sample runs:
Source code: importjava.util.Scanner; public class lab7_1 { public static void main(String args[]) { Scanner input = new Scanner(System.in); System.out.print("Enter a decimal value (0 to 15): "); intdecimal = input.nextInt(); if (decimal > 15 || decimal < 0) System.out.println("Invalid input"); else if (decimal < 10) System.out.println("The hex value is " + decimal); else System.out.println("The hex value is " + (char)('A' + decimal - 10)); } }
Exercise 2 (Financial: compare costs) Suppose you shop for rice in two different packages.You would like to write a program to compare the cost. The program prompts theuser to enter the weight and price of the each package and displays the one withthe better price. Here is a sample run:
Source code: importjava.util.Scanner; public class Lab7_2 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter weight and price for package 1: "); double weight1 = input.nextDouble(); double price1 = input.nextDouble(); System.out.print("Enter weight and price for package 2: "); double weight2 = input.nextDouble(); double price2 = input.nextDouble(); if(price1 * 1.0 / weight1 >= price2 * 1.0 / weight2) System.out.println("Package 1 has the best price."); else System.out.println("Package 2 has the best price."); } }
Exercise 3 (Find the Largest Number) The process of finding the largest value is used frequently in computer applications. Write a program that reads3integers from the console and print the largest integer between them. Here is a sample run:
Source code: Scanner input = new Scanner(System.in); System.out.print("Enter the first integer: "); intx = input.nextInt(); System.out.print("Enter the second integer: "); inty = input.nextInt(); System.out.print("Enter the third integer: "); intz = input.nextInt(); if( x > y && x > z ) System.out.println("The largest number between ["+x+","+y+","+z+"]is "+x); else if ( y > x && y > z ) System.out.println("The largest number between ["+x+","+y+","+z+"]is "+ y); else if ( z > x && z > y ) System.out.println("The largest number between ["+x+","+y+","+z+"]is "+ z); else System.out.println("Entered numbers are not distinct");