For Programmers: Free Programming Magazines  


Home > Archive > Java Help > February 2006 > Reverse Numbers









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Reverse Numbers
IanH

2006-02-28, 3:59 am

Hi
In the following program, what ever digits are typed into the inputbox
I want them displayed in reverse order in the status bar. At the moment
only the first digit appears in the status bar. I can't see where i'm
going wrong. Maybe someone can take a look.
Cheers Ian

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;

public class Reverse extends JApplet implements ActionListener {
JTextField inputField;
JLabel prompt;

// set up GUI components
public void init()
{
prompt = new JLabel( "Enter Digits:" );
inputField = new JTextField( 4 );
inputField.addActionListener( this );

Container container = getContentPane();
container.setLayout( new FlowLayout() );
container.add( prompt );
container.add( inputField );

} // end method init

// call method qualityPoints if user input is within range
public void actionPerformed( ActionEvent actionEvent )
{
int inputNumber = Integer.parseInt( inputField.getText() );


if ( inputNumber != 0 ){
showStatus( "Reversed is: " + qualityPoints( inputNumber ) );}
else
showStatus( "Invalid input." );

} // end method actionPerformed

// return single digit value of grade
public int qualityPoints( int num)
{
int rightDigit =0;
int newnum = 0;

rightDigit = num % 10;
newnum = newnum * 10 + rightDigit;
num = num / 10;

return num;

} // end method qualityPoints

} // end class Reverse

Bart Cremers

2006-02-28, 3:59 am

public int qualityPoints(int num) {
int res = 0;

while (num > 10) {
res = (res * 10) + num % 10;
num /= 10;
}
res = (res * 10) + num;

return res;
}

If you only need to revers a two digit number:
return (num % 10) * 10 + num / 10;

Regards,

Bart

IanH

2006-02-28, 3:59 am

Cheers Bart, that was a great help.

Roedy Green

2006-02-28, 7:04 pm

On 28 Feb 2006 01:19:20 -0800, "IanH" <hill_ian_j@yahoo.co.uk> wrote,
quoted or indirectly quoted someone who said :

>In the following program, what ever digits are typed into the inputbox
>I want them displayed in reverse order in the status bar.


see String.reverse
--
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.
Thomas Hawtin

2006-02-28, 7:04 pm

Roedy Green wrote:
> On 28 Feb 2006 01:19:20 -0800, "IanH" <hill_ian_j@yahoo.co.uk> wrote,
> quoted or indirectly quoted someone who said :
>
>
> see String.reverse


Doesn't exist...

new StringBuffer(str).reverse().toString()

Tom Hawtin
--
Unemployed English Java programmer
http://jroller.com/page/tackline/
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com