/* * Enter a string to count the digits in Your string contains 0 digits. NOTE:
ID: 3544690 • Letter: #
Question
/*
* Enter a string to count the digits in
Your string contains 0 digits.
NOTE: For this assignment you should use the Character.isDigit() method. This method returns a true value if the character being tested is a digit between 0 and 9 and a false value otherwise.
For example, the following code snippet displays the message "That's a digit!":
Enter a string to count the digits in: thx-1138
Your string contains 4 digits.
char testValue = '9';
if (Character.isDigit(testValue)) {
System.out.println("That's a digit!");
Enter a string to count the digits in: thx-1138
Your string contains 4 digits.
*/
import java.util.Scanner;
public class ClosedLab05 {
public static void main(String[]args)
{
Scanner in=new Scanner(System.in);
System.out.println("Enter a string to count the digits in: ");
String str=in.nextLine();
char n=str.charAt(0);
int digit=0,index=0;
while (index<str.length());
{
boolean a=Character.isDigit(n);//ture or false
if(a==true)
{
digit++;
}
n=str.charAt(index);
index=index+1;
}
System.out.println("Your String contains"+ digit +" digits");
}
}
Explanation / Answer
import java.util.Scanner;
public class ClosedLab05 {
public static void main(String[]args)
{
Scanner in=new Scanner(System.in);
System.out.println("Enter a string to count the digits in: ");
String str=in.nextLine();
char n;
boolean a;
int digit = 0,index=0;
while(index<str.length()) {
n= str.charAt(index);
a = Character.isDigit(n);
if (a) {
digit++;
}
index++;
}
System.out.println("Your String contains "+ digit +" digits");
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.