Java substring to split up name - java

I am asked to take input from a user, their first and last name in one string.
Then output their name, with their last name first then their first name.
I have finished everything but the part I am stuck on is how to show their first name then their last name, please help.
This is my code so far as requested
package chapter2Codes;
import java.util.Scanner;
public class StPrac1 {
public static void main(String[] args) {
String name;
System.out.println("Please your full name");
Scanner kbd = new Scanner( System.in );
name = kbd.nextLine();
System.out.print(name.substring(5,8) + (", ") + name.substring(0,));
}
}

If Firstname and Lastname are seperated by white-space then try this
var fullname = "Firstname Surname";
var fname = fullname.Split(" ")[0];
var sname = fullname.Split(" ")[1];
string output = sname + ", " + fname;
OR if you want to Avoid middle name
string fullName = "Firstname MidName LastName";
string[] names = fullName.Split(' ');
string fname = names.First();
string lname = names.Last();
string output = lname + ", " + fname;
OR use your delimeter in .Split('addyourdelimeterhere')
AS per your Code
public class StPrac1 {
public static void main(String[] args) {
String name;
System.out.println("Please your full name");
Scanner kbd = new Scanner( System.in );
name = kbd.nextLine();
string fname = name.Split(" ")[0];
string sname = name.Split(" ")[1];
string output = sname + ", " + fname;
System.out.print(output);
}
}
This is just an example not a perfect solution, It will be easy to help you if you can Post more detail

Related

I've trying to use tokenizer to set name and surname

public static Player newPlayer(Integer playerNum){
Player player = new Player();
System.out.println("Player " + (playerNum+1) + " registration");
try {
String fullname = null;
StringTokenizer lineTokens = new StringTokenizer(fullname);
System.out.print("Name: ");
String name = input.readLine();
String surname = input.readLine();
fullname = input.readLine();
player.setName(name + surname);
while (lineTokens.hasMoreTokens()) {
if ( lineTokens.countTokens() >= 0 ) {
name = lineTokens.nextToken();
surname = lineTokens.nextToken();
fullname = (name+" "+surname);
} else {
String checkSpace = lineTokens.nextToken();
for (int i = 0; i < checkSpace.length(); i++) {
if ( checkSpace.charAt(i) == ' ' ) {
break;
}
}
}
}
}catch (IOException e){}
}
I need to set a name and a surname using Tokenizer it is crashing.
P.S I want learn how to use it instead of the split
I didn't understand exactly what you wanted to do, below is a short script to read first and last name from the user, using StringTokenizer
public static void main(String[] args) {
System.out.println("Enter name: <firstName> <lastName>");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
StringTokenizer tokenizer = new StringTokenizer(input, " ");
String firstName = "";
String lastName = "";
if (tokenizer.countTokens() >= 2){
firstName = tokenizer.nextToken();
lastName = tokenizer.nextToken();
}
System.out.println("first name is " + firstName);
System.out.println("last name is " + lastName);
}

Number format exception in java, taking wrong input

