简体   繁体   中英

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

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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