Java String Concatenation error in output - java

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);
}
}
}

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]+:
A-Za-z is for alphabets.
\\s is for space.
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

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))

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.

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());
}
}
}

Related

Adding a function to java program

I am writing my very first java program, I finally got it all written but on the assignment I need to add a function (other than main). My program counts the number of letter in first name, so I was thinking maybe I could add a function that reads how many letters are uppercase? Any ideas?
public class NameLetters{
public static void main(String []args){
Scanner in = new Scanner(System.in);
String firstName; //Asks for the users first name
int count=0; //Count the letters passing through loop
System.out.print("Hello, this program will ask for your first name and then output the number of letters in your name.");
System.out.print("Please enter your first name:");
String firstName = input.NextLine();
for (int i=0; i<firstName.length(); i++) {
if (firstName.charAt(i) != ' ')
Count ++;
}
system.out.print("There are "+Count+" s in the first name "+firstName+" , Thank you for participating. Goodbye!");
}
}
String s = "NaMe";
int upper = 0;
int lower = 0;
for(int i = 0; i<s.length();i++ ) {
int charASCII= (int)s.charAt(i);
if (charASCII <91 && charASCII > 64){
upper ++;
}
if (charASCII <123 && charASCII > 96){
lower ++;
}
}
System.out.print("Given name string contains "+upper+ " uppercase letters & "+lower + " lowercase letters");

Studing java: character comparing

Exercise:
(Longest common prefix) Write a program that prompts the user to enter two strings and displays the largest common prefix of the two strings.
Here are some sample runs:
Enter the first string: Welcome to C++
Enter the second string: Welcome to programming
The common prefix is Welcome to
Second run:
Enter the first string: Atlanta
Enter the second string: Macon
Atlanta and Macon have no common prefix
my answer:
package chapter5;
import java.util.*;
public class Exer5_51 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the first string: ");
String firstString = input.nextLine();
System.out.println("Enter the second string");
String secondString = input.nextLine();
input.close();
int length = Math.min(firstString.length(), secondString.length());
String commonPrefix = "";
for (int n = 0; n < length; n++) {
if (firstString.charAt(n) == firstString.charAt(n) ) {
commonPrefix += firstString.charAt(n);
}
else {
break;
}
}
if (commonPrefix.length() != 0) {
System.out.printf("The common prefix is %s", commonPrefix);
}
else {
System.out.printf("%s and %s have no common prefix", firstString, secondString);
}
}
}
Is there anything wrong with my code?
Why I can't get the right result?.
if (firstString.charAt(n) == firstString.charAt(n) ) {
commonPrefix += firstString.charAt(n);
}
Should be:
if (firstString.charAt(n) == secondString.charAt(n) ) {
commonPrefix += firstString.charAt(n);
}
You were comparing the first String to itself before.
You are comparing the firstString to itself in the if statement.
if (firstString.charAt(n) == firstString.charAt(n) ) {
commonPrefix += firstString.charAt(n);
}

Java program on name Initials

