In: Computer Science
Checker for integer string
Forms often allow a user to enter an integer. Write a program that takes in a string representing an integer as input, and outputs yes if every character is a digit 0-9.
Ex: If the input is:
1995
the output is:
yes
Ex: If the input is:
42,000
or
1995!
the output is:
no
Hint: Use a loop and the Character.isDigit() function.
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userString;
// Add more variables as needed
userString = scnr.next();
/* Type your code here. */
}
}
Output:
Code:
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new
Scanner(System.in);
String userString;
int flag = 1;
userString =
scnr.next();
//traverse each
character of the string
for(char ch :
userString.toCharArray()){
//check if current Character is digit or not
if(!Character.isDigit(ch)){
flag=0; //set flag to zero to indicate invalid string
break;
}
}
//check if there are
only digits
if(flag==0){
System.out.println("no");
} else{
System.out.println("yes");
}
}
}