How can I assign data from a file to an array - java

I have a file, which looks like follows:
Barack Obama 3
Michael Jackson 1
Dua Lipa 2
... all of 15 lines
I need to read from a file and place names in a one-dimensional array and integers into another, then sort everything from smallest int to biggest.
I was looking for help everywhere, I tried to google it and looked through many articles. I couldn't find the answer. That's what I tried but I know it's wrong.
import java.io.File;
import java.util.Scanner;
public class Boombastic {
public static void main(String[] args) throws Exception {
File file = new File("C:\\Users\\bobo\\Documents\\NetBeansProjects\\" + "boombastic\\boombastic.txt");
String[] fullName;
Scanner sc = new Scanner(file);
while (sc.hasNext()) {
fullName[] = sc.next();
}
}
}
Could you please help me to fix it?

Use scanner.nextLine().
Also, I recommend using ArrayList because you don't know how many lines scanner has. If you do, then you can keep using arrays.
Using ArrayList:
public class Boombastic {
public static void main(String[] args) throws Exception {
File file = new File("C:\\Users\\bobo\\Documents\\NetBeansProjects\\" + "boombastic\\boombastic.txt");
ArrayList<String> fullName = new ArrayList<>();
ArrayList<Integer> ints = new ArrayList<>();
Scanner sc = new Scanner(file);
Scanner sc2 = new Scanner(file); // For the integers.
while(sc.hasNext()) {
fullName.add(sc.nextLine());
ints.add(sc2.nextInt());
}
}
}
Using arrays (assuming the scanner has 3 lines):
public class Boombastic {
public static void main(String[] args) throws Exception {
File file = new File("C:\\Users\\bobo\\Documents\\NetBeansProjects\\" + "boombastic\\boombastic.txt");
String[] fullName = new String[3];
int[] ints = new int[3];
Scanner sc = new Scanner(file);
Scanner sc2 = new Scanner(file);
int i = 0;
while (sc.hasNext()) {
fullName[i ++] = sc.next();
ints[i ++] = sc2.nextInt();
}
}
}
And to sort it, do
Arrays.sort(fullName);
Arrays.sort(ints);
This isn't the most efficient method, since it uses two scanners, but it works.

Instead of trying to assign the data to an array using separators and stuff, it is better to read all lines in a String and then process this String. There are plenty ways of how to read the lines of a text file into a String. Some basic of them can be found in this question.
However, I would not split the data and "store" them into Arrays since you do not know how much your data is. Also, I would choose "a more object oriented programming way" to achieve it. I would create a class, and objects of it will represent this data. After that I'd add these objects to collection and use Java's APIs to sort it within one line.
Finally, instead of new File("C:\\Users\\bobo\\Documents\\NetBeansProjects\\" + "boombastic\\boombastic.txt"); use File class constructor to build the path. Messing with separators is yikes...
An example would be:
public class Boombastic {
public static class Person {
private String firstName, lastName;
private int id; // ??
public Person(String firstName, String lastName, int id) {
this.firstName = firstName;
this.lastName = lastName;
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Override
public String toString() {
return "Person [firstName=" + firstName + ", lastName=" + lastName + ", id=" + id + "]";
}
}
public static void main(String[] args) throws Exception {
File desktop = new File(System.getProperty("user.home"), "Desktop");
File textFileWithData = new File(desktop, "data.txt");
List<Person> persons = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(textFileWithData))) {
String line = br.readLine();
while (line != null) {
String[] lineSplit = line.split("\\s");
Person person = new Person(lineSplit[0], lineSplit[1], Integer.parseInt(lineSplit[2]));
persons.add(person);
line = br.readLine();
}
} catch (IOException e) {
System.err.println("File cannot be read.");
e.printStackTrace();
System.exit(0);
}
// print unsorted
persons.forEach(System.out::println);
Collections.sort(persons, (p1, p2) -> p1.getId() - p2.getId()); // Sort persons by ID
System.out.println();
// print sorted
persons.forEach(System.out::println);
}
}
If you are having hard time to understand the sort part, take a look at how to use comparator in java.
My text file:
John Doe 3
Someone Else 2
Brad Pitt 5
Kevin Spacey 1
Output:
Person [firstName=John, lastName=Doe, id=3]
Person [firstName=Someone, lastName=Else, id=2]
Person [firstName=Brad, lastName=Pitt, id=5]
Person [firstName=Kevin, lastName=Spacey, id=1]
Person [firstName=Kevin, lastName=Spacey, id=1]
Person [firstName=Someone, lastName=Else, id=2]
Person [firstName=John, lastName=Doe, id=3]
Person [firstName=Brad, lastName=Pitt, id=5]

