简体   繁体   中英

Printing an input's digits each in a new line

First of all, i just started programming with Java so i'm really a noob :P

Ok so my instructor gave me an assignment which is to take an int input from the user and put each digit in a new line. for example, if the user gave 12345, the program will give: 1 2 3 4 5 each number in a new line.

The statements i will be using is IF statement and the loops and operators ofcourse.

I thought about using the % operator inside the IF/WHILE but i have two issues. One is that i don't know the number of digits the user is inputting and since i can't use the .length statement i reached a dead end. second of all the console output will be 5 4 3 2 1 inversed.

So can anyone help me or give me any ideas? Thanks in advanced.

How about using a Scanner to get the users input as an int and converting that int to a String using valueOf . Lastly loop over the String to get the individual digits converting them back to int's from char's :

import java.util.Scanner;

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

    Scanner sc = new Scanner(System.in);
    System.out.print("Please enter a Integer:");
    int input = sc.nextInt();

    String stringInput = String.valueOf(input);

    for(int i = 0; i < stringInput.length(); i++) {
      int j = Character.digit(stringInput.charAt(i), 10);
      System.out.println(j);
    }
  }
}

Try it here!

Given the assignment your instructor gave you, can you convert the int into a String ? With the input as a String , you can use the length() String function as you had mentioned to iterate the number of characters in the input and use the built-in String function charAt() to get the index of character you want to print. Something like this:

String input = 12345 + "";
for(int i = 0; i < input.length(); i++)
    System.out.println( input.charAt(i) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM