简体   繁体   English

反转随机数

[英]Reversing a random amount of numbers

I have this code: 我有以下代码:

int rev=0;
int opt=Integer.parseInt(JOptionPane.showInputDialog("How many numbers do you need?"));
for (int i=0; i<numbers; i++) {
   int numbers=Integer.parseInt(JOptionPane.showInputDialog("Add your numbers"));
   while (numbers != 0) {
      rev=rev*10;
      rev=rev+numbers%10;
      numbers=numbers/10;
    }
 }
JOptionPane.showMessageDialog(null,"Your numbers are "+rev);

It works perfectly fine. 它工作得很好。 I want the numbers to be reversed though. 我希望数字可以颠倒。 It does, but it has to be multiple numbers. 可以,但是必须是多个数字。

Example: Let's say I want 2 numbers: 123 , 456 the output would be 321654 例如:比方说,我想2号: 123456的输出将是321654

My question is, if I want 3 numbers: 1 , 2 , 3 how do i make it so it would print 321 because it doesn't work if I add one digit numbers. 我的问题是,如果我想3个数字: 123我如何使它所以它会打印321 ,因为,如果我加一个数字号码不起作用。

I'm sorry if it doesn't make sense or my question doesn't explain much. 很抱歉,如果这没有意义,或者我的问题没有解释太多。

Something like this should work (Its not tested) 这样的东西应该可以工作(未经测试)

 String res="";
 Integer opt=Integer.parseInt(JOptionPane.showInputDialog("How many numbers do you need?"));
 for (int i=0; i<opt; i++) {
   String numbers=JOptionPane.showInputDialog("Add your numbers");
   res = new StringBuilder(numbers).reverse().toString() + res;
 }
 JOptionPane.showMessageDialog(null,"Your numbers are "+res);

Or this 或这个

 String res="";
 Integer opt=Integer.parseInt(JOptionPane.showInputDialog("How many numbers do you need?"));
 for (int i=0; i<opt; i++) {
   String numbers=JOptionPane.showInputDialog("Add your numbers");
   res += numbers;
 }
 String reversedString = new StringBuilder(res).reverse().toString();
 JOptionPane.showMessageDialog(null,"Your numbers are "+ reversedString);

您可以将这些数字放在ArrayList中,然后使用Collections.reverse(list)以相反的顺序获取它们。

You need to reverse each item's inner character order and then reverse the order in which the items were provided to you. 您需要颠倒每个项目的内部字符顺序,然后颠倒提供给您的项目的顺序。

    ArrayList<StringBuilder> reversedNumbers = new ArrayList<StringBuilder>();
    for (/*your for loop condition here...*/) {
        String sNumber = /*ask the user for a string here...*/
        StringBuilder reversedNumber = new StringBuilder(sNumber).reverse();
        reversedNumbers.add(reversedNumber);
    }
    Collections.reverse(reversedNumbers);/*finally reverse the colection*/
    JOptionPane.showMessageDialog(null,"Your numbers are "+ reversedNumbers);

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

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