3 Replies - 12232 Views - Last Post: 18 March 2007 - 01:22 PM Rate Topic: ***** 1 Votes

#1 ejme  Icon User is offline

  • New D.I.C Head

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

Making sure input is only NUMBERS

Post icon  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  Icon User is offline

  • Refactorer in Chief
  • member icon

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

Re: Making sure input is only NUMBERS

Posted 15 March 2007 - 03:16 AM

View Postejme, 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.
Was This Post Helpful? 0
  • +
  • -

#3 horace  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 768
  • View blog
  • 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();


Was This Post Helpful? 0
  • +
  • -

#4 aRTx  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • 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);

}
}
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1