Write an algorithm and a program that prompts the user to enter the weight of a
ID: 3882194 • Letter: W
Question
Write an algorithm and a program that prompts the user to enter the weight of a person in grams and finds the weight in kilograms and grams. One kilogram is 1000 grams. Sample input/output: Enter the weight in grams: 5370 There are 5 kilograms and 370 grams in 5370 grams. Exercise #2: Tons and Kilograms in Grams Write a program that reads a three-digits integer and flip it to form a new integer. Sample input/output: Enter a three digits integer: 371 The flip of 371 is 173 Extra Practice: Tons and Kilograms in Grams Write an algorithm and a program that prompts the user to enter the weight of an object in grams and finds the weight in tons, kilograms and grams. One metric ton is 1000 kilograms.Explanation / Answer
EX#1
Algorithm:
1. read the total no of grams entered by the user.
2. convert it into kgs and grms by dividing it with 1000 and also by using modulus operation.
3. Displaying the output.
GramsToKilograms.java
import java.util.Scanner;
public class GramsToKilograms {
public static void main(String[] args) {
int totGrams, kgs, gms;
/*
* Creating an Scanner class object which is used to get the inputs
* entered by the user
*/
Scanner sc = new Scanner(System.in);
//Getting the input enetred by the user
System.out.print("Enter the Weight in grams :");
totGrams = sc.nextInt();
//Calculating the kgs and grams
kgs = totGrams / 1000;
gms = totGrams % 1000;
//Displaying the output
System.out.print("There are " + kgs + " kilograms and " + gms + " grams in " + totGrams + " grams.");
System.out.println("");
}
}
___________________
Output:
Enter the Weight in grams :5370
There are 5 kilograms and 370 grams in 5370 grams.
___________________
EX#2
FlipNumber
import java.util.Scanner;
public class FlipNumber {
public static void main(String[] args) {
int num, flipNum;
/*
* Creating an Scanner class object which is used to get the inputs
* entered by the user
*/
Scanner sc = new Scanner(System.in);
//Getting the input entered by the user
System.out.print("Enter a Three Digit number :");
num = sc.nextInt();
//Calling the method by passing the user entered number
flipNum = flipNum(num);
//Displaying the output
System.out.println("The Flip of " + num + " is " + flipNum);
}
//This Method flips the number
private static int flipNum(int num) {
//Declaring variables
int temp = 0;
int flip_number = 0;
//This while loop will flip the number
while (num > 0) {
temp = num % 10;
flip_number = flip_number * 10 + temp;
num = num / 10;
}
return flip_number;
}
}
___________________
Output:
Enter a Three Digit number :371
The Flip of 371 is 173
____________________Thank You
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.