When using the code
else if(command.equalsIgnoreCase("add")) {
System.out.println("Enter the Student's Name: ");
String name = input.nextLine();
System.out.println("Enter the Student's Number: ");
String studNum = input.nextLine();
System.out.println("Enter the Student's Address: ");
String address = input.nextLine();
langara.addStudent(name, address, studNum);
System.out.println("A Student added to the College Directory");
}
If the user enters add, it's suppose to go through the above procedure, In the collage class (langara) there is a "addStudent" method :
public void addStudent(String name, String address, String iD) {
Student firstYear = new Student(name, address, iD);
collegeStudents.add(firstYear);
}
And this creates a student object of the student class using the constructor:
public Student(String name, String address, String iD) {
long actualId = Long.parseLong(iD);
studentName = name;
studentID = actualId;
studentAddress = new Address(address);
numberOfQuizzes = 0;
scoreTotal = 0;
}
I'm getting the error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Abernathy, C."
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:589)
at java.lang.Long.parseLong(Long.java:631)
at Student.<init>(Student.java:48)
at College.addStudent(College.java:33)
at CollegeTester.main(CollegeTester.java:53)
It's as if it's trying to convert the Students name to long, but it's supposed to convert the student ID to long..
This is where scanner is created, college is created, and command is initialized:
Scanner input = new Scanner(System.in);
College langara = new College();
String command = "";
System.out.print("College Directory Commands:\n" +
"add - Add a new Student\n" +
"find - Find a Student\n" +
"addQuiz - Add a quiz score for a student\n" +
"findHighest - Find a student with the highest quiz score\n" +
"delete - Delete a Student\n" +
"quit - Quit\n");
command = input.nextLine();
The input is being read from a input.txt file, with each input on it's own line.
The input at the beginning of the file for this command is:
add
Abernathy, C.
10010123
100, West 49 Ave, Vancouver, BC, V7X2K6
What is going wrong here?
It looks right now, but I would swear that when I first looked at this (and copy/pasted your code) that the call to langara.addStudent had the parameters as name, studNum, address. I put this class together with your input file and it appears to work fine:
import java.io.FileInputStream;
import java.util.Scanner;
public class StackOverflow_32895589 {
public static class Student
{
String studentName;
long studentID;
String studentAddress;
long numberOfQuizzes;
long scoreTotal;
public Student(String name, String address, String iD)
{
studentName = name;
studentID = Long.parseLong(iD);
studentAddress = address;
numberOfQuizzes = 0;
scoreTotal = 0;
}
}
public static void main(String[] args)
{
try{
System.setIn(new FileInputStream("c:\\temp\\input.txt"));
}
catch (Exception e)
{
throw new RuntimeException(e);
}
Scanner input = new Scanner(System.in);
String command = input.nextLine();
if (command.equals("add"))
{
System.out.println("Enter the Student's Name:");
String name = input.nextLine();
System.out.println("Enter the Student's Number:");
String studNum = input.nextLine();
System.out.println("Enter the Student's Address:");
String address = input.nextLine();
System.out.println("[" + name + "][" + studNum + "][" + address + "]");
input.close();
addStudent(name, address, studNum);
}
}
public static void addStudent(String name, String address, String iD)
{
Student firstYear = new Student(name, address, iD);
}
}

having trouble compling this code for a starwars name generator

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

Rearranging a string

So my goal is to rearrange a string that is inputted into the program so that it outputs the same info but in a different order. The input order is firstName middleName, lastName, emailAddress and the intended output is lastName, firstName first letter of middleName .
For example the input
John Jack,Brown,JJB#yahoo.com
would output
Brown, John J .
Here's what I have so far
import java.util.Scanner;
public class NameRearranged {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a name like D2L shows them: ");
String entireLine = keyboard.nextLine();
String[] fml = entireLine.split(",");
String newName = fml[0].substring(7);
String newLine = fml[1] + "," + newName + ".";
System.out.println(newLine);
}
public String substring(int endIndex) {
return null;
}
}
I can't figure out how to separate the firstName and middleName so I can substring() the first letter of the middleName followed by a .
This meets your required output.
import java.util.Scanner;
public class NameRearranged {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a name like D2L shows them: ");
String entireLine = keyboard.nextLine();
String[] fml = entireLine.split(","); //seperate the string by commas
String[] newName = fml[0].split(" "); //seperates the first element into
//a new array by spaces to hold first and middle name
//this will display the last name (fml[1]) then the first element in
//newName array and finally the first char of the second element in
//newName array to get your desired results.
String newLine = fml[1] + ", " + newName[0] + " "+newName[1].charAt(0)+".";
System.out.println(newLine);
}
}
Check this.
public class NameRearranged {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a name like D2L shows them: ");
System.out.println(rearrangeName(keyboard.nextLine()));
}
public static String rearrangeName(String inputName) {
String[] fml = inputName.split(" |,"); // Separate by space and ,
return fml[2] + ", " + fml[0] + " " + fml[1].charAt(0) + ".";
}
}
You need to delimit the string for spaces as well. And don't forget the alternate "|" character. Try the following.
String[] fml = entireLine.split(" |, ");

decide if two names are brothers or not

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

Categories