Related

How to read text file line by line in Java and exclude some line which start with specific string

I want to read the text file and input data so that I can create the Patient class object from the input parameter. the Text file contains different lines & categories, the first few lines contain data for Patient class, the next few lines contain data for a drug class, the third category contains the physician data for physician class. as follows
"myFile.txt" is my file name and contain the following data
So I want to read this file and input the data so that I can create an object of the respective class for Patient object, drug object, and physician object. I tried in the following way but I cannot split the category. my program code read all files and input into the patient object. so anyone's help is appreciated.
Note: I have already created classes Patient, Drug & Physician in other class files, I have no problem with creating classes. What I only want is to read data from this Text file main class and build the class object. So my problem is only how to read the Text file line by line based on the class parameters and extract data from it as input for my class objects.
here is my code
import java.util.Scanner;
import java.util.ArrayList;
import java.io.File;
import java.io.FileNotFoundException;
public class Lsystem{
static ArrayList<Patient> pList;
static ArrayList<Drug> dList;
static ArrayList<Physician> plist;
public static void main(String[] args) throws FileNotFoundException{
pList = new ArrayList<Patient>();
dList = new ArrayList<Drug>();
plist = new ArrayList<Physician>() ;
File dataFile = new File("myFile.txt");
Scanner inputData = null;
try {
inputData = new Scanner(dataFile);
}
catch(Exception e) {
System.out.println(e);
System.exit(1);
}
// skip first line
String[] line = inputData.nextLine().split(" ");
//read next lines
while( inputData.hasNextLine()) {
if(!(inputData.hasNext("# drugs "))){
line = inputData.nextLine().split(",");
String name = line[0];
String securityNum = line[1];
Patient newPatient = new Patient(name,securityNum);
pList.add(newPatient);
}
}
for(Patient pas:pList){
System.out.println(pas);
}
else if ((inputData.hasNext("# drugs")))
while( inputData.hasNextLine() && (!(inputData.hasNext("# Physician ")))) {
line = inputData.nextLine().split(",");
String name = line[0];
String type = line[1];
double price = Double.parseDouble(line[2]);
double kg = Double.parseDouble(line[3]);
int conc = Integer.valueOf(line[4]);
Drug newDrug = new Drug(name,type,price,kg,conc);
dList.add(newDrug);
}
for(Drug drg:dList){
System.out.println(drg);
}
// an so on for Physician data as well
// .......
}
}
hope this is what you need (it is dirty but...):
I am assuming that your text file is EXACTLY as the example below:
(file -> text.txt)
# Patient (name, securityNum)
Patient1, 1234
Patient2, 456
# drugs (name, type,pric,kg,concent)
drug1, type1, 12,51,10
drug2, type2,22,42,56
# Physician (name, Idnum)
dr.aaaa, 1234
dr.bbbbb, 456
this is the main (you have to change thee text.txt file path):
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class MainTest {
public static void main(String[] args) throws Exception {
//set the path of your text file
File file = new File(MainTest.class.getClassLoader().getResource("text.txt").getFile());
Scanner myReader = new Scanner(file);
StringBuilder sb = new StringBuilder();
while (myReader.hasNextLine()) {
String tmp = myReader.nextLine();
sb.append(tmp + "\n");
}
myReader.close();
String[] type = sb.toString().split("#");
String patients = type[1];
String drugs = type[2];
String doctors = type[3];
patients = patients.replace("Patient (name, securityNum)\n","");
drugs = drugs.replace("drugs (name, type,pric,kg,concent)\n","");
doctors = doctors.replace("Physician (name, Idnum)\n","");
System.out.println("°°°°°°°°°°°°°°°°°°°°°°°°°°°");
populatePatientBean(patients).forEach( patient -> {
System.out.println("\nname " + patient.getName());
System.out.println("num " + patient.getSecurityNum());
});
populateDrugsBean(drugs).forEach( drugs_ -> {
System.out.println("\nname " + drugs_.getName());
System.out.println("type " + drugs_.getType());
System.out.println("concent " + drugs_.getConcent());
System.out.println("kg " + drugs_.getKg());
});
populatePhysicianBean(doctors).forEach( doctor -> {
System.out.println("\nname " + doctor.getName());
System.out.println("id " + doctor.getIdNum());
});
System.out.println("°°°°°°°°°°°°°°°°°°°°°°°°°°°");
}
public static List<Patient> populatePatientBean(String linePatient){
List<String> patientsTot = Arrays.asList(linePatient.split("\n"));
List<Patient> patientListReturn = new ArrayList<>();
patientsTot.forEach( line -> {
String[] arrayString = line.split(",");
Patient patient = new Patient(arrayString[0].trim(),arrayString[1].trim());
patientListReturn.add(patient);
});
return patientListReturn;
}
public static List<Drugs> populateDrugsBean(String lineDrugs){
List<String> drugsTot = Arrays.asList(lineDrugs.split("\n"));
List<Drugs> drugsListReturn = new ArrayList<>();
drugsTot.forEach( line -> {
String[] arrayString = line.split(",");
Drugs drugs = new Drugs(arrayString[0].trim(),arrayString[1].trim(),Float.valueOf(arrayString[2].trim()),Float.valueOf(arrayString[3].trim()),Float.valueOf(arrayString[4].trim()));
drugsListReturn.add(drugs);
});
return drugsListReturn;
}
public static List<Physician> populatePhysicianBean(String linePhysician){
List<String> physicianTot = Arrays.asList(linePhysician.split("\n"));
List<Physician> physicianListReturn = new ArrayList<>();
physicianTot.forEach( line -> {
String[] arrayString = line.split(",");
Physician physician = new Physician(arrayString[0].trim(),Long.valueOf(arrayString[1].trim()));
physicianListReturn.add(physician);
});
return physicianListReturn;
}}
below the beans....
public class Patient {
private String name;
private String securityNum;
public Patient(String name, String securityNum) {
this.name = name;
this.securityNum = securityNum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSecurityNum() {
return securityNum;
}
public void setSecurityNum(String securityNum) {
this.securityNum = securityNum;
}
}
public class Drugs {
private String name;
private String type;
private float kg;
private float concent;
private float pric;
public Drugs(String name, String type, float kg, float concent, float pric) {
this.name = name;
this.type = type;
this.kg = kg;
this.concent = concent;
this.pric = pric;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public float getKg() {
return kg;
}
public void setKg(float kg) {
this.kg = kg;
}
public float getConcent() {
return concent;
}
public void setConcent(float concent) {
this.concent = concent;
}
public float getPric() {
return pric;
}
public void setPric(float pric) {
this.pric = pric;
}
}
public class Physician {
private String name;
private long idNum;
public Physician(String name, long idNum) {
this.name = name;
this.idNum = idNum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getIdNum() {
return idNum;
}
public void setIdNum(long idNum) {
this.idNum = idNum;
}
}
This uses File and Scanner to process the input file shown in the question. It assumes the file strictly follows the question's sample. For example, there must be three sections, with at least one record in each section. It also assumes there are no blank lines - not even at the end of the file.
In this sense, this solution is brittle, and is missing necessary error checking and validation code. Otherwise, it is a solution to the question.
See the code for additional comments.
The main point, based on your comments, is probably to look at the logic controlling how scanner.nextLine() is called.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.ArrayList;
public class ProcessDataFile {
// Our three lists for our three classes of object:
final List<Patient> patients = new ArrayList();
final List<Drug> drugs = new ArrayList();
final List<Physician> physicians = new ArrayList();
// The file scanner:
Scanner scanner;
// The currently processed line:
String line;
public void populateLists() throws FileNotFoundException {
File file = new File("C:/tmp/medical_data.txt");
scanner = new Scanner(file);
// process the file, one line at a time
while (scanner.hasNextLine()) {
line = scanner.nextLine();
processLine();
}
printResults();
}
// process each line in the file
private void processLine() {
if (line.startsWith("# Patient")) {
line = scanner.nextLine();
processPatients();
}
if (line.startsWith("# drug")) { // note the "d" in drug - not "D"!
line = scanner.nextLine();
processDrugs();
}
if (line.startsWith("# Physician")) {
line = scanner.nextLine();
processPhysicians();
}
}
private void processPatients() {
while (!line.startsWith("#")) {
String[] fields = line.split(",");
// TODO - add check to make sure 2 values are in the split string.
Patient patient = new Patient(
fields[0].trim(),
fields[1].trim());
patients.add(patient);
line = scanner.nextLine();
}
}
private void processDrugs() {
while (!line.startsWith("#")) {
String[] fields = line.split(",");
// TODO - add check to make sure 5 values are in the split string,
// and are of the expected data type:
Drug drug = new Drug(
fields[0].trim(),
fields[1].trim(),
Double.parseDouble(fields[2].trim()),
Double.parseDouble(fields[3].trim()),
Integer.parseInt(fields[4].trim()));
drugs.add(drug);
line = scanner.nextLine();
}
}
private void processPhysicians() {
while (!line.startsWith("#")) {
String[] fields = line.split(",");
// TODO - add check to make sure 2 values are in the split string,
// and are of the expected data type:
Physician physician = new Physician(
fields[0].trim(),
Long.parseLong(fields[1].trim()));
physicians.add(physician);
if (scanner.hasNextLine()) {
// this may be the end of the file already... this assumes
// that the physicians section is the final section.
line = scanner.nextLine();
} else {
return; // to avoid never exiting this method
}
}
}
private void printResults() {
patients.forEach((patient) -> {
System.out.println(patient.name + " : " + patient.securityNum);
});
// and the same for the other 2 beans...
}
}
This prints out the following:
Patient1 : 1234
Patient2 : 456
And it will print out the other 2 beans, if that missing code is added.

Java ~ User by user

I would like the user to provide data by scanner and add it to list. Later, I want to get the size of this list and for example user name, last name. I'm still trying to work with constructors and exceptions and now I want to try to put data from user.
It's Human Service which checks constructors, and if the name has less than 3 letters and lastname less than 5 letters will throw an exception.
import java.util.ArrayList;
import java.util.List;
public class HumanService {
List<Human> humans;
public HumanService() {
humans = new ArrayList<>();
}
public void addHuman(String name, String lastName) throws HumanNameWrongFormat, HumanLastNameWrongFormat {
if(HumanValidator.humanValidatorName(name) && HumanValidator.humanValidatorLastName(lastName)) {
Human human = new Human(sizeOfList(), name, lastName);
humans.add(human);
}
}
public int sizeOfList() {
return humans.size();
}
public Human getHumanByLastName(String lastName) throws HumanNotFoundException {
for (Human human : humans) {
if (human.getLastName().equals(lastName)) {
return human;
}
}
throw new HumanNotFoundException(lastName + " not found");
}
public Human getHumanById (Integer id) throws HumanNotFoundException {
for (Human human : humans) {
if (human.getId().equals(id)) {
return human;
}
}
throw new HumanNotFoundException(id + " not found");
}
}
I want to get data by user to list.
For example.
Please give me your name and last name.
Here is your name and last name by scanner and that will be added to list and checked.
This is also my main class.
public class main {
public static void main(String[] args) throws HumanNotFoundException {
HumanService humanService = new HumanService();
try {
humanService.addHuman("John", "Walker");
humanService.addHuman("Steve", "Williams");
humanService.addHuman("Gregor", "Wroten");
}
catch (HumanNameWrongFormat | HumanLastNameWrongFormat e) {
System.out.println(e.getMessage());
}
System.out.println(humanService.sizeOfList());
try {
humanService.getHumanByLastName("Wroten");
}
catch (HumanNotFoundException e) {
System.out.println(e.getMessage());
}
}
}
Here is the way you can use Scanner to get all the required user names and add them to the list for further processing
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Human> humans = new ArrayList();
while (true) {
System.out.println("Please give your first name");
String firstName = scanner.nextLine();
System.out.println("Please give your last name");
String lastName = scanner.nextLine();
humans.add(new Human(firstName, lastName)); // use your humanService here
boolean breakOut = false;
String input;
do {
System.out.println("Do you want to enter more names? (Y/N)");
input = scanner.nextLine();
if (input.equalsIgnoreCase("Y") || input.equalsIgnoreCase("N")) {
breakOut = true;
} else {
System.out.println("Invalid input. try again");
}
} while (!breakOut);
if (input.equalsIgnoreCase("Y")) {
break;
}
}
System.out.println(humans);
}
}
I am assuming you have two fields firstName, lastName in Human
class Human {
private String firstName;
private String lastName;
public Human(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Override
public String toString() {
return "first name " + firstName + " and last name " + lastName;
}
}
Input:
Please give your first name
John
Please give your last name
Smith
Do you want to enter more names? (Y/N)
y
Please give your first name
Will
Please give your last name
Smith
Do you want to enter more names? (Y/N)
n
Output:
[first name John and last name Smith, first name Will and last name Smith]
In the above code, replace the list with your humanService to add the humans

Storing Objects in Linked List

I am creating a simple program which reads data from a text file and displays it in the console. The data that I am displaying is information regarding a student - name, id, subject, marks etc
The program reads the text file, and creates a student object for each user found. I am running into a problem when trying to store these students in a linked list. It seems to create a new list each time and overrides the previous one, so I always just end up with one student in the list.
How can I get it store them without overriding previous lists? Here is some of my code below:
public static boolean readFile(String filename) {
File file = new File(filename);
try {
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()){
String[] words = scanner.nextLine().split(",");
int id = Integer.parseInt(words[0]);
String firstName = words[1];
String lastName = words[2];
int mathMark1 = Integer.parseInt(words[3]);
int mathMark2 = Integer.parseInt(words[4]);
int mathMark3 = Integer.parseInt(words[5]);
int englishMark1 = Integer.parseInt(words[6]);
int englishMark2 = Integer.parseInt(words[7]);
int englishMark3 = Integer.parseInt(words[8]);
addStudent(id,firstName,lastName,mathMark1,mathMark2,mathMark3,englishMark1,englishMark2,englishMark3);
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("Failed to read file");
}
return true;
}
private static void addStudent(int id, String firstName, String lastName,int
mathsMark1, int mathsMark2, int mathsMark3, int englishMark1, int englishMark2,
int englishMark3) {
LinkedList<Student> student = new LinkedList<>();
student.add(new Student(id,firstName,lastName));
LinkedList<AssignmentMarks> mathematicsMarks = new LinkedList<>();
mathematicsMarks.add(new AssignmentMarks("Mathematics",mathsMark1,mathsMark2,mathsMark3));
LinkedList<AssignmentMarks> englishMarks = new LinkedList<>();
englishMarks.add(new AssignmentMarks("English",englishMark1,englishMark2,englishMark3));
}
This code above is in my Main class. The code below is from my Student class:
public class Student {
private int id;
private String firstName;
private String lastName;
private AssignmentMarks mathMarks;
private AssignmentMarks englishMarks;
public Student(int id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public String getFullName() {
return firstName;
}
}
Any help would be appreciated thanks guys!
This variable
LinkedList<Student> student = new LinkedList<>();
needs to declared outside of the method, as a field, or within readFile and passed in as a parameter, otherwise it will be created everytime that you call addStudent
Declare your LinkedList as a member of the class, because here every time you call addStudent() you are creating a new list.
You should instead do something like :
public class Test {
private LinkedList<Student> student = new LinkedList<>();
public static boolean readFile(String filename) {
// ...
addStudent(id,firstName,lastName,mathMark1,mathMark2,mathMark3,
englishMark1,englishMark2,englishMark3);
}
private static void addStudent(int id, String firstName, String lastName,int
mathsMark1, int mathsMark2, int mathsMark3, int englishMark1, int englishMark2,
int englishMark3) {
// ...
// this will now add it to the only instance of the list
student.add(new Student(id,firstName,lastName));
}
}

how to sort name by last name from command line in java

I am trying to write a program which sorts name by it's last name, first name when "sort" condition is applied. The input will be provided from command line. I have started this way but have no idea how to make it work.
Input: sort "john main" "rob class" "bob ram"
Output: class,rob main,john ram,bob
public static void main(String[] args)
{
String[] args_name = new String[args.length-1];
System.arraycopy(args, 1, args_name, 0, args.length-1);
if(args[0].equals("sort"))
{
String firstName = name.substring(args_name,name.indexOf(" "));
String lastName = name.substring(name.indexOf(" ")+1);
String slst = lastName + ", " + firstName;
Arrays.sort(slst);
for (String s: slst) System.out.print(s);
}
}
Try using a Comparator to sort your input. I removed your args-related code for the sake of simplicity. You will still need to re-add it properly.
Required Imports
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
The Name
class Name{
public static final String FULL_NAME_DELIMITER = " ";
public static final String PRINT_DELIMITER = ", ";
private String firstName;
private String lastName;
public Name(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
public static String[] getName(String fullName){
return fullName.split(FULL_NAME_DELIMITER);
}
public String getLastName(){
return this.lastName;
}
#Override
public String toString(){
return String.join(PRINT_DELIMITER , this.lastName, this.firstName);
}
public void print(){
System.out.println(this);
}
}
The Comparator
class NameComparator implements Comparator<Name>{
#Override
public int compare(Name a, Name b) {
return a.getLastName().compareTo(b.getLastName()); // ASC: a to b or DESC: b to a
}
}
Usage
public class Main {
// Holds the sorted names
private static List<Name> names = new ArrayList<>();
public static void main(String[] args) {
// The input names
String[] input = new String[]{
"john main",
"rob class",
"bob ram"
};
// Prepare list for sorting
String firstName;
String lastName;
String[] completeName;
for (String fullName : input) {
completeName = Name.getName(fullName);
firstName = completeName[0];
lastName = completeName[1];
names.add(new Name(firstName, lastName));
}
// Actually sort
names.sort(new NameComparator());
// Print
names.forEach(System.out::println);
}
}
EDIT
To use the input from the command line, the args parameter is what you want to use.
Usage with Commandline Input
public class Main {
// Holds the sorted names
private static List<Name> names = new ArrayList<>();
public static void main(String[] args) {
// The method (in case something else than "sort" is desired)
String method = args[0];
// Check for valid method
if(!method.equals("sort")) return;
// The input names
String[] input = Arrays.copyOfRange(args, 1, args.length);
// Prepare list for sorting
String firstName;
String lastName;
String[] completeName;
for (String fullName : input) {
completeName = Name.getName(fullName);
firstName = completeName[0];
lastName = completeName[1];
names.add(new Name(firstName, lastName));
}
// Actually sort
names.sort(new NameComparator());
// Print
names.forEach(System.out::println);
}
}
EDIT 2
To use the first name instead of the last name, simply alter the Comparator.
class NameComparator implements Comparator<Name>{
#Override
public int compare(Name a, Name b) {
return a.getFirstName().compareTo(b.getFirstName()); // ASC: a to b or DESC: b to a
}
}
Of course, you would need to adjust the Name class as well, by adding:
public String getFirstName(){
return this.firstName;
}
if i understand your question well here is my code that solving this problem
public static void shortName(String shortName){
System.out.println("please enter yout name : ");
Scanner scanner = new Scanner(System.in);
String fullName = scanner.nextLine();
if( shortName.equals("sort")){
String [] nameArr = fullName.split(" ");
int lastNameIndex = nameArr.length - 1;
String name = nameArr[0] +" "+ nameArr[lastNameIndex];
System.out.println("welcome : "+name);
}
else {
System.out.println("welcome : "+fullName);
}
}
public static void main(String[] args) {
shortName("sort");
}

Separating strings and matching them with text file in java

I have a text file which contains a student number (9 digits), pin (4 digits), first name, last name. Which looks like this:
456864324,4965,Eves,Dalton
457642455,2164,Jagger,Michael
132435465, 3578,McIvar, Alan
543247531,2854,Jones, Alan
The student enters its student number and then pin. The program matches his input to the text file and checks if it matches or not.
So far I've separated the text line by line and stored it into an ArrayList and then thought about splitting it with ",". I've also thought about using Maps but cannot figure out how I will store the names with it as well.
String studentdb = sn_field.getText(); //get student number from input
String pindb = pin_field.getText(); //get pin from input
try {
File f = new File("file name");
Scanner sc = new Scanner(f);
ArrayList<String> number= new ArrayList<String>();
ArrayList<String> pswd = new ArrayList<String>();
while(sc.hasNextLine()){
String line = sc.nextLine();
// = line.split("\n");
String sn = line;
people.add(sn);
}
//if(people.contains(studentdb)){
//System.out.println("pass");}
} catch (FileNotFoundException f) {
System.out.print("file not found");
}
All in all if the student number and pin both are wrong, it should give an error, if both are correct and match, it passes. Any help would be appreciated as I'm just a beginner at Java.
I was able to process your file with the following example. Thanks for the problem as it provided a fun playground for some of the new features in Java 8 that I'm still getting familiar with . . .
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.Scanner;
public class StudentInformationMatcher
{
private static final Path FILE_PATH = Paths.get("C:\\projects\\playground\\src\\main\\resources\\studentinfo.txt");
public static void main(String[] args) throws IOException
{
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter your student number: ");
String studentNumber = scanner.next();
System.out.print("Please enter your pin: ");
String pin = scanner.next();
Optional<Person> matchingPersonRecord =
Files.lines(FILE_PATH)
.map(line -> line.split(","))
.map(csvValues -> new Person(csvValues))
.filter(person -> person.getStudentNumber().equals(studentNumber) && person.getPin().equals(pin))
.findFirst();
if (matchingPersonRecord.isPresent())
{
Person matchingPerson = matchingPersonRecord.get();
System.out.println("Hello " + matchingPerson.getFirstName() + " " + matchingPerson.getLastName());
}
else
{
System.out.println("No matching record found");
}
}
private static class Person
{
private final String studentNumber;
private final String pin;
private final String lastName;
private final String firstName;
private Person(String[] csvValues)
{
this.studentNumber = csvValues[0].trim();
this.pin = csvValues[1].trim();
this.lastName = csvValues[2].trim();
this.firstName = csvValues[3].trim();
}
private String getStudentNumber()
{
return studentNumber;
}
private String getPin()
{
return pin;
}
private String getLastName()
{
return lastName;
}
private String getFirstName()
{
return firstName;
}
}
}
Here an idea how you could achieve this:
Create a "student" class:
class student {
private String lastname;
private String firstname;
private String studentId;
private String pin;
// Getter and Setter methods
public static createNewStudent(String line) {
// split here the line and save the fields in the member variables
}
public boolean checkPinCode(String pin) {
return this.pin.equals(pin);
}
}
In your loop you can create student objects and add them to a Hashtable.
The key is the studentId and the value is the student object.
You can retrieve a student object from the hashtable with the entered key and check if the pin passes.

Categories