Issue
For my APCS class, my assignment was to take a three-digit number inputed by the user and to print each digit in order on separate lines. My code works fine:
import java.util.Scanner;
public class threeDigits
{
public static void main (String [] args ){
System.out.println("Give me a three digit integer and I will print out each individual digit");
Scanner input = new Scanner(System.in);
int number = input.nextInt();
int digit1 = number / 100;
int digit2 = (number % 100)/10;
int digit3 = number % 10;
System.out.println(digit1);
System.out.println(digit2);
System.out.println(digit3);
}
}
What I would like to know is if there is a better, more simple way to get the same result or if this is the best way to do it. Even if this is the most quick-and-dirty way to get the result, I would love to see alternate ways of doing the same thing, not to hand in for a grade but just as a learning experience.
Solution
Alternate solution:
First input a integer and convert it to String
then loop through the String
.
public static void main (String [] args ) {
System.out.println("Give me a three digit integer and I will print out each individual digit");
Scanner input = new Scanner(System.in);
int number = input.nextInt();
String str = Integer.toString(number);
for(int i=0; i<str.length(); i++){
System.out.println(str.charAt(i));
}
}
Answered By - ashiquzzaman33
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.