Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 垂直显示输入数字的模数_Java_Modulus - Fatal编程技术网

Java 垂直显示输入数字的模数

Java 垂直显示输入数字的模数,java,modulus,Java,Modulus,基本上,我需要用java编写一个程序,要求用户输入一个整数,然后垂直显示该数字(仅使用数学),因此数字2849将显示: 二, 八, 四, 九, 我知道我可以使用10的模,得到9,4,8,2,但我不知道如何编写代码,在第一个模之后继续携带新值 import java.util.Scanner; public class HorizToVert { public static void main(String[] args) { Scanner input = new Scann

基本上,我需要用java编写一个程序,要求用户输入一个整数,然后垂直显示该数字(仅使用数学),因此数字2849将显示:

二,

八,

四,

九,

我知道我可以使用10的模,得到9,4,8,2,但我不知道如何编写代码,在第一个模之后继续携带新值

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

这就是我目前所知道的。正如我所说,我知道它会给我第一个余数。假设用户输入4936。我知道第一个模数等于6。我不知道如何去493后,我做了第一个模数继续这个过程。任何帮助都会很好

您需要使用模数和除法的组合。模数将去掉数字上方的内容;除法时去掉数字下面的部分

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.
}
int-answer=input.nextInt();
如果(答案<0)
{
系统输出打印(“-”);
answer=answer*-1;//使循环为正
}
对于(整数指数=1;答案>0;指数=指数+1)
{
int mod=答案%Math.pow(10,指数);//去掉所需数字上方的数字。
int digit=mod/Math.pow(10,指数-1);//去掉所需数字下面的数字,并将所需数字置于[0-9]范围内。
系统输出打印(数字);
answer=answer-mod;//循环控制需要。
}

正如您正确观察到的,模10将只返回最后一位数字

所以必须写一个循环,依次得到每个数字,将非余数除以10,然后重复。最后,反转列表进行打印


一种更简单的方法可能是使用字符串转换,您可以简单地逐位打印数字字符。

因此我意识到除法是实际的处理方法,因为模数将给出输入的相反方向。但我仍然不知道如何到达第二个间歇。