为什么我的程序挂起?

时间:2023-01-17 13:34:20

I am trying to reverse an integer inputed by calling on a different method. I have this

我试图通过调用不同的方法来反转一个整数。我有这个

import java.util.*;

public class reverseDigit
{

  public static int reverseDigit(int number) //digit reversing method
  {  
    int reverse= 0;

    while(number >= 0)
     {
      reverse = reverse*10 + number%10;
      number = number/10;
     }
   return reverse;
  }
 static Scanner console = new Scanner (System.in);

 public static void main (String[]args) //main method
 {
  int number;

  System.out.println("Enter an interger to be reversed");

  number = console.nextInt();

  System.out.println(number+"reversed is:"+ reverseDigit(number));

 }
}

I've hit a wall so any help is appreciated.

我撞墙了,所以任何帮助都表示赞赏。

3 个解决方案

#1


4  

Use

while(number > 0)

When number gets zero then it stays zero and so you are in an infinite loop.

当数字变为零时,它保持为零,因此您处于无限循环中。

#2


0  

It looks like your program is in an infinite loop caused by the line while(number >= 0). Use of the debugger in your IDE would have helped you find this issue quickly. Replace that line with while(number > 0) to correct the infinite loop.

看起来你的程序处于由行(while> = 0)引起的无限循环中。在IDE中使用调试器可以帮助您快速找到此问题。用while(number> 0)替换该行以纠正无限循环。

#3


0  

Or you can do it with Strings?

或者你可以用字符串来做到这一点?

static int reverse(int number){
    String temp = String.valueOf(number);
    StringBuilder reversedTemp = new StringBuilder(temp);
    reversedTemp.reverse();
    return Integer.parseInt(reversedTemp.toString());
}

Or spice it up with a one-liner!

或者用一个内衬来加强它!

static int reverse(int number){
        return Integer.parseInt(new StringBuilder(String.valueOf(number)).reverse().toString());
}

#1


4  

Use

while(number > 0)

When number gets zero then it stays zero and so you are in an infinite loop.

当数字变为零时,它保持为零,因此您处于无限循环中。

#2


0  

It looks like your program is in an infinite loop caused by the line while(number >= 0). Use of the debugger in your IDE would have helped you find this issue quickly. Replace that line with while(number > 0) to correct the infinite loop.

看起来你的程序处于由行(while> = 0)引起的无限循环中。在IDE中使用调试器可以帮助您快速找到此问题。用while(number> 0)替换该行以纠正无限循环。

#3


0  

Or you can do it with Strings?

或者你可以用字符串来做到这一点?

static int reverse(int number){
    String temp = String.valueOf(number);
    StringBuilder reversedTemp = new StringBuilder(temp);
    reversedTemp.reverse();
    return Integer.parseInt(reversedTemp.toString());
}

Or spice it up with a one-liner!

或者用一个内衬来加强它!

static int reverse(int number){
        return Integer.parseInt(new StringBuilder(String.valueOf(number)).reverse().toString());
}