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
Related
Basically, I just tried to learn linked lists but I can't seem to understand how to insert a bunch of data from different variables into it. Does it work as an array/ ArrayList? Before we end the loop we are supposed to store the data right, but how??
Let say I have variables ( name, age, phonenum).
'''
char stop='Y';
while(stop!='N'){
System.out.println("\nEnter your name : ");
int name= input.nextLine();
System.out.println("\nEnter your age: ");
int age= input.nextInt();
System.out.println("\nEnter your phone number: ");
int phonenum= input.nextLine();
System.out.println("Enter 'Y' to continue, 'N' to Stop: ");
stop = sc.nextLine().charAt(0);
}
'''
First, change your code to use appropriate types. Name and phone should be of type String, not int.
Define a class to hold your fields. Records are an easy way to do that.
record Person ( String name , int age , String phone ) {}
Declare your list to hold objects of that class.
List< Person > list = new LinkedList<>() ;
Instantiate some Person objects, and add to list.
list.add( New Person( "Alice" , 29 , "477.555.1234" ) ) ;
In the line above, I hard-coded some example data. In your own code, you will be passing to the constructor the variables you populated by interacting with the user.
list.add( New Person( name , age , phonenum ) ) ;
You can create an object which has name, age and phenomenon then create an insert method which you call in your while loop.
In psuedo code it would look something like this:
public class Data {
String name;
int age;
int phenomenon;
//constructor
//getters & setters
}
This class above will hold contain the user input. You can gather all the user input and store it in an array and perform the insert with array of data instead of inserting one object at a time
public void InsertData(LinkedList<Data> list, Arraylist<Data> input) {
for(Data d: input){
list.add(d);
}
}
You can read up on linkedlists a bit more here to understand how exactly linkedlists work and implement your own from scratch: https://www.geeksforgeeks.org/implementing-a-linked-list-in-java-using-class/
Try this
Possibility : 1
import java.util.*;
public class Naddy {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char stop = 'Y';
LinkedList<Object> list = new LinkedList<Object>();
while (stop != 'N') {
System.out.println("\nEnter your name : ");
String name = input.nextLine();
System.out.println("\nEnter your age: ");
int age = input.nextInt();
System.out.println("\nEnter your phone number: ");
long phonenum = input.nextLong();
list.add(name);
list.add(age);
list.add(phonenum);
System.out.println("Enter 'Y' to continue, 'N' to Stop: ");
input.nextLine();
stop = input.nextLine().charAt(0);
}
System.out.println(list);
}
}
possibility : 2
import java.util.*;
public class Naddy {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char stop = 'Y';
LinkedList<User> list = new LinkedList<User>();
while (stop != 'N') {
System.out.println("\nEnter your name : ");
String name = input.nextLine();
System.out.println("\nEnter your age: ");
int age = input.nextInt();
System.out.println("\nEnter your phone number: ");
long phonenum = input.nextLong();
list.add(new User(name, age, phonenum));
System.out.println("Enter 'Y' to continue, 'N' to Stop: ");
input.nextLine();
stop = input.nextLine().charAt(0);
}
System.out.println(list);
}
}
class User {
private String name;
private int age;
private long phonenum;
public User() {
}
public User(String name, int age, long phonenum) {
this.name = name;
this.age = age;
this.phonenum = phonenum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public long getPhonenum() {
return phonenum;
}
public void setPhonenum(long phonenum) {
this.phonenum = phonenum;
}
#Override
public String toString() {
return "User [age=" + age + ", name=" + name + ", phonenum=" + phonenum + "]";
}
}
The program described here should be implemented in the class PersonalInformationCollection. NB! Do not modify the class PersonalInformation.
After the user has entered the last set of details (they enter an empty first name), exit the repeat statement.
Then print the collected personal information so that each entered object is printed in the following format: first and last names separated by a space (you don't print the identification number). An example of the working program is given below:
Sample output
First name: Jean
Last name: Bartik
Identification number: 271224
First name: Betty
Last name: Holberton
Identification number: 070317
First name:
Jean Bartik
Betty Holberton
The PersonalInformation class:
public class PersonalInformation {
private String firstName;
private String lastName;
private String identificationNumber;
public PersonalInformation(String firstName, String lastName, String identificationNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.identificationNumber = identificationNumber;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getIdentificationNumber() {
return identificationNumber;
}
#Override
public String toString() {
return this.lastName + ", " + this.firstName + " (" + this.identificationNumber + ")";
}
}
My solution which I can only print all values instead of only Firstnames and the Lastnames from the array:
public class Main {
public static void main(String[] args) {
// write your code here
Scanner scanner = new Scanner(System.in);
ArrayList<PersonalInformation> infoCollection = new ArrayList<>();
while (true) {
System.out.println("First name: ");
String firstName = scanner.nextLine();
if (firstName.equals("")) {
break;
}
System.out.println("Last name: ");
String lastName = scanner.nextLine();
System.out.println("Identification number: ");
String identificationNumber = scanner.nextLine();
infoCollection.add(new PersonalInformation(firstName, lastName, identificationNumber));
}
System.out.println(infoCollection);
}
}
I need to modify the code. I am a beginner, an explanatory suggestion would be much appreciated.
Instead of
System.out.println(infoCollection);
you´ll have
infoCollection.stream().forEach(p -> System.out.println(p.getFirstName() + " " + p.getLastName()));
public class Main {
public static void main(String[] args) {
// write your code here
ArrayList<PersonalInformation> infoCollection = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("First name: ");
String firstName = scanner.nextLine();
if (firstName.equals("")) {
break;
}
System.out.println("Last name: ");
String lastName = scanner.nextLine();
System.out.println("Identification number: ");
String identificationNumber = scanner.nextLine();
infoCollection.add(new PersonalInformation(firstName, lastName, identificationNumber));
}
for (int i = 0; i < infoCollection.size(); i++) {
System.out.println(infoCollection.get(i).getFirstName() + " "
+ infoCollection.get(i).getLastName());
}
}
}
After the while statement, to print just the first and last names, try:
for (int i = 0; i < infoCollection.size(); i++) {
System.out.println(infoCollection.get(i).getFirstName() + " " + infoCollection.get(i).getLastName());
}
for (PersonalInformation personalInformation: infoCollection) {
System.out.println(personalInformation.getFirstName() + ' ' +
personalInformation.getLastName());
}
This question already has answers here:
How to compare two java objects [duplicate]
(5 answers)
Closed 6 years ago.
For some reason, in my Pseudo database, my remove method seems to be completely ineffective and isn't working. The source code is below:
import java.util.ArrayList;
import java.util.Scanner;
public class Lab2 {
static ArrayList<Person> peopleDirectory = new ArrayList<Person>(10);
public static void main(String[] args) {
// TODO Auto-generated method stub
int choice;
Scanner userInput = new Scanner(System.in);
do {
System.out.println("Welcome to the people directory please make a choice from the list below:");
System.out.println("-------------------------------------------------------------------------");
System.out.println("1. Add a person to the directory.");
System.out.println("2. Remove a Person from the directory.");
System.out.println("3. View the User Directory.");
System.out.println("4. Exit the directory.");
choice = userInput.nextInt();
switch(choice) {
case 1:
addPerson(new Person());
break;
case 2: removePerson(new Person());
break;
case 3: displayPeople();
break;
case 4: System.out.println("Thanks for using the people diretory!");
System.exit(0);
break;
default: System.out.println("Invalid choice! Please select a valid choice!");
break;
}
} while (choice != 4);
}
public static void addPerson(Person thePerson) {
String firstName;
String lastName;
String phoneNumber;
int age;
if (peopleDirectory.size() >= 10) {
System.out.println("Sorry the list can not be larger than 10 people");
} else {
int i = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter the first name of the Person you would like to add: ");
firstName = input.nextLine();
thePerson.setFirstName(firstName);
System.out.println("Enter the last name of the Person you would like to add: ");
lastName = input.nextLine();
thePerson.setLastName(lastName);
System.out.println("Enter the phone number of the Person you would like to add: ");
phoneNumber = input.nextLine();
thePerson.setPhoneNumber(phoneNumber);
System.out.println("Enter the age of the Person you would like to add: ");
age = input.nextInt();
thePerson.setAge(age);
peopleDirectory.add(i, thePerson);
i++;
}
}
public static void removePerson(Person thePerson) {
if (peopleDirectory.size() < 1) {
System.out.println("There is absolutely nothing to remove from the Directory");
}
else {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the first name of the person you would like to delete: ");
String firstName = input.nextLine();
thePerson.setFirstName(firstName);
System.out.println("Enter the last name of the Person you would like to remove: ");
String lastName = input.nextLine();
thePerson.setLastName(lastName);
System.out.println("Enter the phone number of the Person you would like to remove: ");
String phoneNumber = input.nextLine();
thePerson.setPhoneNumber(phoneNumber);
System.out.println("Enter the age of the Person you would like to remove: ");
int age = input.nextInt();
thePerson.setAge(age);
for (int i = 0; i < peopleDirectory.size(); i++) {
if (peopleDirectory.get(i).equals(thePerson)) {
peopleDirectory.remove(thePerson);
}
}
}
}
public static void displayPeople() {
for (Person person : peopleDirectory) {
System.out.println("First Name: " + person.getFirstName() + " Last name: " +
person.getLastName() + " Phone number: " + person.getPhoneNumber() +
" Age: " + person.getAge());
}
}
}
class Person {
private String firstName;
private String lastName;
private int age;
private String phoneNumber;
public Person (String firstName, String lastName, int personAge, String phoneNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.age = personAge;
this.phoneNumber = phoneNumber;
}
public Person() {
this.firstName = "";
this.lastName = "";
this.age = 0;
this.phoneNumber = "";
}
public int getAge() {
return this.age;
}
public String getFirstName() {
return this.firstName;
}
public String getLastName() {
return this.lastName;
}
public String getPhoneNumber() {
return this.phoneNumber;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setAge(int age) {
this.age = age;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
When I attempt to remove an element from the ArrayList, it still remains in the arrayList. I have no idea why, but I feel as if my remove method is a bit clunky.
For instance I add an element and attempt to remove it (see output below):
Welcome to the people directory please make a choice from the list below:
-------------------------------------------------------------------------
1. Add a person to the directory.
2. Remove a Person from the directory.
3. View the User Directory.
4. Exit the directory.
1
Enter the first name of the Person you would like to add:
Tom
Enter the last name of the Person you would like to add:
Jones
Enter the phone number of the Person you would like to add:
6073388152
Enter the age of the Person you would like to add:
24
Welcome to the people directory please make a choice from the list below:
-------------------------------------------------------------------------
1. Add a person to the directory.
2. Remove a Person from the directory.
3. View the User Directory.
4. Exit the directory.
3
First Name: Tom Last name: Jones Phone number: 6073388152 Age: 24
Welcome to the people directory please make a choice from the list below:
-------------------------------------------------------------------------
1. Add a person to the directory.
2. Remove a Person from the directory.
3. View the User Directory.
4. Exit the directory.
2
Please enter the first name of the person you would like to delete:
Tom
Enter the last name of the Person you would like to remove:
Jones
Enter the phone number of the Person you would like to remove:
6073388152
Enter the age of the Person you would like to remove:
24
Welcome to the people directory please make a choice from the list below:
-------------------------------------------------------------------------
1. Add a person to the directory.
2. Remove a Person from the directory.
3. View the User Directory.
4. Exit the directory.
3
First Name: Tom Last name: Jones Phone number: 6073388152 Age: 24
Welcome to the people directory please make a choice from the list below:
-------------------------------------------------------------------------
1. Add a person to the directory.
2. Remove a Person from the directory.
3. View the User Directory.
4. Exit the directory.
What could I be doing wrong here?
if you want to compare objects should have something like this, complete answer here here !
public boolean equals(Object object2) {
return object2 instanceof MyClass && a.equals(((MyClass)object2).a);
}
or could compare for any specific field of its objects for example
if(peopleDirectory.get(i).getFirstName().equals(thePerson.getFirstName()))
*no need to send a parameter a new Person () could work with a single object class level and only modify their attributes with its setter when you want to perform some operation
nor declare as many Scanner objects if you can work with one for example *
static Scanner userInput = new Scanner(System.in);
to work with a single object could be something
static Person person = new Person();//declaration
and its method add or remove when requesting data entry setteas object attributes created and comparison also perform based on that object
System.out.println("Enter the first name of the Person you would like to add: ");
person.setFirstName(userInput.nextLine());//data entry and setteo
if (peopleDirectory.get(i).equals(person)) // comparation
I have created a simple program which outputs student details. Ideally I would like to give the user an option to add both courses. Will this require a lot of messing about changing code? If not can someone help?
class Student
{
public static void main(String[]args)//The main method; starting point of the program.
{
Scanner input = new Scanner(System.in);
String surName, foreName, courseName;
int age,telephone;
System.out.println("\t\t\t***********************************************");
System.out.println("\t\t\tWelcome to the Mobile College's Student Records");
System.out.println("\t\t\t***********************************************");
System.out.println("\nHow many students would you like to add?");
int noStudents = input.nextInt();
Stu [] TheStu = new Stu [noStudents];
for (int x = 0; x < noStudents; x++)
{
System.out.println("Please enter Surname: ");
surName = input.next();
System.out.println("Please enter Forename: ");
foreName = input.next();
System.out.println("Please enter Age: ");
age = input.nextInt();
System.out.println("Please enter Telephone No. ");
telephone = input.nextInt();
System.out.println("Which course do you want to add the student to? .......Literacy or Numeracy ");
courseName = input.next();
TheStu [x] = new Stu (surName, foreName, age, telephone, courseName);
}
for (int y = 0; y < noStudents; y++)
{
System.out.println("\t\t\t***********************************************");
System.out.println ("\t\t\tName: " + TheStu[y].getfName() + " " + TheStu[y].getsName());
System.out.println ("\t\t\tAge: " + TheStu[y].getstuAge());
System.out.println ("\t\t\tTelephone No. 0" + TheStu[y].getphone());
System.out.println ("\t\t\tEnrolled on the " + TheStu[y].getcourseType() + " Course.");
System.out.println("\t\t\t***********************************************");
}
}// end of class
}
class Stu
{
private String sName;
private String fName;
private int stuAge;
private int phone;
private String courseType;
Stu (String s, String f, int a, int p, String c)
{
sName = s;
fName = f;
stuAge = a;
phone = p;
courseType = c;
}
String getsName()
{
return sName;
}
String getfName()
{
return fName;
}
int getstuAge()
{
return stuAge;
}
int getphone()
{
return phone;
}
String getcourseType()
{
return courseType;
}
}
If you want something pretty basic, you could change your courses into a String array so you could store both courses. Also when asking the user to input a course name, you could have an ALL option, so you automatically register the student for all courses. See below for a slightly modified version of your code :
import java.util.Scanner;
class Student
{
public static void main(String[] args)//The main method; starting point of the program.
{
Scanner input = new Scanner(System.in);
String surName, foreName, courseName;
String[] courses = new String[]{};
int age,telephone;
System.out.println("\t\t\t***********************************************");
System.out.println("\t\t\tWelcome to the Mobile College's Student Records");
System.out.println("\t\t\t***********************************************");
System.out.println("\nHow many students would you like to add?");
int noStudents = input.nextInt();
Stu [] TheStu = new Stu [noStudents];
for (int x = 0; x < noStudents; x++)
{
System.out.println("Please enter Surname: ");
surName = input.next();
System.out.println("Please enter Forename: ");
foreName = input.next();
System.out.println("Please enter Age: ");
age = input.nextInt();
System.out.println("Please enter Telephone No. ");
telephone = input.nextInt();
System.out.println("Which courses do you want to add the student to? .......Literacy or Numeracy or both ");
courseName = input.nextLine();
// change to either upper case or lower case for easy treatment
courseName = courseName.toUpperCase();
// Also verify that the user entered a valid course name
if(courseName.equals("LITERACY")){
courses = new String[]{"LITERACY"};
} else if(courseName.equals("NUMERACY")){
courses = new String[]{"NUMERACY"};
} else if(courseName.equals("BOTH")){
courses = new String[]{"LITERACY", "NUMERACY"};
} else{
System.out.println("Error : You entered an invalid option.... \n This student won't be registered for any courses");
}
TheStu [x] = new Stu (surName, foreName, age, telephone, courses);
}
for (int y = 0; y < noStudents; y++)
{
System.out.println("\t\t\t***********************************************");
System.out.println ("\t\t\tName: " + TheStu[y].getfName() + " " + TheStu[y].getsName());
System.out.println ("\t\t\tAge: " + TheStu[y].getstuAge());
System.out.println ("\t\t\tTelephone No. 0" + TheStu[y].getphone());
System.out.println ("\t\t\tEnrolled in the following courses : ");
courses = TheStu[y].getcourseTypes();
for(int i = 0; i < courses.length; i++){
System.out.println(courses[i]);
}
if(courses.length < 1){
System.out.println("No Courses");
}
System.out.println("\t\t\t***********************************************");
}
}// end of class
}
class Stu
{
private String sName;
private String fName;
private int stuAge;
private int phone;
private String[] courseTypes;
Stu (String s, String f, int a, int p, String[] c)
{
sName = s;
fName = f;
stuAge = a;
phone = p;
courseTypes = c;
}
String getsName()
{
return sName;
}
String getfName()
{
return fName;
}
int getstuAge()
{
return stuAge;
}
int getphone()
{
return phone;
}
String[] getcourseTypes()
{
return courseTypes;
}
}
I tried as much as possible not to make any serious changes to your code as i assume you're a beginner, but there are a lot of changes you could make to improve your code. Happy Coding :)
When you ask for the course name, keep asking until they have entered in a sentinal value. Inside Stu keep an List<String> courseTypes. Store the entered courses in courseTypes. Also, you may want to add a set value to some of the fields in Stu. What if their phone number changes?
I have an assignment that asks me to create students with first name, last name, GPA and major as options the user can input and I am supposed to give these "students" a student ID as well. I can give them an ID in the constructor of one of the classes but I can't seem to iterate through the student count, to give the students the correct type of student id, eg. 123456, 123457, 123458 etc. I am only pasting a few lines because the whole assignment is about 300 lines long and I didn't think anyone cared to read it all over. Can anyone tell me what I'm doing wrong or if this doesn't even make sense to try? I know of another way but I don't like it because it makes me have the student id numbers stored in a separate ArrayList than the other student data and then I would just match up indices. Here's the constructor, with count being initialized as a field with 0...
public Student( String fName, String lName, String maj, double gpa) {
sNumber += count++;
firstName = fName;
lastName = lName;
major = maj;
this.gpa = gpa;
}
Here's the add method from another class....
private static void addStudent(ArrayList<Student> L) {
System.out.println();
Scanner input = new Scanner(System.in);
System.out.print("First name: ");
String uFName = input.nextLine();
System.out.print("Last name: ");
String uLName = input.nextLine();
System.out.print("Major: ");
String studyMaj = input.nextLine();
System.out.print("GPA: ");
double grades = input.nextDouble();
Student newStudent = new Student(uFName, uLName, studyMaj, grades);
L.add(newStudent);
input.close();
}
try this
public Student( String fName, String lName, String maj, double gpa,number ) {
firstName = fName;
lastName = lName;
major = maj;
this.gpa = gpa;
sNumber = number;
}
private static void addStudent(ArrayList<Student> L) {
System.out.println();
Scanner input = new Scanner(System.in);
System.out.print("First name: ");
String uFName = input.nextLine();
System.out.print("Last name: ");
String uLName = input.nextLine();
System.out.print("Major: ");
String studyMaj = input.nextLine();
System.out.print("GPA: ");
double grades = input.nextDouble();
int number=0;
if(l.size()>0){
number=l.get(l.size()-1).getSNumber()+1;
}
Student newStudent = new Student(uFName, uLName, studyMaj, grades,number);
L.add(newStudent);
input.close();
}