Java循环垂直

huangapple go评论96阅读模式
英文:

Java loop vertical

问题

  1. import java.util.Scanner;
  2. public class Main {
  3. public static void main(String args[]) {
  4. Scanner in = new Scanner(System.in);
  5. int num = in.nextInt();
  6. int rev = 0;
  7. while (num != 0) {
  8. rev = rev * 10;
  9. rev = rev + num % 10;
  10. num = num / 10;
  11. }
  12. while (rev != 0) {
  13. System.out.println(rev % 10);
  14. rev = rev / 10;
  15. }
  16. }
  17. }
英文:

My code basically arranged the number into reverse order for example 415 the program will arrange it into 514 well my code is correct but I have a problem the output should be vertical.

> expected output
> 5
> 1
> 4

  1. import java.util.Scanner;
  2. public class Main{
  3. public static void main(String args[])
  4. {
  5. Scanner in = new Scanner(System.in);
  6. int num = in.nextInt();
  7. int rev=0;
  8. while( num != 0 )
  9. {
  10. rev = rev * 10;
  11. rev = rev + num%10;
  12. num = num/10;
  13. }
  14. System.out.println(rev);
  15. }
  16. }

答案1

得分: 5

你只需要像这样做:

  1. while (num != 0)
  2. {
  3. System.out.println(num % 10);
  4. num = num / 10;
  5. }
英文:

You just need to do it like this:

  1. while( num != 0 )
  2. {
  3. System.out.println(num % 10);
  4. num = num / 10;
  5. }

答案2

得分: 0

这是另一种方法,您可以使用此方法获取超过整型数据类型所能容纳的过大的整数。

  1. Scanner in = new Scanner(System.in);
  2. String s = in.nextLine();
  3. for (int i = s.length() - 1; i >= 0; i--) {
  4. System.out.println(s.charAt(i));
  5. }
英文:

I am leaving this as an alternate method. By this you can take int which are are too big to fit in int datatype

  1. Scanner in = new Scanner(System.in);
  2. String s = in.nextLine();
  3. for (int i = s.length() - 1; i >= 0; i--) {
  4. System.out.println(s.charAt(i));
  5. }

huangapple
  • 本文由 发表于 2020年10月18日 12:28:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/64409737.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定