在Java中用新行打印数字的每个数字

时间:2015-11-13 01:37:30

标签: java loops methods while-loop

我有以下代码,用于程序的目的是为用户输入一个数字,即123,程序将其输出为1 2 3垂直。无论我做什么,我的程序都是3 2 1.我需要在这个程序中使用循环,我似乎无法弄明白。

import java.util.Scanner;

public class DigitsDisplay {
    public static Scanner console = new Scanner(System.in);

    public static void main(String[] args) {
        int a = getInt("Give a non-negative integer: ");
        double backwards = 0;
        int reverse;
        int numOfDigits = numOfDigits(a);
        double place = Math.pow(10, numOfDigits);

        while (a != 0) {
            reverse = a % 10;
            backwards = backwards + place * reverse;
            System.out.println(reverse);
            a = a / 10;
        }
    }

    public static int getInt(String prompt) {
        int input;

        System.out.print(prompt);
        input = console.nextInt();

        return input;
    }

    public static int numOfDigits(int a) {
        int numOfD = (int)(Math.log10(a)) + 1;

        return numOfD;
    }

}

1 个答案:

答案 0 :(得分:3)

反转反转值

您的程序旨在反转数字。确实如此。如果您想要撤消它们,我建议您将它们附加到StringBuilder,然后reverse。像,

protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            //if(!IsPostBack)
            //{
                string search = txt_search.Text;
                if (search != "")

                    lstbox_work.Items.Clear();
                    string[] ext = new string[] { ".pptx", ".xlsx", ".docx", ".xls", ".pdf" };
                    var files = Directory.GetFiles(@"\\192.168.1.12\files\workinstruction", txt_search.Text + "*.*").Where(s => ext.Any(n => s.EndsWith(n)));

                    IComparer mycomparer = new myReverserClass();
                    string[] sarray = files.ToArray();

                    DateTime[] creationtime = new DateTime[sarray.Length];
                    for (int i = 0; i < sarray.Length; i++)
                        creationtime[i] = new FileInfo(sarray[i]).CreationTime;
                    Array.Sort(creationtime, sarray, mycomparer);

                    foreach (string file in sarray)
                    {
                        lstbox_work.Items.Add(new ListItem(Path.GetFileName(file), file)); //here the item is listed without spacing. i need the items list with spacing 
                    }

                    {
                        txt_search.Text = "";
                    }

使用正则表达式

使用String.replaceAll(String, String) regular expression匹配并对StringBuilder sb = new StringBuilder(); while (a != 0) { reverse = a % 10; sb.append(reverse).append(System.lineSeparator()); backwards = backwards + place * reverse; a = a / 10; } System.out.print(sb.reverse()); 的所有数字进行分组,然后将每个数字替换为自身加上一个新行,可以简化您的算法。像,

a