# Making sure input is only NUMBERS

Page 1 of 1

## 3 Replies - 12280 Views - Last Post: 18 March 2007 - 01:22 PMRate Topic: 1 Votes //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=25089&amp;s=bdc8a43de0990422dbe02169cd3a19af&md5check=' + ipb.vars['secure_hash'], cur_rating: 5, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 ejme

Reputation: 0
• Posts: 2
• Joined: 15-March 07

# Making sure input is only NUMBERS

Posted 15 March 2007 - 01:59 AM

How do you check input to make sure it only has numbers?

Or is there a way to make input compulsory numbers only?

eg. input is a salary:

```System.out.print("Enter your annual salary: ");
salary = console.nextDouble();

```

Is This A Good Question/Topic? 0

## Replies To: Making sure input is only NUMBERS

### #2 Programmist

• Refactorer in Chief

Reputation: 255
• Posts: 1,843
• Joined: 02-January 06

## Re: Making sure input is only NUMBERS

Posted 15 March 2007 - 03:16 AM

ejme, on 15 Mar, 2007 - 01:59 AM, said:

How do you check input to make sure it only has numbers?

Or is there a way to make input compulsory numbers only?

eg. input is a salary:

```System.out.print("Enter your annual salary: ");
salary = console.nextDouble();

```

Inside a try-catch statement, use Double.parseDouble( String s ) to attempt to convert the input to a Double. if you catch a NumberFormatException then you know it was a bad input. Put all of this (including your prompt and input reading) inside a loop that only terminates if an exception is not thrown.

### #3 horace

• D.I.C Lover

Reputation: 768
• Posts: 3,832
• Joined: 25-October 06

## Re: Making sure input is only NUMBERS

Posted 18 March 2007 - 09:03 AM

you can test if the next token is a double, if not discard it. Keep doing that until you get a double entered, e.g.
```System.out.print("Enter your annual salary: ");
// if next token is a double read it otherwise ignore it
while (!console.hasNextDouble()) console.next();	// not double, discard token
salary = console.nextDouble();

```

### #4 aRTx

Reputation: 0
• Posts: 2
• Joined: 02-December 06

## Re: Making sure input is only NUMBERS

Posted 18 March 2007 - 01:22 PM

if we have interactive input p.s

import javax.swing.*;
public class isNumber{
public static void main(String[] args){
String s1 = JOptionPane.showInputDialog("write something");

//we can convert this string to integer

int nr = Integer.parseInt(s1);

// but if the string does not content number the program will be fail

// I have a question, how to repeat input while we will write number

// plz tell us

System.out.println(nr);

}
}