in here i want to collect everything after a substring and set it as their specfic field.
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
/**
*
*
* class StudentReader for retrieveing data from file
*
*/
public class StudentReader {
public static Student[] readFromTextFile(String fileName) {
ArrayList<Student> result = new ArrayList<Student>();
File f = new File(filename);
Scanner n = new Scanner(f);
while (n.hasNextLine()) {
String text = n.nextLine();
}
n.close();
String hold1[] = text.Split(",");
String hold2[] = new String[hold1.length];;
for(int i = 0; i < hold1.length(); ++i) {
hold2[i] = hold1.Split("=");
if (hold2[i].substring(0,3).equals("name")) {
}
}
return result.toArray(new Student[0]);
}
}
backing up the goal of this code is to first open and read a file where it has about 20 lines that look just like this
Student{name=Jill Gall,age=21,gpa=2.98}
I then need to split it as done above, twice first to get rid of comma and the equals, I then for each line need to collect the value of the name, age and double, parse them and then set them as a new student object and return that array they are going to be saved onto, what I am currently stuck on is that i cannot figure out what's the right code here for collecting everything after "name" "age" "gpa", as i dont know how to set specific substrings for different name
im using this link as a reference but I don't see what actually does it
How to implement discretionary use of Scanner
I think the bug is in following lines,
while (n.hasNextLine()) {
String text = n.nextLine();
}
Above code should throw compilation error at String hold1[] = text.Split(","); as text is local variable within while loop.
Actual it should be,
List<String> inputs = new ArrayList<String>()
Scanner n = new Scanner(f);
while (n.hasNextLine()) {
inputs.add(n.nextLine());
}
You can use above inputs list to manipulate your logic
By the look of it, at least by your ArrayList<> declaration, you have a class named Student which contains member variable instances of studentName, studentAge, and studentGPA. It might look something like this (the Getter/Setter methods are of course optional as is the overriden toString() method):
public class Student {
// Member Variables...
String studentName;
int studentAge = 0;
double studentGPA = 0.0d;
// Constructor 1:
public Student() { }
// Constructor 2: (used to fill instance member variables
// right away when a new instance of Student is created)
public Student(String name, int age, double gpa) {
this.studentName = name;
this.studentAge = age;
this.studentGPA = gpa;
}
// Getters & Setters...
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getStudentAge() {
return studentAge;
}
public void setStudentAge(int studentAge) {
this.studentAge = studentAge;
}
public double getStudentGPA() {
return studentGPA;
}
public void setStudentGPA(double studentGPA) {
this.studentGPA = studentGPA;
}
#Override
public String toString() {
return new StringBuilder("").append(studentName).append(", ")
.append(String.valueOf(studentAge)).append(", ")
.append(String.valueOf(studentGPA)).toString();
}
}
I should think the goal would be to to read in each file line from the Students text file where each file line consists of a specific student's name, the student's age, and the student's GPA score and create a Student instance for the Student on that particular file line. This is to be done until the end of file. If there are twenty students within the Students text file then, when the readFromTextFile() method has completed running there will be twenty specific instances of Student. Your StudentReader class might look something like this:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
*
* class StudentReader for retrieving data from file
*
*/
public class StudentReader {
private static final Scanner userInput = new Scanner(System.in);
private static Student[] studentsArray;
public static void main(String args[]) {
String underline = "=====================================================";
String dataFilePath = "StudentsFile.txt";
System.out.println("Reading in Student data from file named: " + dataFilePath);
if (args.length >= 1) {
dataFilePath = args[0].trim();
if (!new File(dataFilePath).exists()) {
System.err.println("Data File Not Found! (" + dataFilePath + ")");
return;
}
}
studentsArray = readFromTextFile(dataFilePath);
System.out.println("Displaying student data in Console Window:");
displayStudents();
System.out.println(underline);
System.out.println("Get all Student's GPA score average:");
double allGPA = getAllStudentsGPAAverage();
System.out.println("GPA score average for all Students is: --> " +
String.format("%.2f",allGPA));
System.out.println(underline);
System.out.println("Get a Student's GPA score:");
String sName = null;
while (sName == null) {
System.out.print("Enter a student's name: --> ");
sName = userInput.nextLine();
/* Validate that it is a name. Should validate in
almost any language including Hindi. From Stack-
Overflow post: https://stackoverflow.com/a/57037472/4725875 */
if (sName.matches("^[\\p{L}\\p{M}]+([\\p{L}\\p{Pd}\\p{Zs}'.]*"
+ "[\\p{L}\\p{M}])+$|^[\\p{L}\\p{M}]+$")) {
break;
}
else {
System.err.println("Invalid Name! Try again...");
System.out.println();
sName = null;
}
}
boolean haveName = isStudent(sName);
System.out.println("Do we have an instance of "+ sName +
" from data file? --> " +
(haveName ? "Yes" : "No"));
// Get Student's GPA
if (haveName) {
double sGPA = getStudentGPA(sName);
System.out.println(sName + "'s GPA score is: --> " + sGPA);
}
System.out.println(underline);
}
public static Student[] readFromTextFile(String fileName) {
List<Student> result = new ArrayList<>();
File f = new File(fileName);
try (Scanner input = new Scanner(f)) {
while (input.hasNextLine()) {
String fileLine = input.nextLine().trim();
if (fileLine.isEmpty()) {
continue;
}
String[] lineParts = fileLine.split("\\s{0,},\\s{0,}");
String studentName = "";
int studentAge = 0;
double studentGPA = 0.0d;
// Get Student Name (if it exists).
if (lineParts.length >= 1) {
studentName = lineParts[0].split("\\s{0,}\\=\\s{0,}")[1];
// Get Student Age (if it exists).
if (lineParts.length >= 2) {
String tmpStrg = lineParts[1].split("\\s{0,}\\=\\s{0,}")[1];
// Validate data.
if (tmpStrg.matches("\\d+")) {
studentAge = Integer.valueOf(tmpStrg);
}
// Get Student GPA (if it exists).
if (lineParts.length >= 3) {
tmpStrg = lineParts[2].split("\\s{0,}\\=\\s{0,}")[1];
// Validate data.
if (tmpStrg.matches("-?\\d+(\\.\\d+)?")) {
studentGPA = Double.valueOf(tmpStrg);
}
}
}
}
/* Create a new Student instance and pass the student's data
into the Student Constructor then add the Student instance
to the 'result' List. */
result.add(new Student(studentName, studentAge, studentGPA));
}
}
catch (FileNotFoundException ex) {
System.err.println(ex);
}
return result.toArray(new Student[result.size()]);
}
public static void displayStudents() {
if (studentsArray == null || studentsArray.length == 0) {
System.err.println("There are no Students within the supplied Students Array!");
return;
}
for (int i = 0; i < studentsArray.length; i++) {
System.out.println(studentsArray[i].toString());
}
}
public static boolean isStudent(String studentsName) {
boolean found = false;
if (studentsArray == null || studentsArray.length == 0) {
System.err.println("There are no Students within the supplied Students Array!");
return found;
} else if (studentsName == null || studentsName.isEmpty()) {
System.err.println("Student name can not be Null or Null-String (\"\")!");
return found;
}
for (int i = 0; i < studentsArray.length; i++) {
if (studentsArray[i].getStudentName().equalsIgnoreCase(studentsName)) {
found = true;
break;
}
}
return found;
}
public static double getStudentGPA(String studentsName) {
double score = 0.0d;
if (studentsArray == null || studentsArray.length == 0) {
System.err.println("There are no Students within the supplied Students Array!");
return score;
} else if (studentsName == null || studentsName.isEmpty()) {
System.err.println("Student name can not be Null or Null-String (\"\")!");
return score;
}
boolean found = false;
for (int i = 0; i < studentsArray.length; i++) {
if (studentsArray[i].getStudentName().equalsIgnoreCase(studentsName)) {
found = true;
score = studentsArray[i].getStudentGPA();
break;
}
}
if (!found) {
System.err.println("The Student named '" + studentsName + "' could not be found!");
}
return score;
}
public static double getAllStudentsGPAAverage() {
double total = 0.0d;
if (studentsArray == null || studentsArray.length == 0) {
System.err.println("There are no Students within the supplied Students Array!");
return total;
}
for (int i = 0; i < studentsArray.length; i++) {
total += studentsArray[i].getStudentGPA();
}
return total / (double) studentsArray.length;
}
}
Related
I'm having the following issue.
I have a list filled with instances of the "God" class, 12 instances, for now, but will add more in the future.
I also have an list empty.
Both lists can take type God instances.
The user will pick 6 of these gods, and these gods will be added to the empty list, and also be remove of the filled list, so they can't get picked again.
The goal of this part of the project is, to:
The user will pick 6 times. So I have a for loop from 0 to 5;
The Scanner takes the id of the god
The second for loop, from 0 to listFilledWithGods.size(), will check if the scanner matches the id
If the id matches, it will add to the empty list, and remove from the List filled with gods
If it does not match the user needs to be asked constantly to pick another one, until the user picks an available god. (here is where I'm having trouble)
Github: https://github.com/OrlandoVSilva/battleSimulatorJava.git
The issue in question resides in the class player in the method selectGodsForTeam
There is a JSON jar added to the project: json-simple-1.1.1
*Edit:
I added the while loop, as an exmaple of one of the ways that I tried to fix the issue.
If the user on the first pick picks id 3, it should work, because no god has been picked yet, however the loop when comparing it with the first position (id 1) it says to pick another one, which should is not the intended objective.
Main:
import java.util.List;
public class Main {
public Main() {
}
public static void main(String[] args) {
Launcher launch = new Launcher();
godSelection(launch.loadGods());
}
private static void godSelection(List<God> listOfloadedGods) {
Player player = new Player(listOfloadedGods);
player.selectGodsForTeam();
}
}
Launcher:
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class Launcher {
private List<God> godCollection;
public Launcher(){
godCollection = new ArrayList<>();
}
List<God> loadGods(){ // load all gods from Json file into list
String strJson = getJSONFromFile("C:\\Users\\OrlandoVSilva\\Desktop\\JavaBattleSimulator\\battlesimulator\\src\\projectStructure\\gods.json");
// Try-catch block
try {
JSONParser parser = new JSONParser();
Object object = parser.parse(strJson); // converting the contents of the file into an object
JSONObject mainJsonObject = (JSONObject) object; // converting the object into a json object
//-------------------
JSONArray jsonArrayGods = (JSONArray) mainJsonObject.get("gods");
//System.out.println("Gods: ");
for(int i = 0; i < jsonArrayGods.size(); i++){
JSONObject jsonGodsData = (JSONObject) jsonArrayGods.get(i);
String godName = (String) jsonGodsData.get("name");
//System.out.println("Name: " + godName);
double godHealth = (double) jsonGodsData.get("health");
//System.out.println("Health: " + godHealth);
double godAttack = (double) jsonGodsData.get("attack");
//System.out.println("Attack: " + godAttack);
double godSpecialAttack = (double) jsonGodsData.get("specialAttack");
//System.out.println("Special Attack: " + godSpecialAttack);
double godDefense = (double) jsonGodsData.get("defense");
//System.out.println("Defense: " + godDefense);
double godSpecialDefence = (double) jsonGodsData.get("specialDefense");
//System.out.println("Special Defence: " + godSpecialDefence);
double godSpeed = (double) jsonGodsData.get("speed");
//System.out.println("Speed: " + godSpeed);
double godMana = (double) jsonGodsData.get("mana");
//System.out.println("Mana: " + godMana);
String godPantheon = (String) jsonGodsData.get("pantheon");
//System.out.println("Pantheon: " + godPantheon);
long godId = (long) jsonGodsData.get("id");
int newGodId = (int) godId;
//System.out.println("Id: " + newGodId);
godCollection.add(new God(godName, godHealth, godAttack, godSpecialAttack, godDefense, godSpecialDefence, godSpeed, godMana, godPantheon, newGodId));
//System.out.println();
}
} catch (Exception ex){
ex.printStackTrace();
}
// Try-catch block
//System.out.println("Size: " + godCollection.size());
return godCollection;
}
public static String getJSONFromFile(String filename) { // requires file name
String jsonText = "";
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(filename)); // read the file
String line; // read the file line by line
while ((line = bufferedReader.readLine()) != null) {
jsonText += line + "\n"; // store json dat into "jsonText" variable
}
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
return jsonText;
}
}
Player:
import java.util.*;
public class Player {
// --- Properties ---
private List<God> listOfAllGods; // List of all the gods;
private List<God> selectedGods; // list for the selected gods;
// --- Properties ---
// --- Constructor ---
Player(List<God> listOfAllGods){
this.listOfAllGods = listOfAllGods;
selectedGods = new ArrayList<>();
}
// --- Constructor ---
// --- Getters & Setters ---
public List<God> getSelectedGods() {
return listOfAllGods;
}
// --- Getters & Setters ---
// --- Methods ---
void selectGodsForTeam(){
Scanner scanner = new Scanner(System.in);
boolean isGodAvailable;
int chooseGodId;
/*
char answerChar = 'n';
while (answerChar == 'n'){
answerChar = informationAboutGods();
// Do you want to see information about any of the gods first?
// y or n
while(answerChar == 'y'){
answerChar = informationAboutAnyOtherGods();
// Which of the gods, do you want to see information of?
// godId
// Do you want to see information about any other gods?
// y or n
}
answerChar = proceedWithGodPick();
// Do you want to proceed with the God pick?
// y or n
}
System.out.println();
*/
System.out.println("Please choose the 6 id's of the gods, you wish to pick:");
for(int i = 0; i <= 5; i++){
chooseGodId = scanner.nextInt();
for(int j = 0; j < listOfAllGods.size(); j++){
if(chooseGodId == listOfAllGods.get(j).getId()){
selectedGods.add(listOfAllGods.get(j));
listOfAllGods.remove(j);
} else {
isGodAvailable = false;
while (!isGodAvailable){
System.out.println("Please pick another one");
chooseGodId = scanner.nextInt();
if(chooseGodId == listOfAllGods.get(j).getId()) {
isGodAvailable = true;
selectedGods.add(listOfAllGods.get(j));
listOfAllGods.remove(j);
}
}
}
}
}
}
char informationAboutGods(){
Scanner scanner = new Scanner(System.in);
char answerChar = 'n';
//-----------
System.out.println("This is a list, of all the selectable gods: ");
System.out.println();
for (int i = 0; i < listOfAllGods.size(); i++){
System.out.println(listOfAllGods.get(i).getName() + " = " + "Id: " + listOfAllGods.get(i).getId());
}
System.out.println();
System.out.println("Do you want to see information about any of the gods first?");
System.out.println("[y] or [n]");
answerChar = scanner.next().charAt(0);
return answerChar;
}
char informationAboutAnyOtherGods(){
Scanner scanner = new Scanner(System.in);
char answerChar = 'n';
int answerInt;
//------------
System.out.println();
System.out.println("Which of the gods, do you want to see information of?");
System.out.println("Please input it's id number: ");
answerInt = scanner.nextInt();
System.out.println();
System.out.println("Display god information here!");
System.out.println();
System.out.println("Do you want to see information about any other gods?");
System.out.println("[y] or [n]");
answerChar = scanner.next().charAt(0);
return answerChar;
}
char proceedWithGodPick(){
Scanner scanner = new Scanner(System.in);
char answerChar = 'n';
//----------
System.out.println();
System.out.println("Do you want to proceed with the God pick?");
System.out.println("[y] or [n]");
answerChar = scanner.next().charAt(0);
return answerChar;
}
// --- Methods ---
}
God:
public class God {
private final String name;
private double health;
private double attack;
private double specialAttack;
private double defense;
private double specialDefense;
private double speed;
private double mana;
private final String pantheon;
private final int id;
public God(String name, double health, double attack, double specialAttack, double defense, double specialDefense, double speed, double mana, String pantheon, int id) {
this.name = name;
this.health = health;
this.attack = attack;
this.specialAttack = specialAttack;
this.defense = defense;
this.specialDefense = specialDefense;
this.speed = speed;
this.mana = mana;
this.pantheon = pantheon;
this.id = id;
}
public double getHealth() {
return this.health;
}
public void setHealth(double health) {
this.health = health;
}
public double getAttack() {
return this.attack;
}
public void setAttack(double attack) {
this.attack = attack;
}
public double getSpecialAttack() {
return this.specialAttack;
}
public void setSpecialAttack(double specialAttack) {
this.specialAttack = specialAttack;
}
public double getDefense() {
return this.defense;
}
public void setDefense(double defense) {
this.defense = defense;
}
public double getSpecialDefense() {
return this.specialDefense;
}
public void setSpecialDefense(double specialDefense) {
this.specialDefense = specialDefense;
}
public double getSpeed() {
return this.speed;
}
public void setSpeed(double speed) {
this.speed = speed;
}
public double getMana() {
return this.mana;
}
public void setMana(double mana) {
this.mana = mana;
}
public String getName() {
return this.name;
}
public String getPantheon() {
return this.pantheon;
}
public int getId() {
return this.id;
}
}
If I understand correctly, the key is to replace the for loop, which will have 6 iterations, with a while loop, which will iterate until the user has successfully selected 6 gods. Use continue; when there is a failure to select a god.
System.out.println("Please choose the 6 id's of the gods, you wish to pick:");
while (selectedGods.size () < 6) {
System.out.print ("You have selected " + selectedGods.size ()
+ "gods. Please enter I.D. of next god >");
chooseGodId = scanner.nextInt();
if (findGod (selectedGods, chooseGodID) >= 0) {
System.out.println ("You already selected god " + chooseGodId
+ ". Please select again.");
continue;
}
int godSelectedIndex = findGod (listOfAllGods, chooseGodId);
if (godSelectedIndex < 0) {
System.out.println ("God " + chooseGodID + " is not available."
+ " Please select again.");
continue;
}
selectedGods.add (listOfAllGods.get(godSelectedIndex));
listOfAllGods.remove (godSelectedIndex);
}
This assumes the existence of
static public int findGod (List<God> godList, int targetGodID)
This findGod method searches godList for an element in which .getId() is equal to gargetGodID. When a match is found, it returns the index of element where the match was found. When a match is not found, it returns -1. The O/P has shown the ability to create this method.
Note: I have not verified the code in this answer. If you find an error, you may correct it by editing this answer.
I'm creating a phone book for an assignment and I'm stuck on this part. I need to print every match if the user didn't enter the first name. Currently, my program only print the first match.
Part of the instruction: If the user enters just the last name, the program goes through the entire array, printing out every match. If the user enters both first and last names, the program will print out the first match, then stop.
This is my search method in my PhoneBook class:
// use linear search to find the targetName.
// Return a reference to the matching PhoneEntry
// or null if none is found
public PhoneEntry search(String fName, String lName) {
for (int j = 0; j < phoneBook.length; j++) {
if (phoneBook[j].lastName.equals(lName)) {
if (phoneBook[j].firstName.equals(fName) || fName.equals("")) {
return phoneBook[j];
}
}
}
return null;
}
And this is my loop for prompting the user and printing the information in my Tester
do {
// Prompt the user to enter the name
System.out.print("Pleast enter the last name to search: ");
lastName = input.nextLine();
System.out.print("Please enter the first name to search: ");
firstName = input.nextLine();
// search for the person
entry = pb.search(firstName.toUpperCase(), lastName.toUpperCase());
// if found, print out the entry
if (entry != null) {
System.out.println(entry.firstName + " " + entry.lastName + ": " + entry.phone);
}
// if user enter quit, then say good bye
else if ("quit".equals(lastName)) {
System.out.println("Good Bye!");
}
// if not found, tell the user
else {
System.out.println("Name not found.");
}
} while (!"quit".equals(lastName));
I just need to get the program to print all of the matches if only last name is entered. I'm new to arrays and I only know Java.
Thank you in advance! :)
Update
Thanks to #TyeolRik, I was able to do "something" about it. His way was using the cases way and sorry but I do not know how to do cases. I implemented his way into mine, but I do not know how to connect them between classes. I tried to put "return resultList" on the search method, but it didn't allowed me to because it is a PhoneEntry[] instead of PhoneEntry, and that is true, but I can't search it using "entry = pb.search(firstName.toUpperCase(), lastName.toUpperCase());" if it is an array type. I need help! Thank you guys.
This is my complete current code (I have 3 classes):
PhoneBook (ignore the add method because that is for something else that I'm doing for another instruction):
public class PhoneBook {
PhoneEntry[] phoneBook;
PhoneEntry[] resultList = new PhoneEntry[10];
// constructor
public PhoneBook() {
phoneBook = new PhoneEntry[10];
// load the phone book with data
phoneBook[0] = new PhoneEntry("James", "Barclay", "(418) 665-1223");
phoneBook[1] = new PhoneEntry("Grace", "Dunbar", "(860) 399-3044");
phoneBook[2] = new PhoneEntry("Paul", "Kratides", "(815) 439-9271");
phoneBook[3] = new PhoneEntry("Violet", "Smith", "(312) 223-1937");
phoneBook[4] = new PhoneEntry("John", "Wood", "(913) 883-2874");
phoneBook[5] = new PhoneEntry("John", "Smith", "(407) 123-4555");
}
// use linear search to find the targetName.
// Return a reference to the matching PhoneEntry
// or null if none is found
public PhoneEntry search(String fName, String lName) {
int i = 0;
if (fName.equals("")) {
for (int j = 0; j < phoneBook.length; j++) {
if (phoneBook[j].lastName.equals(lName)) {
resultList[i] = phoneBook[j];
i++;
}
}
}
else {
for (int j = 0; j < phoneBook.length; j++) {
if (phoneBook[j].lastName.equals(lName) && phoneBook[j].firstName.equals(fName)) {
resultList[i] = phoneBook[j];
i++;
}
}
}
return null;
}
public void add(String fName, String lName, String phone) {
for (int i = 0; i < phoneBook.length; i++) {
if (phoneBook[i] == null) {
phoneBook[i] = new PhoneEntry(fName, lName, phone);
}
else {
System.out.println("No room in phone book.");
}
}
}
}
Tester:
import java.util.*;
public class PhoneBookTester {
public static void main(String[] args) {
PhoneBook pb = new PhoneBook();
PhoneEntry entry;
// Create a new scanner object
Scanner input = new Scanner(System.in);
String lastName;
String firstName;
do {
// Prompt the user to enter the name
System.out.print("Pleast enter the last name to search: ");
lastName = input.nextLine();
System.out.print("Please enter the first name to search: ");
firstName = input.nextLine();
// search for the person
entry = pb.search(firstName.toUpperCase(), lastName.toUpperCase());
// if found, print out the entry
if (entry != null) {
//for(Phonebook eachEntry : pb.search(firstName.toUpperCase(), lastName.toUpperCase())) {
System.out.println(entry.firstName + " " + entry.lastName + ": " + entry.phone);
}
// if user enter quit, then say good bye
else if ("quit".equals(lastName)) {
System.out.println("Good Bye!");
}
// if not found, tell the user
else {
System.out.println("Name not found.");
}
} while (!"quit".equals(lastName));
}
}
PhoneEntry:
public class PhoneEntry {
String firstName; // first name of a person
String lastName; // first name of a person
String phone; // phone number of a person
// constructor
public PhoneEntry(String fName, String lName, String p) {
firstName = fName.toUpperCase();
lastName = lName.toUpperCase();
phone = p;
}
}
Solution
public PhoneEntry search(String fName, String lName) {
// There could be 2 cases.
// 1. There is only LastName == There is no First name
// 2. There are First and Last name; == There is First name
// That means, you can easily handle this problem with checking whether there is first name
int caseNumber = 0; // Default number 0 will return null
if(fName.equals("")) { // if there is no first name
caseNumber = 1;
} else {
caseNumber = 2;
}
PhoneBook[] searchResultList = new PhoneBook[]; // This will be result phonebook
switch(caseNumber) {
case 1:
for (int j = 0; j < phoneBook.length; j++) {
if (phoneBook[j].lastName.equals(lName)) {
searchResultList.add(phoneBook[j]);
}
}
return searchResultList;
case 2:
for (int j = 0; j < phoneBook.length; j++) {
if (phoneBook[j].lastName.equals(lName) && phoneBook[j].firstname.equals(fName)) {
searchResultList.add(phoneBook[j]); // This could be mutiple. (There is possible situation that there is two person whose name is same and different phone number)
}
}
return searchResultList;
default:
return null;
}
}
And you can print the answer
for(Phonebook eachBook : pb.search(inputFName, inputLName)) {
System.out.println(eachBook .firstName + " " + eachBook .lastName + ": " + eachBook .phone);
}
I don't know what exactly PhoneBook class is. So, I assume PhoneBook class has 3 variable, firstName, lastName, phone. So, please modify this answer that this codes fit your codes.
=========== Edit :: Add solution ===========
main() class
public static void main(String[] args) {
// Create a new scanner object
Scanner input = new Scanner(System.in);
String lastName;
String firstName;
int variableForCountArray;
do {
PhoneBook pb = new PhoneBook();
PhoneEntry[] entry;
entry = null;
variableForCountArray = 0;
// Prompt the user to enter the name
System.out.print("Pleast enter the last name to search: ");
lastName = input.nextLine();
System.out.print("Please enter the first name to search: ");
firstName = input.nextLine();
// search for the person
entry = pb.search(firstName.toUpperCase(), lastName.toUpperCase());
// if found, print out the entry
if (entry != null) {
for(int i = 0; i < entry.length; i++) {
if(entry[i] != null) { // Could get NullPointerException
variableForCountArray++;
}
}
for(int index = 0; index < variableForCountArray; index++) {
System.out.println(entry[index].firstName + " " + entry[index].lastName + ": " + entry[index].phone);
}
}
// if user enter quit, then say good bye
else if ("quit".equals(lastName)) {
System.out.println("Good Bye!");
}
// if not found, tell the user
else {
System.out.println("Name not found.");
}
} while (!"quit".equals(lastName));
}
PhoneEntry.java // No change
public class PhoneEntry {
String firstName; // first name of a person
String lastName; // last name of a person
String phone; // phone number of a person
// constructor
public PhoneEntry(String fName, String lName, String p) {
firstName = fName.toUpperCase();
lastName = lName.toUpperCase();
phone = p;
}
}
PhoneBook.java
public class PhoneBook {
PhoneEntry[] phoneBook;
PhoneEntry[] resultList = new PhoneEntry[10];
// constructor
public PhoneBook() {
phoneBook = new PhoneEntry[10];
// load the phone book with data
phoneBook[0] = new PhoneEntry("James", "Barclay", "(418) 665-1223");
phoneBook[1] = new PhoneEntry("Grace", "Dunbar", "(860) 399-3044");
phoneBook[2] = new PhoneEntry("Paul", "Kratides", "(815) 439-9271");
phoneBook[3] = new PhoneEntry("Violet", "Smith", "(312) 223-1937");
phoneBook[4] = new PhoneEntry("John", "Wood", "(913) 883-2874");
phoneBook[5] = new PhoneEntry("John", "Smith", "(407) 123-4555");
}
// use linear search to find the targetName.
// Return a reference to the matching PhoneEntry
// or null if none is found
public PhoneEntry[] search(String fName, String lName) {
int i = 0;
if (fName.equals("")) {
for (int j = 0; j < phoneBook.length; j++) {
if(phoneBook[j] != null) {
if (phoneBook[j].lastName.equals(lName)) {
resultList[i] = phoneBook[j];
i++;
}
}
}
} else {
for (int j = 0; j < phoneBook.length; j++) {
if(phoneBook[j] != null) {
if (phoneBook[j].lastName.equals(lName) && phoneBook[j].firstName.equals(fName)) {
resultList[i] = phoneBook[j];
i++;
}
}
}
}
if(i == 0) {
return null;
} else {
return resultList;
}
}
public void add(String fName, String lName, String phone) {
for (int i = 0; i < phoneBook.length; i++) {
if (phoneBook[i] == null) {
phoneBook[i] = new PhoneEntry(fName, lName, phone);
}
else {
System.out.println("No room in phone book.");
}
}
}
}
Print test result
Pleast enter the last name to search: smith
Please enter the first name to search:
VIOLET SMITH: (312) 223-1937
JOHN SMITH: (407) 123-4555
Pleast enter the last name to search: smith
Please enter the first name to search: john
JOHN SMITH: (407) 123-4555
Pleast enter the last name to search: hello
Please enter the first name to search:
Name not found.
Pleast enter the last name to search: quit
Please enter the first name to search:
Good Bye!
Java8 approach.
PhoneEntry class:
public class PhoneEntry {
final String firstName;
final String lastName;
final String phone;
public PhoneEntry(String firstName, String lastName, String phone){
this.firstName = firstName;
this.lastName = lastName;
this.phone = phone;
}
}
PhoneBook class:
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class PhoneBook {
List<PhoneEntry> contancts = new ArrayList<PhoneEntry>();
public List<PhoneEntry> search(String lastName) {
return contancts.stream()
.filter(phoneEntry ->
phoneEntry.firstName.toLowerCase().equals(lastName.toLowerCase())
|| phoneEntry.lastName.toLowerCase().equals(lastName.toLowerCase()))
.collect(Collectors.toList());
}
public Optional<PhoneEntry> search(String firsName, String lastName){
return contancts.stream()
.filter(phoneEntry ->
phoneEntry.firstName.toLowerCase().equals(firsName.toLowerCase())
&& phoneEntry.lastName.toLowerCase().equals(lastName.toLowerCase()))
.findFirst();
}
}
Test class:
import java.util.List;
import java.util.Optional;
import java.util.Scanner;
public class App {
public static void main(String[] args) {
PhoneBook phoneBook = new PhoneBook();
phoneBook.contancts.add(new PhoneEntry("John","Xavier","(992)-30421-323"));
phoneBook.contancts.add(new PhoneEntry("Mary","Doser","(992)-30421-353"));
phoneBook.contancts.add(new PhoneEntry("George","Sesame","(990)-30421-353"));
phoneBook.contancts.add(new PhoneEntry("Liam","Xavier","(990)-30211-353"));
Scanner input = new Scanner(System.in);
String lastName;
String firstName;
do {
// Prompt the user to enter the name
System.out.print("Pleast enter the last name to search: ");
lastName = input.nextLine();
System.out.print("Please enter the first name to search: ");
firstName = input.nextLine();
// search for the person
Optional<PhoneEntry> entry = phoneBook.search(firstName, lastName);
List<PhoneEntry> entries = phoneBook.search(lastName);
// if found, print out the entry
if (entry.isPresent() && firstName.length() !=0) {
System.out.println(entry.get().firstName + " " + entry.get().lastName + ": " + entry.get().phone);
}else if(firstName.length() == 0 && entries.size() !=0 ){
entries.forEach(e -> System.out.println(e.firstName + " " + e.lastName + ": " + e.phone));
}
// if user enter quit, then say good bye
else if ("quit".equals(lastName)) {
System.out.println("Good Bye!");
}
// if not found, tell the user
else {
System.out.println("Name not found.");
}
} while (!"quit".equals(lastName));
}
}
I'm trying to take data out of a txt file and create comparable objects out of the data and add them to an array. After that array is created, I want to make a 2d array that stores a 1 in a slot if two options meet the requirements. I keep getting a String index out of range: 0 error though and I do not know where it comes from.
import java.util.*;
import java.io.*;
public class CourseScheduler
{
public int numberOfCourses;
public int[][] adjacent;
public Course[] courses;
public CourseScheduler(String filename)
{
File file = new File(filename);
try{
Scanner scan = new Scanner(file);
numberOfCourses = scan.nextInt();
courses = new Course[numberOfCourses];
adjacent = new int[numberOfCourses][numberOfCourses];
scan.useDelimiter(",|\\n");
for(int i = 0; i < numberOfCourses;i ++){
if(scan.hasNext()){
String dept = scan.next();
String num = scan.next();
String building = scan.next();
String room = scan.next();
String instruct = scan.next();
courses[i] = new Course(dept, num, building, room, instruct);
}
}
}
catch(FileNotFoundException ex){
System.out.println("File was not found");
}
for(int x = 0;x<numberOfCourses;x++){
for(int y = 0;y<numberOfCourses;y++){
adjacent[x][y] = (courses[x].compare(courses[y]));
}
}
}
This is the code for the main class
public class Course{
String department;
String courseNum;
String buildingCode;
String roomCode;
String instructorName;
public Course(String dept, String number, String building, String room, String instructor){
department = dept;
courseNum = number;
buildingCode = building;
roomCode = room;
instructorName = instructor;
}
public String getDept(){
return department;
}
public String getCourse(){
return courseNum;
}
public String getBuilding(){
return buildingCode;
}
public String getRoom(){
return roomCode;
}
public String getInstructor(){
return instructorName;
}
public String toString(){
return department + ";" + courseNum + ";" + buildingCode + ";" + roomCode + ";" + instructorName;
}
public int compare(Course comp){
int ans = 1;
String compNum = comp.getCourse();
if(instructorName == comp.getInstructor())
ans = 0;
if(buildingCode == comp.getBuilding()){
if(roomCode == comp.getRoom())
ans = 0;
}
if(department == comp.getDept()){
if(courseNum.charAt(0) == compNum.charAt(0))
ans = 0;
}
return ans;
}
}
this is the code for the course class
Educated guess: Most likely your error is coming from this line:
if(courseNum.charAt(0) == compNum.charAt(0))
ans = 0;
Either courseNum or compNum are empty.
I did not try to compile and run it but its seems that the exception comes from this line
if(courseNum.charAt(0) == compNum.charAt(0))
If a string is empty, charAt(0) will throw exactly the given exception.
Tip: if you don't know how to use a debugger, use the old fashioned System.out.println(). Put println() here and there in your code to understand how it works.
I am attempting to sort the values in my program using the Bubble Sort method. I believe that my code in the organisedRoom method is correct. However when I run the code, add some customers and then attempt to sort them, the program crashes. If anyone can please point me in the right direction I would greatly appreciate it.
package test;
import java.io.IOException;
import java.util.Scanner;
public class Test {
private class Customer implements Comparable<Customer>{
private String name;
public Customer(String name) {
this.name = name;
}
//Override to stop the program returning memory address as string
#Override
public String toString() {
return name;
}
#Override
public int compareTo(Customer c) {
return name.compareTo(c.name);
}
}
//Array to store customers
public Customer[] customers;
public Scanner input = new Scanner(System.in);
public Test(int nRooms) throws IOException {
customers = new Test.Customer[nRooms];
System.out.println("Welcome to the Summer Tropic Hotel\n");
chooseOption();
}
final JFileChooser fc = new JFileChooser();
// Call new Hotel with int value to allocate array spaces
public static void main(String[] args) throws IOException {
Test t = new Test(11);
}
// New procedure to return User input and point to next correct method
private String chooseOption() throws IOException {
// Set to null, this will take user input
String choice;
//Menu options
System.out.println("This is the Hotel Menu. Please choose from the following options:\n");
System.out.println("A: " + "This will add a new entry\n");
System.out.println("O: " + "View booked rooms, in order of customers name.\n");
System.out.println("X: " + "Exit the program\n");
// Take user input and assign it to choice
choice = input.next();
// Switch case used to return appropriate method
switch (choice.toUpperCase()) {
case "A" :
System.out.println("");
addCustomer();
return this.chooseOption();
case "O" :
System.out.println("");
organisedRoom();
return this.chooseOption();
case "X":
System.exit(0);
}
return choice;
}
// Add a new customer to the Array
public void addCustomer() throws IOException {
// New variable roomNum
int roomNum = 1;
// Loop
do {
// Take user input as room number matching to array index - 1
System.out.println("Please choose a room from 1 to 10");
roomNum = input.nextInt() - 1;
// If room is already booked print this
if (customers[roomNum] != null) {
System.out.println("Room " + roomNum + 1 + " is not free, choose a different one.\n");
this.addCustomer();
}
// Do until array index does not equal to null
} while (customers[roomNum]!= null);
System.out.println("");
// User input added to array as name replacing null (non case-sensetive)
System.out.println("Now enter a name");
customers[roomNum] = new Customer(input.next().toLowerCase());
// Customer (name) added to room (number)
System.out.println(String.format("Customer %s added to room %d\n", customers[roomNum], roomNum + 1));
}
private void organisedRoom() {
boolean flag = true;
Customer temp;
int j;
while (flag) {
flag = false;
for (j = 0; j < customers.length - 1; j++) {
if (customers[j].compareTo(customers[j+1]) < 0) {
temp = customers[j];
customers[j] = customers[j + 1];
customers[j + 1] = temp;
flag = true;
}
}
}
}
}
I think this is because the initialisation of the array adds null to all the array index places.
The stack trace is as follows:
Exception in thread "main" java.lang.NullPointerException
at test.Test$Customer.compareTo(Test.java:34)
at test.Test.organisedRoom(Test.java:133)
at test.Test.chooseOption(Test.java:83)
at test.Test.chooseOption(Test.java:79)
at test.Test.chooseOption(Test.java:79)
at test.Test.<init>(Test.java:46)
at test.Test.main(Test.java:55)
Java Result: 1
It fails because you create Customer[] which will be initialized with11 null references. If you want to order them all elements in the array will be compared. Which lead into the java.lang.NullPointerException.
Store the Customer in an ArrayList. Then you should be able to prevent this error.
edit
If you really need to stick as close as possible to your current code. The following would fix your sorting. (don't use this solution for a real life project)
private void organisedRoom() {
for (int i = customers.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (customers[j + 1] == null) {
continue;
}
if (customers[j] == null ||customers[j + 1].compareTo(customers[j]) < 0) {
Customer temp = customers[j + 1];
customers[j + 1] = customers[j];
customers[j] = temp;
}
}
}
System.out.println("show rooms: " + Arrays.toString(customers));
}
edit 2
To keep most of your current code, you might store the room in the Customer instance (which I personally would not prefer).
// change the constructor of Customer
public Customer(String name, int room) {
this.name = name;
this.room = room;
}
// change the toString() of Customer
public String toString() {
return String.format("customer: %s room: %d", name, room);
}
// store the Customer like
customers[roomNum] = new Customer(input.next().toLowerCase(), roomNum);
Your implementation of Bubble Sort is incorrect. It uses nested for loops.
for(int i = 0; i < customers.length; i++)
{
for(int j = 1; j < (customers.length - i); j++)
{
if (customers[j-1] > customers[j])
{
temp = customers[j-1];
customers[j-1] = customers[j];
customers[j] = temp;
}
}
}
I'm having trouble understanding how to parse text documents with unknown amounts of 'students'. All my solutions are coming up strange and I'm having trouble with the Scanner. Breaking down the input, the first integer represents how many classes there are, the first string is the class name, the following are students with respective dates and variables that need to be stored along with the student, with an unknown amount of students. I want to store each student along with the class they are in.
My code is extremely messy and confusing so far:
String filename = "input.txt";
File file = new File(filename);
Scanner sc = new Scanner(file);
Student[] studArr = new Student[100];
int studCounter = 0;
boolean breaker = false;
boolean firstRun = true;
int numClasses = sc.nextInt();
System.out.println(numClasses);
while(sc.hasNextLine()){
String className = sc.nextLine();
System.out.println("Name: " + className);
String test = null;
breaker = false;
sc.nextLine();
// Breaks the while loop when a new class is found
while (breaker == false){
Student temp = null;
// Boolean to tell when the first run of the loop
if (firstRun == true){
temp.name = sc.nextLine();
}
else
temp.name = test;
System.out.println(temp.name);
temp.date = sc.nextLine();
if (temp.date.isEmpty()){
System.out.println("shit is empty yo");
}
temp.timeSpent = sc.nextInt();
temp.videosWatched = sc.nextInt();
temp.className = className;
studArr[studCounter] = temp;
studCounter++;
sc.nextLine();
test = sc.nextLine();
firstRun = false;
}
}
}
}
class Student {
public String name;
public String date;
public String className;
public int timeSpent;
public int videosWatched;
}
I don't need an exact answer, but should I be looking into a different tool then Scanner? Is there a method I can research?
Thanks for any assistance.
I came up with the following solution. Scanner is a fine tool for the job. The tricky part is that you have to sort of look ahead to see if you have a blank line or a date to know if you have a student or a class.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Parser {
private static String nextLine(Scanner sc) {
String line;
while (sc.hasNext()) {
if (!(line = sc.nextLine()).isEmpty()) {
return line;
}
}
return null;
}
public static ArrayList<Student>[] parseFile(String fileName) {
File file = new File(fileName);
try (Scanner sc = new Scanner(file)) {
int numClasses = sc.nextInt();
String className = nextLine(sc);
ArrayList<Student>[] classList = new ArrayList[numClasses];
for (int i = 0; i < numClasses; i++) {
classList[i] = new ArrayList<>();
while (true) {
String studentOrClassName = nextLine(sc);
if (studentOrClassName == null) {
break;
}
String dateOrBlankLine = sc.nextLine();
if (dateOrBlankLine.isEmpty()) {
className = studentOrClassName;
break;
}
int timeSpent = sc.nextInt();
int videosWatched = sc.nextInt();
classList[i].add(new Student(className, dateOrBlankLine, studentOrClassName, timeSpent,
videosWatched));
}
}
return classList;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return new ArrayList[0];
}
public static void main(String[] args) {
for (ArrayList<Student> students : parseFile("classList.txt")) {
if (!students.isEmpty()) {
System.out.println(students.get(0).className);
}
for (Student student : students) {
System.out.println(student);
}
}
}
static class Student {
public String className;
public String date;
public String name;
public int timeSpent;
public int videosWatched;
public Student(String className, String date, String name, int timeSpent,
int videosWatched) {
this.className = className;
this.date = date;
this.name = name;
this.timeSpent = timeSpent;
this.videosWatched = videosWatched;
}
public String toString() {
return name + '\n' + date + '\n' + timeSpent + '\n' + videosWatched + '\n';
}
}
}
Ask yourself, what does a Student contain? A name, date, number and number. So you want to do the following (not actual code) (format written in Lua code, very understandable. This means this will not run in Lua :P)
if line is not empty then
if followingLine is date then
parseStudent() // also skips the lines etc
else
parseClass() // also skips lines
end
end