0

How can i add output that warn user when they input non-number? (Means error when user input other than number as alphabet)

package decimal_binary; //use import javax.swing package when we use a gui import javax.swing.*; import java.util.Scanner; public class Decimal_Binary { public static void main(String[] args) { int n; String decNum; String binary; Scanner sc=new Scanner(System.in); { decNum = JOptionPane.showInputDialog(null, "Enter decimal number:"); n = Integer.parseInt(decNum); } if(n<0) { JOptionPane.showMessageDialog(null,"Invalid entry! Enter positive numbers only"); } else { binary = Integer.toBinaryString(n); JOptionPane.showMessageDialog(null, "Binary equivalent is: " +binary); } } }

5th Dec 2016, 5:23 AM
frhnims
1 Resposta
+ 1
Will the user write their input into a text field or using the scanner you,ve defined?. Either way you could have have separate method that will loop through the entire word the user wrote and use isDigit() method. e.g public boolean validator(String userInput){ int counter = 0; for(int i = 0: i < userInput.length(); i++){ if(Character.isDigit(userInput.charAt(i){ counter++; } } if(counter == userInput.length()) return true; return false; } If it returns false then you can warn the user. I believe also there is a better way to do it if you're using a scanner.
5th Dec 2016, 9:13 AM
Ousmane Diaw