I am writing a program that will give the Initials of the name(String) user gives as input.
I want to use the Space function while writing the name as the basis of the algorithm.
For eg:
<Firstname><space><Lastname>
taking the char once in a for loop and checking if there is a space in between, if there is it will print the charecter that was just before.
Can someone tell me how to implement this?
I'm trying this but getting one error.
Any help is dearly appreaciated..
P.S- i am new to java and finding it a lot intresting. Sorry if there is a big blunder in the coding
public class Initials {
public static void main(String[] args) {
String name = new String();
System.out.println("Enter your name: ");
Scanner input = new Scanner(System.in);
name = input.nextLine();
System.out.println("You entered : " + name);
String temp = new String(name.toUpperCase());
System.out.println(temp);
char c = name.charAt(0);
System.out.println(c);
for (int i = 1; i < name.length(); i++) {
char c = name.charAt(i);
if (c == '') {
System.out.println(name.charAt(i - 1));
}
}
}
}
EDIT:
Ok Finally got it. The algorithm is a lot fuzzy but its working and will try to do it next time with Substring..
for (int i = 1; i < temp.length(); i++) {
char c1 = temp.charAt(i);
if (c1 == ' ') {
System.out.print(temp.charAt(i + 1));
System.out.print(".");
}
}
Thanks a lot guys :)
This works for me
public static void main(String[] args) {
Pattern p = Pattern.compile("((^| )[A-Za-z])");
Matcher m = p.matcher("Some Persons Name");
String initials = "";
while (m.find()) {
initials += m.group().trim();
}
System.out.println(initials.toUpperCase());
}
Output:
run:
SPN
BUILD SUCCESSFUL (total time: 0 seconds)
Simply use a regex:
keep only characters that are following a whitespace
remove all remaining whitespace and finally
make it upper case:
" Foo Bar moo ".replaceAll("([^\\s])[^\\s]+", "$1").replaceAll("\\s", "").toUpperCase();
=> FBM
I will do something like this:
Remember, you only need the inicial characters
public staticvoid main (String[] args){
String name;
System.out.println("Enter your complete name");
Scanner input = new Scanner(System.in);
name = input.nextLine();
System.out.println("Your name is: "+name);
name=" "+name;
//spacebar before string starts to check the initials
String ini;
// we use ini to return the output
for (int i=0; i<name.length(); i++){
// sorry about the 3x&&, dont remember the use of trim, but you
// can check " your name complete" if " y"==true y is what you want
if (name.charAt(i)==" " && i+1 < name.length() && name.charAt(i+1)!=" "){
//if i+1==name.length() you will have an indexboundofexception
//add the initials
ini+=name.charAt(i+1);
}
}
//after getting "ync" => return "YNC"
return ini.toUpperCase();
}
If you care about performance (will run this method many times), the extra charAt(i+1) isn't needed and is relatively costly.
Also, it'll break on texts with double spaces, and will crash on names that end with a space.
This is a safer and faster version:
public String getInitials(String name) {
StringBuilder initials = new StringBuilder();
boolean addNext = true;
if (name != null) {
for (int i = 0; i < name.length(); i++) {
char c = name.charAt(i);
if (c == ' ' || c == '-' || c == '.') {
addNext = true;
} else if (addNext) {
initials.append(c);
addNext = false;
}
}
}
return initials.toString();
}
public String getInitials() {
String initials="";
String[] parts = getFullName().split(" ");
char initial;
for (int i=0; i<parts.length; i++){
initial=parts[i].charAt(0);
initials+=initial;
}
return(initials.toUpperCase());
}

Printing initials of user input name of any length along with full surname in java

