finding weather all the given input array elements are strings
import java.util.Scanner;
public class Q166809 {
public static void main(String[] args) {
// Scanner object
Scanner keyboard = new Scanner(System.in);
try {
//Declare array
String strings[];
// Get the number of strings from the user
System.out.print("Enter the number of strings: ");
int N = keyboard.nextInt();
strings=new String[N];
keyboard.nextLine();
// Get the string from the user
for(int i=0;i<N;i++) {
System.out.print("Enter the string: ");
strings[i] = keyboard.nextLine();
}
// Display result
for(int i=0;i<N;i++) {
if(isString(strings[i])) {
System.out.println("\""+strings[i] +"\" is a string");
}
}
} catch (Exception e) {
// Display the error message:
System.out.print("Incorrect value");
}
// close Scanner
keyboard.close();
}
/**
* This function allows to check if a string has only letters
* @param string
* @return
*/
public static boolean isString(String string)
{
for (char c : string.toCharArray())
{
if (!Character.isLetter(c)) return false;
}
return true;
}
}
Comments
Leave a comment