2

Basically I need to write a program in java that will ask the user for an integer, and then display that number vertically (using only math), so the number 2849 will display:

2

8

4

9

I know that I can use modulus by 10, getting 9, 4, 8, 2 but what I do not know is how to write code that will carry over the new value after the first modulus to keep going.

import java.util.Scanner;

public class HorizToVert {
   public static void main(String[] args) {
      Scanner input = new Scanner(System.in);
      System.out.print("Enter a number: ");
      int answer = input.nextInt();
         System.out.print(answer%10);


   }//close main
}//close class

That's what I have so far. As I said, I know that it will give me the first remainder. So say the user enters 4936. I know the first modulus gets me 6. I don't know how to go to 493 after I do that first modulus to continue the process. Any help would be great!

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Devin
  • 21
  • 1
  • So I realized that division is the actual way I should approach this, because modulus will give me the reverse of the input. But I still don't know how to get to the second interval. – Devin May 06 '15 at 22:16

2 Answers2

0

You need to use a combination of modulus and division. The modulus will strip away what's above the digit; while the division while strip away what is below the digit.

int answer = input.nextInt();

if (answer < 0)
{
    System.out.print("-");
    answer = answer * -1; // make it positive for the loop
}

for (int exponent = 1; answer > 0; exponent = exponent + 1)
{
    int mod = answer % Math.pow(10, exponent); //strip away digits above the desired digit.
    int digit = mod / Math.pow(10, exponent - 1); //strip away digits below the desired digit and bring the desired digit into the [0 - 9] range.
    System.out.print(digit);

    answer = answer - mod; //needed for loop control.
}
Vargo
  • 308
  • 2
  • 13
0

As you correctly observe, modulo 10 will only return the last digit.

So have to write a loop to get each digit in turn, divide the non-remainder by 10 and repeat. Finally reverse the list for printing.

An easier approach might use the string conversion, where you can simply print digit character by digit character.

guidot
  • 5,095
  • 2
  • 25
  • 37