I am new to java and I have been trying to solve a problem which I feel might have a simpler answer than my code.The problem was to print the initials of a user input name of any length along with the full surname.But this has to be done without any String.split() or arrays.I tried getting the user to input his name one word at a time, but is there any there a possible way to get the whole name at once and do as required.
My code is as follows:
import java.io.*;
public class Initials {
public static void main(String[]args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of words your name contains");
int n=Integer.parseInt(br.readLine());
String str="";
for(int x=1;x<=n-1;x++){
System.out.println("Enter your name's word number:"+" "+x);
String s=br.readLine();
String st=s.toUpperCase();
char ch=st.charAt(0);
str=str+ch+".";
}
System.out.println("Enter your surname");
String sur=br.readLine();
str=str+" "+sur.toUpperCase();
System.out.println(str);
}
}
Use a regular expression (namely (?<=\w)\w+(?=\s)):
String name = "John Paul Jones"; // read this from the user
System.out.println(name.replaceAll("(?<=\\w)\\w+(?=\\s)", "."));
J. P. Jones
No split(), no arrays :)
A little explanation: We essentially want to replace all letters of each word that is followed by a whitespace character except the first letter, with a . character. To match such words, we use (?<=\w)\w+(?=\s):
(?<=\w) is a positive lookbehind; it checks that a word-character exists at the start of the match but does not include it in the match itself. We have this component because we don't want to match the first character of each name, but rather all but the first (except for the last name, which we'll deal with shortly).
\w+ matches any continuous string of word characters; we use this to match the rest of the name.
(?=\s) is a positive lookahead; it checks that our match is followed by a whitespace character, but does not include it in the match itself. We include this component because we don't want to replace anything on the last name, which should not be followed by a whitespace character and hence should not match the regular expression.
Another way around---
import java.util.Scanner;
//a class that will print your output
class Initial {
public void Initials() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Full name:");
String name = sc.nextLine();
int l = name.length();
int pos = 0;
for (int i = l - 1; i >= 0; i--) {
char ch = name.charAt(i);
if (ch == ' ') {
pos = i; //getting the last space before Surname
break;
}
}
System.out.print("The initials are: ");
System.out.print(name.charAt(0) + ".");//prints first name initial
// with dot
for (int x = 1; x < pos; x++) //finds midname initial
{
char ch = name.charAt(x);
if (ch == ' ') {
System.out.print(name.charAt(x + 1) + ".");
}
}
for (int i = pos; i < l; i++) { //for printing Surname
System.out.print(name.charAt(i));
}
}
}
public class Str {
public static void main(String[] args) {
Initial i = new Initial();
i.Initials();
}
}
//This code will work for any no. of words in the name
class Surnam {
public static void main(String name) {
name = " " + name;
int l=name.length(), p=0, m=0, r=0;
char y;
String word=" ", words=" ";
for(int i = 0; i = 0; i--) {
y=name.charAt(i);
if(y==' ') {
r=name.lastIndexOf(y); //extracting the last space of the string
word=name.substring(i,l); //extracting the surname
words=name.replace(word," "); //removing the surname break;
}
}
for (int i = 0; i <= r - 1; i++) {
char x=words.charAt(i);
if (x == ' ') {
System.out.print(words.charAt(i + 1) + "."); //Printing all initials before the surname with a dot
}
}
for (int i = l - 1; i >= 0; i--) {
char x=name.charAt(i);
if(x==' ') {
m=i;
name=name.substring(m,l); //extracting the surname
name=name.trim(); //removing all the spaces before the surname
System.out.print(name);
break;
}
}
}
}

How to count the key characters?

I have the following code:
import java.util.Scanner;
public class chara{
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.println("Input a string");
String user=input.nextLine();
if(user.length()<7)
{
return;
}
else
{
}
System.out.println("now input a letter to be replaced");
String letter = input.next();
String user2 = user.replace(letter, "-");
String user3 = user.replace(letter, "");
System.out.println(user2);
System.out.println(user3);
}
}
the code needs to do three things take a string and a letter and :
replace the key letter in the string with "-"
remove the key letter of the string
count the amount of times the key letter appears.
At present I have two problems. I don't know how to count the amount of times the letter
appears because technically it is a string and not a char and i do not know how to count
strings. Second, I need to make it so that if the strings are not of the desired length it
simply asks again instead of exiting the program. I have tried to use the getString() method but for some reason it always says that the method is undefined.
For issue #1:
Near the top of the main method:
int count = 0;
After user3 is assigned:
count += (user3.length() - user.length());
With full credit to user1324109 for their solution to issue #1, here is how you can solve your issue #2:
import java.util.Scanner;
public class StringReader {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String user1 = "", user2 = "", user3 = "";
int count = 0;
while(user1.equals("") || user1.length() < 7) {
System.out.println("Input a string");
user1 = input.nextLine();
}
if(!user1.equals("")) {
System.out.println("now input a letter to be replaced");
String letter = input.next();
user2 = user1.replace(letter, "-");
user3 = user1.replace(letter, "");
System.out.println(user2);
System.out.println(user3);
count += (user1.length() - user3.length());
System.out.println("letter was found to be present "+count+" times");
}
}
}
To help with issue #3:
int count = 0;
for(char c : user.toCharArray() ){
if ( c == letter.charAt(0)) count++;
}
System.out.println("Number of occurences: "+count);

Categories