Help?

/*
* Lesson 7 Coding Activity Question 1
*
* Input a positive three digit integer. Print out the digits one per line.
*
* Sample run:

Please enter a three digit number:
678

Here are the digits:
6
7
8

*/

import java.util.Scanner;
import java.lang.Math;

class Lesson_7_Activity_One {
public static void main(String[] args) {

/* Write your code here
* Copy and paste your entire code to Code Runner to complete the activity,
* from the first import statement to the last bracket.
*/
Scanner scan = new Scanner (System.in);
System.out.println("Please enter a three digit number:");
int num= scan.nextInt();
int first = num % 10;
int second = ( num - first ) % 100 / 10;
int third = ( num - first - second ) % 1000 / 100;
System.out.println("Here are the digits: ");
System.out.println(first);
System.out.println(second);
System.out.println(third);
}
}

Respuesta :

tonb

In stead of going number arithmetic, you could also approach it as string handling. Replace the last lines of your code (right after the scan statement) with:


String s = Integer.toString(num);

System.out.println("Here are the digits: ");

System.out.println(s.charAt(0)+"\n"+s.charAt(1)+"\n"+s.charAt(2));

The program illustrates the use of arithmetic operation; most especially, the modulo operation.

A modulo operator (represented as %) returns the remainder after two integers are divided

Take for instance:

[tex]5 \% 3 = 2[/tex]

The result is 2, because when 5 is divided by 3, the remainder is 2

The modified program in java, where comments are used to explain each line is as follows:

import java.util.Scanner;

import java.lang.Math;

class Lesson_7_Activity_One {

public static void main(String[] args) {

//This creates a scanner object

   Scanner scan = new Scanner (System.in);

//This prompts the user for a three-digit number

   System.out.println("Please enter a three-digit number:");

//This gets the input from the user

   int num= scan.nextInt();

//This calculates the first digit using the modulo operator

   int first = (num - num % 100)/100;

//This calculates the remainder

  num -= first * 100;

//This calculates the second digit using the modulo operator

   int second = (num - num % 10)/10;

//This calculates the third digit

   int third = num -second * 10;

//This prints the output header

   System.out.println("Here are the digits: ");

//This prints the first digit

   System.out.println(first);

//This prints the second digit

   System.out.println(second);

//This prints the third digit

   System.out.println(third);

}

}

At the end of the program, the first, second and third digit of the number are printed.

See attachment for sample run

Read more about modulo operator at:

https://brainly.com/question/24635879

Ver imagen MrRoyal
ACCESS MORE