printing first 3 digits of decimal number from user input

Viewed 78

The prompt says:

Input a double and print the first three digits after the decimal point with a space between them.

Sample run:

Please input a decimal number:
67.3424
Answer: 3 4 2

What I have so far

Scanner scan = new Scanner(System.in);
System.out.print("Please input a decimal number: ");
double hit_n = scan.nextDouble();

double hit_4 = hit_n % 10;
hit_n /= 10;
double hit_3 = hit_n % 10;
hit_n /= 10;
double hit_2 = hit_n % 10;
hit_n /= 10;
double hit_1 = hit_n % 10;

System.out.println(hit_1);
System.out.println(hit_2);
System.out.println(hit_3);
System.out.println(hit_4);

The problem with this code is that it keeps printing the decimals added when you input them.

2 Answers

Since, it doesn't say how you do it. One way is to ignore all the characters before '.', print three characters following '.', and ignore the rest.

public class Main
{
    public static void main(String[] args) throws java.io.IOException {
       System.out.print("Please input a decimal number: ");
       char c = 0;
       int count = 0;
       boolean print = false;
        while((c = (char) System.in.read()) != '\n'){
          if (c == '.') print = true;
          else if (print && count++ < 3){
             System.out.print(c);
          }
        }
    }
}

Output:

Please input a decimal number: 5234.25234233
252

If you don't want to think about precision of decimal then try this:

public static void main(String[] args) {
    final Scanner scan = new Scanner(System.in);
    System.out.println("Please input a decimal number: ");
    final double hit_n = scan.nextDouble();  // 67,3424

    final String doubleString = String.valueOf(hit_n); // "67.3424"
    final int pointIndex = doubleString.indexOf(".");  // 2
    final String digits = doubleString.substring(pointIndex + 1).substring(0, 3);  // "342"
    final String addSpaces = digits.replaceAll("", " ").trim();  // "3 4 2"
    System.out.println(addSpaces);   // "3 4 2"
}
Related