The problem is :
Write a program that read form user 2 full names, and then decide if the 2 are brothers or not.
Sample Run:
Enter 2 names:
- First name: Ali Ibrahim Mohammed
- Second name: Ahmad Ibrahim Mohammed
Ali and Ahmad are brothers
import java.util.*;
public class Test
{
static Scanner scan = new Scanner (System.in);
public static void main(String args[])
{
String name1 = ""; //the name1 without first name
String name2 = ""; //the name2 without first name
String firstname1="";//only the first name of name1
String firstname2="" ;//only the fist name of name2
String fname ="";
String lname ="";
String string, string2;
int space ;
int i =0;
int j=0;
System.out.println("Enter 2 names :");
while ( i<2 )
{
if (i==0)
System.out.println("- First name :");
else
System.out.println("- Second name :");
while (j==i)
{
string = scan.nextLine();
space= string.indexOf(" ");
fname = string.substring(0,space);
string2 = string.toLowerCase();
lname = string.substring(space);
string2 = lname.toLowerCase();
j++;
}
if(i==0){
firstname1=fname;
lname=name1;
}
else if(i==1){
firstname2=fname;
lname=name2;
}
i++;
}
if ( name1.equals(name2))
System.out.println(firstname1 + " and " + firstname2 + " are brothers ");
else
System.out.println(firstname1 + " and " + firstname2 + " are NOT brothers ");
}
}
I tried to write my code, but they are always brothers even if the last name is not the same!
Try to split your problem into smaller problems, and code each. For example,
How should you represent a person's name? Does everyone have a first, middle, and last name? What happens if someone types just George Booth?
Can you write a Name class?
What would be a better set of variable names?
How would you test your code?
Also, try not to do everything in main. It makes things hard to test.
I think you want
if ( lname1.equals(lname2))
instead of
if ( name1.equals(name2))
There may be other problems, but this is at least one of them.
I implemented this using a tokenizer, with this approach the program is able to find if multiple people are brothers. How this works is we store the person full name in an ArrayList. We then break up those name using a tokenizer and store only the lastname into a new array. We then check for everybody that have the same last name and display that they are brothers.
List<String> names = new ArrayList <String>();
Scanner scanner = new Scanner(System.in);
//gets user name
for (int x = 0; x < 4; x++)
{
System.out.printf("Enter Full Name #%d: ", (x + 1));
names.add(scanner.nextLine());
}
String [] lastName = new String [names.size()];
//gets lastName
for (int x = 0; x < names.size(); x++)
{
StringTokenizer token = new StringTokenizer(names.get(x));
while (token.hasMoreTokens())
lastName[x] = token.nextToken();
}
//check for brothers
for (int x = 0; x < names.size(); x++)
for (int i = x + 1; i < names.size();i++)
{
if (lastName[x].equalsIgnoreCase(lastName[i]))
System.out.printf("%s and %s are brothers",names.get(x),names.get(i));
}
Output:
Enter Full Name #1: Andree Freemantle
Enter Full Name #2: Mario Dennis
Enter Full Name #3: Kyle Freemantle
Enter Full Name #4: Steve dennis
Andree Freemantle and Kyle Freemantle are brothers
Mario Dennis and Steve dennis are brother
Please refer to below modified version your code, hope this solves your issue.
public static void main(String[] args) {
String n1="Ali Ibrahim Mohammed";
String n2="Ahmad Ibrahim Mohammed";
String name1FirstName=n1.split(" ")[0];
String name2FirstName=n2.split(" ")[0];
String name1LastName=n1.split(" ")[2];
String name2LastName=n2.split(" ")[2];
String name1MiddleName=n1.split(" ")[1];
String name2MiddleName=n2.split(" ")[1];
if(name1LastName.equals(name2LastName)){ // Check if Last name is same or not
if(name1MiddleName.equals(name2MiddleName)){ // Check if middle name is same or not
System.out.println(name1FirstName+" and "+name2FirstName+" are brothers");
}else{
System.out.println(name1FirstName+" and "+name2FirstName+" are not brothers");
}
}else{
System.out.println(name1FirstName+" and "+name2FirstName+" are not brothers");
}
}
import java.util.*;
class Test
{
static Scanner scan = new Scanner (System.in);
public static void main(String args[])
{
//String name1 = ""; //the name1 without first name
//String name2 = ""; //the name2 without first name
String firstname1="";//only the first name of name1
String firstname2="" ;//only the fist name of name2
String fname ="";
String lname ="";
String lname1 ="";
String lname2 ="";
String string, string2;
int space ;
int i =0;
int j=0;
System.out.println("Enter 2 names :");
while ( i<2 )
{
if (i==0)
System.out.println("- First name :");
else
System.out.println("- Second name :");
while (j==i)
{
string = scan.nextLine();
space= string.indexOf(" ");
fname = string.substring(0,space);
string2 = string.toLowerCase();
lname = string.substring(space);
string2 = lname.toLowerCase();
j++;
}
if(i==0){
firstname1=fname;
lname1=lname;
}
else if(i==1){
firstname2=fname;
lname2=lname;
}
i++;
}
if ( lname1.equals(lname2))
System.out.println(firstname1 + " and " + firstname2 + " are brothers ");
else
System.out.println(firstname1 + " and " + firstname2 + " are NOT brothers ");
}
}
output:--
Enter 2 names :
- First name :
Ali Ibrahim Mohammed
- Second name :
Ahmad Ibrahim Mohammed
Ali and Ahmad are brothers
retry:==
Enter 2 names :
- First name :
Ahmad Ibrahim
- Second name :
Ali Ibrahim Mohammed]
Ahmad and Ali are NOT brothers
Related
Hi I have a password generator and I have it mostly figured out. The only issue I am having is that when I print out my reversed string instead of printing the 2nd to last like I need. But it prints both of the last 2 letters of the first name. Here is the code:
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter first name here: ");
String fname = input.next();
System.out.println("enter middle name here: ");
String mname = input.next();
System.out.println("Enter last name here: ");
String lname = input.next();
System.out.println("Enter birthday (MMDDYYYY) here: ");
int age = input.nextInt();
lname = lname.substring(lname.length()-3);
char resultfn = fname.charAt(1);
char resultmn = mname.charAt(2);
fname = fname.substring(fname.length()-2);
System.out.print(resultfn);
System.out.print(resultmn);
System.out.print(lname);
System.out.print(fname);
}
}
Ok so I figured it out what i did was add a new line of code which was
char reversedfn = fname.charAt(0);
after I did that it worked great!
I put it after the
fname = fname.substring(fname.length()-2);
and then had it print out the reversedfn line and it came out to the letter i needed. So it now looks like this.
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter first name here: ");
String fname = input.next();
System.out.println("enter middle name here: ");
String mname = input.next();
System.out.println("Enter last name here: ");
String lname = input.next();
System.out.println("Enter birthday (MMDDYYYY) here: ");
int age = input.nextInt();
lname = lname.substring(lname.length()-3);
char resultfn = fname.charAt(1);
char resultmn = mname.charAt(2);
fname = fname.substring(fname.length()-2);
char reversedfn = fname.charAt(0);
System.out.print(resultfn);
System.out.print(resultmn);
System.out.print(lname);
System.out.print(reversedfn);
}
}
This question already has answers here:
Remove specific string from arraylist elements containing a particular subsrtring
(5 answers)
Closed 3 years ago.
I want to remove this whole single input by just having the user type in the Lisence Plate Number which would be a unique number.
The String would print out something like "Car Ford F1 LC4PR0 Black"
Is there a way to find "LC4PR0" only and delete this whole String?
public static void Add_Vehicle(ArrayList<String> list){
int listsize = list.size();
if(listsize == 50){
System.out.println("Vehicle Garage Full! 50/50 Vehicles");
}
else{
Scanner input = new Scanner(System.in);
System.out.println("Enter Vehicle Type. Car/Motorbike");
String VehicleType = input.nextLine().toUpperCase();
if(VehicleType.equals("CAR")){
String VehicleCar = "Car";
System.out.println("Enter Vehicle Make");
String CarMake = input.nextLine();
System.out.println("Enter Vehicle Model");
String CarModel = input.nextLine();
System.out.println("Enter Vehicle Lisence Plate.");
String CarPlate = input.nextLine();
System.out.println("Enter Vehicle Colour");
String CarColour = input.nextLine();
String CarDetails = VehicleCar + " " + CarMake + " " + CarModel + " " + CarPlate + " " + CarColour;
list.add(CarDetails);
}
else if(VehicleType.equals("MOTORBIKE")){
String VehicleMotorbike = "Car";
System.out.println("Enter Vehicle Make");
String MotorbikeMake = input.nextLine();
System.out.println("Enter Vehicle Model");
String MotorbikeModel = input.nextLine();
System.out.println("Enter Vehicle Lisence Plate.");
String MotorbikePlate = input.nextLine();
System.out.println("Enter Vehicle Colour");
String MotorbikeColour = input.nextLine();
String MotorbikeDetails = VehicleMotorbike + " " + MotorbikeMake + " " + MotorbikeModel + " " + MotorbikePlate + " " + MotorbikeColour;
list.add(MotorbikeDetails);
}
else{
System.out.println("Please Only Enter Vehicle Type, Car or Motorbike!");
}
Menu(list);
}
}```
If you know the specific pattern of License Plate you can use regex to find all the ocurrence.
Use String#split(String).
Split slice string to string array with parameter.
As example, "test test2 test3".split(" ") returns {"test","test2","test3"}.
See code below.
Java 7
public String search(String target){
for(String n : list){
String[] split = n.split(" ");
if(split[3].equals(target)){
return split[3]; // Return n if you want to return all string
}
// Cannot find target
return null;
}
Java 8
public String search(String str){
List<String> lst = list.filter(s -> s.split(" ")[3].equals(str)).collect(Collectors.toList());
return lst.size() == 0 ? null : lst.get(0).split(" ")[3]; // Do not split if you want to return all string
}
The procedure of this code must be looping until 1000 applicants enter their name and gender but it stopped at the first applicant. Please help me find out what's going on. I tried different ways but it didn't work.
Here's the code:
import java.util.Scanner;
public class Problem5 {
public static void main (String [] args)
{
Scanner myVar = new Scanner (System.in);
int b = 1000;
String [] name = new String [b];
/*enter name and gender of applicants*/
for (int i=0; i<name.length; i++)
{
int index = i;
System.out.println("Enter name of applicant and gender:");
System.out.println("M for male and F for female");
name[index] = myVar.nextLine();
for (String name1:name)
{
int maleCount = 0;
int femaleCount = 0;
if (name1.contains("M"))
{
maleCount++;
}
if (name1.contains("F"))
{
femaleCount++;
}
System.out.println("NUMBER OF MALE: "+maleCount);
System.out.println("NUMBER OF FEMALE: "+femaleCount);
}
}
}
}
The result must look like this.
For example, I type my name Isabella Cruz and my gender F.
Enter name of applicant and gender:
M for male and F for female
Isabella Cruz F
NUMBER OF MALE: 0
NUMBER OF FEMALE: 1
But, it stops there and an error came:
Exception in thread "main" java.lang.NullPointerException
at Problem5.main(Problem5.java:30)
I need solutions for this, please.
name has "Isabella Cruz F" in index 0 and the rest of the array is nulls, so name1 is null in the second iteration. Take the second loop out of the first one.
for (int i = 0; i < name.length; i++) {
//...
}
for (String name1 : name) {
//...
}
You can also use only one loop and get the data there
int maleCount = 0;
int femaleCount = 0;
for (int i = 0; i < name.length; i++)
{
int index = i;
System.out.println("Enter name of applicant and gender:");
System.out.println("M for male and F for female");
name[index] = myVar.nextLine();
if (name[index].contains("M")) {
maleCount++;
}
else if (name[index].contains("F")) {
femaleCount++;
}
}
System.out.println("NUMBER OF MALE: " + maleCount);
System.out.println("NUMBER OF FEMALE: " + femaleCount);
There is couple issues. First is there is a nested for loop. I see that you are populating the String array first then iterating over it to check for the count. You really only need one loop. Second is that you are checking if the String contains "M" or "F" which may be problematic if the persons name contains that String(Ex Joanna M Smith F). You only need to check the last character.
import java.util.Scanner;
public class Problem5 {
public static void main (String [] args)
{
Scanner myVar = new Scanner (System.in);
int b = 1000;
String [] names = new String [b];
int maleCount = 0;
int femaleCount = 0;
/*enter name and gender of applicants*/
for (int i=0; i<name.length; i++)
{
System.out.println("Enter name of applicant and gender:");
System.out.println("M for male and F for female");
String line = myVar.nextLine();
names[i] = line;
// check if the line passed in is a M or F
if (line.substring(line.length()-1).equals("M"))
{
maleCount++;
}
if (line.substring(line.length()-1).equals("F"))
{
femaleCount++;
}
System.out.println("NUMBER OF MALE: "+maleCount);
System.out.println("NUMBER OF FEMALE: "+femaleCount);
}
}
}
How to get the First Name Friend
But here I want to take the first name even though its input there is a last name with spaces
Example :
First friend
I Input the name : Alvin Indra
Second Friend
I Input the name : Redi Rusmana
And output :
Alvin
Redi
Please help me
Syntax :
package latihan;
import java.util.Scanner;
public class LatihanArray {
public static void main(String[] args) {
int many;
String[] friend = new String[100];
Scanner sc = new Scanner(System.in);
Scanner scx = new Scanner(System.in);
System.out.print("Enter How Many Friends : ");
many = sc.nextInt();
for(int i=0;i<n;i++){
System.out.print("Friend Of-"+(i+1)+" : ");
friend[i] = scx.nextLine();
}
System.out.print("\n");
System.out.println("Initials : ");
for(int i=0;i<many;i++){
System.out.println((i+1)+". "+friend[i].charAt(0));
}
System.out.print("\n");
System.out.println("4 Letterhead : ");
for(int i=0;i<n;i++){
System.out.println((i+1)+". "+friend[i].substring(0,4));
}
System.out.println("First Name : ");
for(??????){
if(??????){
for(????????){
???????????????;
}
}
}
}
}
You enter friend's name as a string "<firstName> <lastName>" (with space symbol between parts). In case you want to store it as one String, you can use following methods:
Regular expression: (?<firstName>\w+)\s+(?<lastName>\w+) and get both parts directly
Split string with space: String[] parts = friend.split("\s+") and get parts[0] as first name, and parts[1] as last name
But I strongly recommend you to use special class to store input data, because in general case, if you need post processing, it is much better to prepare all data for it. I give you simple example to show id. You could look at it and maybe use it with some corrections (because I do not know your requirements):
Friend data holder
final class Friend {
private final int id;
private final String firstName;
private final String lastName;
public Friend(int id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public String getInitials() {
return String.valueOf(firstName.charAt(0)) + lastName.charAt(0);
}
public String getLetterHead() {
return firstName.substring(0, 4);
}
}
Method to read and print data (from your question)
List<Friend> friends = new ArrayList<>();
Scanner scan = new Scanner(System.in);
System.out.print("Enter How Many Friends : ");
int many = scan.nextInt();
for (int i = 0; i < many; i++) {
System.out.print("Friend Of-" + (i + 1) + " : ");
String firstName = scan.next();
String lastName = scan.next();
friends.add(new Friend(i + 1, firstName, lastName));
}
scan.close();
System.out.println("\nInitials: ");
for (Friend friend : friends)
System.out.println(String.format("%d. %s", friend.id, friend.getInitials()));
System.out.println("\n4 Letterhead: ");
for (Friend friend : friends)
System.out.println(String.format("%d. %s", friend.id, friend.getLetterHead()));
System.out.println("\nFirst Name: ");
for (Friend friend : friends)
System.out.println(String.format("%d. %s", friend.id, friend.firstName));
System.out.println("\nLast Name: ");
for (Friend friend : friends)
System.out.println(String.format("%d. %s", friend.id, friend.lastName));
}
}
As result you see following in console:
Enter How Many Friends : 2
Friend Of-1 : Alvin Indra
Friend Of-2 : Redi Rusmana
Initials:
1. AI
2. RR
4 Letterhead:
1. Alvi
2. Redi
First Name:
1. Alvin
2. Redi
Last Name:
1. Indra
2. Rusmana
I need to use first three letters of actual first name + first two letters of actual last name, and first two letters of mother's maiden name + first three letters of birth city. I also need to have the first letter be capitalized. Using toUpperCase() and toLowerCase(). Thanks!
import java.util.Scanner;
public class Assignment2
{
public static void main(String[] args)
{
System.out.printf("Enter your first name: ");
/* This should be string as your gettting name*/
String firstname = input.nextLine();
firstname = firstname.substring(0, 1).toUpperCase() + firstname.substring(1);
/* Don't need new variable use same and that also should be string. */
System.out.printf("Enter your last name: ");
String lastname = input.nextLine();
lastname = lastname.substring(0,2). toUpperCase() + lastname.substring(1);
System.out.printf("Enter your mother's maiden name: ");
String mothersname = input.nextLine();
mothersname = mothersname.substring(0,2);
System.out.printf("Enter the name of the city in which you were born: ");
String cityname = input.nextLine();
cityname = cityname.substring(0,3);
String StarWarsName = firstname+lastname+mothersname+cityname;
System.out.println("May the force be with you, " + StarWarsName );
}
}
//* Updated code
import java.util.Locale;
import java.util.Scanner;
public class Assignment2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.printf("Enter your first name: ");
String firstname = input.nextLine();
firstname = firstname.substring(0, 1).toUpperCase() + firstname.substring(1).toLowerCase();
System.out.printf("Enter your last name: ");
String lastname = input.nextLine();
lastname = lastname.substring(0,1). toUpperCase() + lastname.substring(1).toLowerCase();
System.out.printf("Enter your mother's maiden name: ");
String mothersname = input.nextLine();
mothersname = mothersname.substring(0,2);
System.out.printf("Enter the name of the city in which you were born: ");
String cityname = input.nextLine();
cityname = cityname.substring(0,3);
String StarWarsName = firstname+lastname+" "+mothersname+cityname;
System.out.println("May the force be with you, " + StarWarsName );
}
}
Corrected the code and explained the changes in comments. Go through comments also. Don't just copy this code.
import java.util.Scanner;
public class test1
{
public static void main(String[] args)
{
Scanner input = new Scanner();
System.out.printf("Enter your first name: ");
/* This should be string as your gettting name*/
String firstname = input.nextLine();
/* Don't need new variable use same and that also should be string. */
firstname = firstname.substring(0,1);
System.out.printf("Enter your last name: ");
String lastname = input.nextLine();
lastname = lastname.substring(0,2);
System.out.printf("Enter your mother's maiden name: ");
String mothersname = input.nextLine();
mothersname = mothersname.substring(0,1);
System.out.printf("Enter the name of the city in which you were born: ");
String cityname = input.nextLine();
cityname = cityname.substring(0,2);
String StarWarsName = ( "firstname" + "lastname " + "mothersname " + "cityname");
System.out.println("May the force be with you, " + StarWarsName );
}
}
firstname cannot be resolved to a variable
You didn't declare firstname. Not only firstname you didn't declare lastname, mothersname, cityname. So you should declare all. Those should be String.
You didn't create Scanner object. Create Scanner class object.
Scanner input = new Scanner(System.in);
Next change. You declared cityname as two times and as inttype. But nextLine() returns String not int.
String cityname = input.nextLine();//returns String, not int
cityname = city.substring(0,3);//returns the first 3 characters as String, not int
String#substring() returns String not int. So check the entire code.
Change
String StarWarsName = ( "firstname" + "lastname " + "mothersname " + "cityname");
to
String StarWarsName = firstname+lastname+" "+mothersname+cityname;
All these are variables not values. So don't put in double quotes.
Edit: Capitalize the first letter of firstname
firstname = firstname.substring(0, 1).toUpperCase() + firstname.substring(1).toLowerCase();