繁体   English   中英

仅使用循环即可反转数字;不使用数组,只需初学者即可转换为String…错误:零

[英]Reverse number using only loops;no Arrays,convert to String just beginner…Bug:Zero

我正在尝试将随机数从1反转为9999,并陷入错误0:

示例: 23100是随机数。 我的输出是132,但解决方案是00132

由于我仍然不了解数组,因此请转换为String(操作),对象解决方案等。 我找不到针对此问题的初学者级解决方案。 由于此页面对我有很大帮助,因此我决定尝试帮助某人。 这是初学者解决问题的方法:

123反向321

12300返回00321 //错误问题为零

我仍然遇到问题:00123和输出32100而不是321

这是我的代码:

import java.util.Scanner;
public class R_N{
public static void main(String[] args){
Scanner input=new Scanner(System.in);
System.out.print("enter number:\n");
int x=input.nextInt();
int temp=x;
int z;
while(temp>0){
    z=temp%10;
        if(z==0){
            System.out.printf("%d",0);
        }else{
            System.out.printf("%d",z);
        }
    temp=temp/10;
  } 
 }
}

据我所知,这类任务与使用字符串等无关。 正确使用modulo和div就是全部。 仅当文本值为00123时,尾随零才有意义。 123是一个数字。 因此,您的程序可以很好地完成您的任务。 但是你的if(z == 0)没有意义:)

为了将00123反转为32100您需要将输入读取为String ,然后测试它是否仅包含带有正则表达式的数字(例如\\\\d+ ),最后您可以从打印每个字符的结尾开始对其进行迭代。 就像是,

Scanner input = new Scanner(System.in);
System.out.print("Please enter a number:\n");
System.out.flush();
while (input.hasNextLine()) {
    String x = input.nextLine().trim();
    if (x.matches("\\d+")) {
        // Iterate the input String in reverse order,
        for (int i = x.length() - 1; i >= 0; i--) {
            // Print each character
            System.out.print(x.charAt(i));
        }
        System.out.println();
    } else {
        // Give the user a message ...
        System.out.printf("%s is not a number%n", x);
    }
    System.out.print("Please enter a number:\n");
    System.out.flush();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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