Java循环垂直

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

Java loop vertical

问题

import java.util.Scanner;

public class Main {
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        int num = in.nextInt();
        int rev = 0;
        
        while (num != 0) {
            rev = rev * 10;
            rev = rev + num % 10;
            num = num / 10;
        }
        
        while (rev != 0) {
            System.out.println(rev % 10);
            rev = rev / 10;
        }
    }
}
英文:

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

import java.util.Scanner;
public class Main{
  public static void main(String args[])
  {
    Scanner in = new Scanner(System.in);
    int num = in.nextInt();
    int rev=0;
    while( num != 0 )
      {
          rev = rev * 10;
          rev = rev + num%10;
          num = num/10;
      }
          System.out.println(rev);
  }
}

答案1

得分: 5

你只需要像这样做:

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

You just need to do it like this:

while( num != 0 )
{
	System.out.println(num % 10);
	num = num / 10;
}

答案2

得分: 0

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

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

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

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

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:

确定