3

I'm a beginner in Java and got this school problem:

The authority of XYZ gated residential colony wants its residents' name datum Should be stored in the following format - residents' name his/her father's name. Write a program to concat the father's name to the residents' name. The name should be validated,on validation the name should contain only alphabets and space is allowed. If the name is not valid display the message "Invalid name". If valid string then convert it to uppercase and print it

Sample Input 1:

Inmate's name:Aron

Inmate's father's name:Terby

Sample Output 1:

ARON TERBY

Error: It prints out "Invalid Input" whenever I enter a two-letter Inmate's name like- Aron Kumar otherwise for a single word string input code works alright.

This was the code I wrote:


     Scanner sc=new Scanner(System.in);
     System.out.println("Inmate's name:"); //if I enter 2 word string,output-"Invalid name1"//
     String name=sc.nextLine();
     System.out.println("Inmate's father's name:");
     String fname=sc.nextLine();

        String s3=name.toUpperCase();
        String s4=fname.toUpperCase();

        char[] a1= s3.toCharArray();
        char[] a2= s4.toCharArray();
        for(int i=0;i<a1.length;i++)
        {   
            if(a1[i]>='A' && a1[i]<='Z')
             count=1;

            else {
                System.out.print("Invalid name1");
                count=0;
                break; }
        }

        if(count==1)
        {
            for(int i=0;i<a2.length;i++)
           {
            if(a2[i]>='A' && a2[i]<='Z')
            count=2;

            else   {
            System.out.print("Invalid name");
            break; }
       }  
           }

       if(count==2) {
         System.out.print(s3+" "+s4);
                   }
   }
}
2
  • 2
    It would be preferable if you posted a minimal reproducible example without the line numbers, since they prevent anyone copying and running your code. Commented Apr 12, 2020 at 20:46
  • 2
    Thanks for the valuable suggestion, Sir. I'm a beginner to this platform, next time I'll keep this in mind. Commented Apr 14, 2020 at 16:09

4 Answers 4

2

The problem is that you are not checking for a space character. Check it as follows:

if (a1[i] >= 'A' && a1[i] <= 'Z' || a1[i] == ' ')

Another problem with your code is changing the value of count to 1 and 2 in each iteration whereas it should be changed when the loop terminates. Given below is the corrected code:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int count = 0, i;
        Scanner sc = new Scanner(System.in);
        System.out.println("Inmate's name:"); 
        String name = sc.nextLine();
        System.out.println("Inmate's father's name:");
        String fname = sc.nextLine();

        String s3 = name.toUpperCase();
        String s4 = fname.toUpperCase();

        char[] a1 = s3.toCharArray();
        char[] a2 = s4.toCharArray();
        for (i = 0; i < a1.length; i++) {
            if (!(a1[i] >= 'A' && a1[i] <= 'Z' || a1[i] == ' ')) {
                System.out.print("Invalid name1");
                count = 0;
                break;
            }
        }

        // If 'i' reached a1.length, it means no invalid character was found
        if (i == a1.length) {
            count = 1;
        }

        if (count == 1) {
            for (i = 0; i < a2.length; i++) {
                if (!(a2[i] >= 'A' && a2[i] <= 'Z' || a2[i] == ' ')) {
                    System.out.print("Invalid name");
                    break;
                }
            }

            // If 'i' reached a2.length, it means no invalid character was found
            if (i == a2.length) {
                count = 2;
            }
        }

        if (count == 2) {
            System.out.print(s3 + " " + s4);
        }
    }
}

Additional note:

You can make your code much shorter by using regex as follows:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Inmate's name: ");
        String name = sc.nextLine();
        System.out.print("Inmate's father's name: ");
        String fname = sc.nextLine();
        if (name.matches("[A-Za-z\\s]+") && fname.matches(("[A-Za-z\\s]+"))) {
            System.out.println(name.toUpperCase() + " " + fname.toUpperCase());
        } else if (!name.matches("[A-Za-z\\s]+")) {
            System.out.println("Inmate's name is invalid");
        } else if (!fname.matches(("[A-Za-z\\s]+"))) {
            System.out.println("Inmate's father's name is invalid");
        }
    }
}

The explanation of the regex, [A-Za-z\\s]+:

  1. A-Za-z is for alphabets.
  2. \\s is for space.
  3. The + at the end of [A-Za-z\\s]+ means more than one occurrences are allowed.

A sample run:

Inmate's name: Ram Kumar
Inmate's father's name: Raj Kumar
RAM KUMAR RAJ KUMAR

Another sample run:

Inmate's name: Ram5 Kumar
Inmate's father's name: Raj Kumar
Inmate's name is invalid

Another sample run:

Inmate's name: Ram Kumar
Inmate's father's name: Raj5 Kumar
Inmate's father's name is invalid
Sign up to request clarification or add additional context in comments.

5 Comments

I think regular expressions might be too advanced for someone who is just learning to program.
@VGR- Thanks for the feedback. I agree with you. That is why I have written that option under Additional Note
Thanks a lot for the solution Sir, I tried the solution but, error: array required, but int found if((a1[i]>='A' && a1[i]<='Z') || (a[i]==' ')) ^
@zeus - I've corrected your code and posted the same. Feel free to comment in case there is any issue/doubt.
@ArvindKumarAvinash Yes Sir, the error is resolved. Thanks a lot. I've accepted the answer.
0

When you compare char values in Java, you're relying on the ASCII value of that char. The ASCII value of A is 65, whereas the ASCII value of Z is 90.

Your current code is simply evaluating each char in the character array to make sure it's in the range of 65 to 90, inclusive. The ASCII value of the space char, however, is 32, falling well outside of that range.

Rewrite your code to accept capital letters or spaces (as dictated by the problem description) like so:

if((a1[i]>='A' && a1[i]<='Z') || (a1[i] == 32))

2 Comments

Why use the magic number 32 instead of just writing a1[i] == ' ' ?
Thanks a lot for the solution. I tried the solution but, error: array required, but int found if((a1[i]>='A' && a1[i]<='Z') || (a[i]==32)) ^
0

It happens because here

if(a1[i]>='A' && a1[i]<='Z') count=1;

You asking "if char in array is between A and Z, then count = 1"

But in case with name "Aron Kumar" You have a space symbol between two words and this space symbol is not between A and Z, so count don't equals 1 and output is "Invalid Input".

You have to check char array for space too.

You can take the answer of MarsAtomic as a good example.

Comments

0
import java.util.Scanner;
import java.util.regex.*;

public class Authority{
    
    public static void main(String[] args)
    {
        Scanner s = new Scanner(System.in);
        
        System.out.println("Inmate's name:");
        
        String Inmate = s.nextLine();
        System.out.println("Inmate's father's name:");
        
        String father = s.nextLine();
        
        if(!Pattern.matches("^[a-zA-Z\\s]+",Inmate))
        {
            System.out.println("Invalid name");
        }
        else if(!Pattern.matches("^[a-zA-Z\\s]+",father))
        {
            System.out.println("Invalid name");
        }
        else
        {
           String k = Inmate +" "+ father;
           System.out.println(k.toUpperCase());
        }
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.