I'm attempting to search through an object to see if a user's input matches what the program has stored, but I cannot figure out a way to make it work. I attempted to see if the value inputed by a user matched that of one in the userID spot for any of these Employee objects, but that didn't work. For example, here is the object:
Employee{userID='u1234567', userSalary=65000, userType=true}
Employee{userID='u1938562', userSalary=100000, userType=true}
Employee{userID='u1047218', userSalary=125000, userType=false}
Employee{userID='u1530078', userSalary=55000, userType=true}
Employee{userID='u1088621', userSalary=78400, userType=true}
Employee{userID='u2405234', userSalary=105000, userType=false}
Employee{userID='u1142592', userSalary=87500, userType=true}
Employee{userID='u1000092', userSalary=235000, userType=true}
Employee{userID='u1220433', userSalary=450000, userType=false}
Employee{userID='u1082304', userSalary=95000, userType=true}
My first function attempts to match the user's input with one of the userID's, but like I said it only works with the "u1234567"'s line. I have been attempting this for quite a while now, but I am relatively new to java and so I'm still learning. Below is my code, and where I commented out the "This is where I'm trying to loop through objects to look for a match" is where I would think to place this code, but I would greatly appreciate any feedback or better suggestions.
package homework4;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
public class main {
public static void main(String[] args) throws Exception {
// pass the path to the file as a parameter
Scanner file_in = new Scanner(new File("input.txt"));
Scanner in = new Scanner(System.in);
ArrayList<Employee> employees = new ArrayList<>();
// CREATE NEW ARRAY LIST FOR THE USERS
while (file_in.hasNextLine()) {
boolean isWorker = false;
String current_line = file_in.nextLine();
String[] line_split = current_line.split(",");
if (line_split[2].equals("1")) {
isWorker = true;
}
//Load the data To the List
employees.add(new Employee(line_split[0], Integer.parseInt(line_split[1]), isWorker));
}
ArrayList<Employee> copyEmployeesList1 = new ArrayList<>();
String userID = null;
//loop 4 times then create output.txt
for(int i = 0; i < 4; i++) {
// This is where I'm trying to loop through the object to look for a match
for(int b = 0; b < employees.size(); b++) {
employees.get(userID);
}
// User inputs userID and checks to see if theres a match
System.out.println("Enter employee ID of an employee?");
userID = in.nextLine();
for (Employee employee : employees){
if (employee.getUserID().equalsIgnoreCase(userID)) {
copyEmployeesList1.add(employee);
//System.out.println(employee);
break;
} else {
System.out.println("Incorrect value, please try again");
System.out.println("Enter employee ID of an employee?");
userID = in.nextLine();
break;
}
}
// User inputs user salary and checks if it matches the previous userID's lines salary.
System.out.println("Enter salary of the employee");
String userSalary = in.nextLine();
int userInput = Integer.parseInt(userSalary);
if(userInput == copyEmployeesList1.get(0).getUserSalary()) {
} else {
System.out.println("Incorrect value, please try again");
System.out.println("Enter salary of the employee");
}
// Redundant input my professor requires, but input a 1 or a 2
System.out.println("Is this in a manager or worker? (Enter 1 for worker 2 for manager)");
String userType = in.nextLine();
boolean choice;
choice = userType.equals("1");
employees.add(new Employee(userID, Integer.parseInt(userSalary), choice));
}
//compile salaries
for(Employee emp:employees) {
ManagerEmployee.calculate(emp);
WorkerEmployee.calculate(emp);
}
employees.forEach(System.out::println);
}
employees is an arraylist of Employee, you can only use .get to get by a specific index. You will need to use something like javas stream filter or a different method like in this tutorial.
ArrayList<Employee> employeesWithASpecificID = users.stream()
.filter(employee -> employee.getUserID() == userID)
.collect(Collectors.toList());
What I want to do is read a text file that has humans and animals. It will compile but has an error when I try to run it. I think I need a for loop to read the stringtokenizer to decipher between the human and animal in the txt file so far this is my driver class.
txt file:
Morely,Robert,123 Anywhere Street,15396,4,234.56,2
Bubba,Bulldog,58,4-15-2010,6-14-2011
Lucy,Bulldog,49,4-15-2010,6-14-2011
Wilder,John,457 Somewhere Road,78214,3,124.53,1
Ralph,Cat,12,01-16-2011,04-21-2012
Miller,John,639 Green Glenn Drive,96258,5,0.00,3
Major,Lab,105,07-10-2012,06-13-2013
King,Collie,58,06-14-2012,10-05-2012
Pippy,cat,10,04-25-2015,04-25-2015
Jones,Sam,34 Franklin Apt B,47196,1,32.09,1
Gunther,Swiss Mountain Dog,125,10-10-2013,10-10-2013
Smith,Jack,935 Garrison Blvd,67125,4,364.00,4
Perry,Parrot,5,NA,3-13-2014
Jake,German Shepherd,86,11-14-2013,11-14-2013
Sweetie,tabby cat,15,12-15-2013,2-15-2015
Pete,boa,8,NA,3-15-2015
Source:
import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.File;
import java.io.IOException;
/**
* This is my driver class that reads from a txt file to put into an array and uses the class refrences so it can use the menu and spit out
*
* #author ******
* #version 11/25/2015
*/
public class Driver
{
/**
* Constructor for objects of class Driver, what it does is read in the txt file gets the two class refrences and loops through to read through the whole file looking for string tokens to go to the next line
* and closes the file at the end also uses for loop to count number of string tokens to decipher between human and pets.
*/
public static void main(String[] args) throws IOException
{
Pet p;
Human h;
Scanner input;
char menu;
input = new Scanner(new File("clientdata.txt"));
int nBalance;
int id;
/**
* this while statement goes through each line looking for the string tokenizer ",". I want to count each "," to decipher between Human and Animal
*/
while(input.hasNext())
{
StringTokenizer st = new StringTokenizer(input.nextLine(), ",");
h = new Human();
h.setLastName(st.nextToken());
h.setFirstName(st.nextToken());
h.setAddress(st.nextToken());
h.setCiD(Integer.parseInt(st.nextToken()));
h.setVisits(Integer.parseInt(st.nextToken()));
h.setBalance(Double.parseDouble(st.nextToken()));
p = new Pet(st.nextToken(), st.nextToken(), Integer.parseInt(st.nextToken()), st.nextToken(), st.nextToken());
}
/**
* this is my seond while statement that loops the case switch statements and asks the user for client ID
*/
menu = 'Y';
while(menu == 'y' || menu == 'Y') {
System.out.print("\nChose one:\n A- client names and outstanding balance \n B- client's pets, name, type and date of last visit\n C-change the client's outstanding balance: ");
menu = input.next().charAt(0);
System.out.print("Enter client ID: ");
id = input.nextInt();
h = new Human();
if(id == h.getCiD())//if the id entered up top is equal to one of the id's in the txt file then it continues to the menu
{
p = new Pet();
switch(menu)
{ case 'A':
System.out.println("client name: " + h.getFirstName() + "outstanding balance: " + h.getBalance());
break;
case 'B':
System.out.println("pet's name: " + p.getName() + "type of pet: " + p.getTanimal() + "date of last visit: " + p.getLastVisit());
break;
case 'C':
System.out.println("what do you want to change the clients balances to?");
input.close();
}
}
else// if not then it goes to this If statement saying that the Client does not exist
{
System.out.println("Client does not exist.");
}
}
}
}
You have a number of issues you need to overcome...
For each line, you need to determine the type of data the line represents
You need some way to keep track of the data you've loaded (of the clients and their pets)
You need some way to associate each pet with it's owner
The first could be done in a number of ways, assuming we can change the data. You could make the first token meaningful (human, pet); you could use JSON or XML instead. But lets assume for the moment, you can't change the format.
The key difference between the two types of data is the number of tokens they contain, 7 for people, 5 for pets.
while (input.hasNext()) {
String text = input.nextLine();
String[] parts = text.split(",");
if (parts.length == 7) {
// Parse owner
} else if (parts.length == 5) {
// Parse pet
} // else invalid data
For the second problem you could use arrays, but you would need to know in advance the number of elements you will need, the number of people and for each person, the number of pets
Oddly enough, I just noticed that the last element is an int and seems to represent the number of pets!!
Morely,Robert,123 Anywhere Street,15396,4,234.56,2
------------^
But that doesn't help us for the owners.
For the owners, you could use a List of some kind and when ever you create a new Human, you would simply add them to the List, for example...
List<Human> humans = new ArrayList<>(25);
//...
if (parts.length == 7) {
// Parse the properties
human = new Human(...);
humans.add(human);
} else if (parts.length == 5) {
Thirdly, for the pets, each Pet should associated directly with the owner, for example:
Human human = null;
while (input.hasNext()) {
String text = input.nextLine();
String[] parts = text.split(",");
if (parts.length == 7) {
//...
} else if (parts.length == 5) {
if (human != null) {
// Parse pet properties
Pet pet = new Pet(name, type, age, date1, date2);
human.add(pet);
} else {
throw new NullPointerException("Found pet without human");
}
}
Okay, so all this does, is each time we create a Human, we keep a reference to the "current" or "last" owner created. For each "pet" line we parse, we add it to the owner.
Now, the Human class could use either a array or List to manage the pets, either will work, as we know the expected number of pets. You would then provide getters in the Human class to get a reference to the pets.
Because out-of-context code can be hard to read, this is an example of what you might be able to do...
Scanner input = new Scanner(new File("data.txt"));
List<Human> humans = new ArrayList<>(25);
Human human = null;
while (input.hasNext()) {
String text = input.nextLine();
String[] parts = text.split(",");
if (parts.length == 7) {
String firstName = parts[0];
String lastName = parts[1];
String address = parts[2];
int cid = Integer.parseInt(parts[3]);
int vists = Integer.parseInt(parts[4]);
double balance = Double.parseDouble(parts[5]);
int other = Integer.parseInt(parts[6]);
human = new Human(firstName, lastName, address, cid, vists, balance, other);
humans.add(human);
} else if (parts.length == 5) {
if (human != null) {
String name = parts[0];
String type = parts[1];
int age = Integer.parseInt(parts[2]);
String date1 = parts[3];
String date2 = parts[4];
Pet pet = new Pet(name, type, age, date1, date2);
human.add(pet);
} else {
throw new NullPointerException("Found pet without human");
}
}
}
What about using split() function instead of using StringTokenizer?
Say, You can change your first while loop like below:
while (input.hasNext()) {
// StringTokenizer st = new StringTokenizer(input.nextLine(), ",");
String[] tokens = input.nextLine().split(",");
if (tokens.length == 7) {
h = new Human();
h.setLastName(tokens[0]);
h.setFirstName(tokens[1]);
h.setAddress(tokens[2]);
h.setCiD(Integer.parseInt(tokens[3]));
h.setVisits(Integer.parseInt(tokens[4]));
h.setBalance(Double.parseDouble(tokens[5]));
} else {
p = new Pet(tokens[0], tokens[1], Integer.parseInt(tokens[2]), tokens[3], tokens[4]);
}
}
And for keeping track of which pet belongs to which human, you can append an arrayList of type Pet in Human class like below:
ArrayList<Pet> pets = new ArrayList<>();
And say you have another ArrayList of type Human named humans in the main function. So, you could append in if block like:
humans.add(h);
and in the else section, you could append in else block:
humans.get(humans.size()-1).pets.add(p);
You can try something like this -
Populate a map and then using that you can assign values according to your requirement.
public void differentiate(){
try {
Scanner scan=new Scanner(new BufferedReader(new FileReader("//your filepath")));
Map<String,List<String>> map=new HashMap<String, List<String>>();
while(scan.hasNextLine()){
List<String> petList=new ArrayList<String>();
String s=scan.nextLine();
String str[]=s.split(",");
String name=str[1]+" "+str[0];
int petCount=Integer.parseInt(str[str.length-1]);
for(int i=1;i<=petCount;i++){
String petString=scan.nextLine();
petList.add(petString);
}
map.put(name, petList);
}
Set<String> set=map.keySet();
for(String str:set){
System.out.println(str+" has "+map.get(str)+" pets");
}
}
catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
}
Pretty much for my assignment I have to List all the courses (just the course code) that have classes in a given building on a given day such that any part of the class is between the given times. Each course involved should only be listed once, even if it has several classes. I have done everything except listing the course once, even if it has several classes. How do I ignore duplicate strings from a file?
public void potentialDisruptions(String building, String targetDay, int targetStart, int targetEnd){
UI.printf("\nClasses in %s on %s between %d and %d%n",
building, targetDay, targetStart, targetEnd);
UI.println("=================================");
boolean containsCourse = false;
try {
Scanner scan = new Scanner(new File("classdata.txt"));
while(scan.hasNext()){
String course = scan.next();
String type= scan.next();
String day = scan.next();
int startTime = scan.nextInt();
int endTime = scan.nextInt();
String room = scan.next();
if(room.contains(building)){
if(day.contains(targetDay)){
if(endTime >= targetStart){
if( startTime<= targetEnd){
UI.printf("%s%n", course);
containsCourse = true;
}
}
}
}
}
if(!containsCourse){
UI.println("error");
}
}
catch(IOException e){
UI.println("File reading failed");
}
UI.println("=========================");
}
You can put all the string token in Set and check if that token contain in Set befor you process further as below :-
// Declration
....
Set courseSet = new HashSet();
...
// Check befor you process further
if(!courseSet.contains(course))
{
...
// Your Code...
...
courseSet.add(course)
}
You could put the courses in a Set and loop over them since a Set always contains unique values.
So basically what I need to do is:
Read a text file like this:
[Student ID], [Student Name], Asg 1, 10, Asg 2, 10, Midterm, 40, Final, 40
01234567, Timture Choi, 99.5, 97, 100.0, 99.0
02345678, Elaine Tam, 89.5, 88.5, 99.0, 100
and present it like this (with calculations of rank and average):
ID Name Asg 1 Asg 2 Midterm Final Overall Rank
01234567 Timture Choi 99.5 97.0 100.0 99.0 99.3 1
02345678
Elaine Tam 89.5 88.5 99.0 100.0 97.4 2
Average: 94.5 92.75 99.5 99.5 98.3
Using printf() function
now this is what I have done so far:
import java.io.*;
import java.util.Scanner;
class AssignmentGrades {
public static void main(String args[]) throws Exception {
Scanner filename = new Scanner(System.in);
String fn = filename.nextLine(); //scannig the file name
System.out.println("Enter your name of file : ");
FileReader fr = new FileReader(fn+".txt");
BufferedReader br = new BufferedReader (fr);
String list;
while((list = br.readLine()) !=null) {
System.out.println(list);
}
fr.close();
}
}
So I can ask the user for the name of the file, then read it and print.
Now.. I'm stuck. I think I need to probably put it in to array and split?
String firstrow = br.readLine();
String[] firstrow = firstrow.split(", ");
something like that?.. ugh ive been stuck here for more than an hour
I really need help!! I appreciate your attention!! ( I started to learn java this week)
There are two ways for splitting the input line just read from the file
Using String object's split() method which would return an array. Read more about the split here.
StringTokenizer Class - This class can be used to divide the input string into separate tokens based on a set of delimeter. Here is a good tutorial to get started.
You should be able to get more examples using google :)
In case you want to parse integers from String. Check this.
Here I store the columns as an array of Strings and I store the record set as an ArrayList of String arrays. In the while loop if the column set is not initialized yet (first iteration) I initialize it with the split. Otherwise I add the split to the ArrayList. Import java.util.ArrayList.
String[] columns = null;
ArrayList<String[]> values = new ArrayList<String[]>();
String list;
while((list = br.readLine()) !=null) {
if (columns != null) {
columns = list.split(", ");
} else {
values.add(list.split(", "));
}
}
fr.close();
When i try to run this code I keep getting this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Oblig3B.main(Oblig3B.java:8)
Here is my code:
import java.util.*;
import java.io.*;
class Oblig3B{
public static void main(String[]args){
OrdAnalyse oa = new OrdAnalyse();
Line 8. String filArgs=args[0];
oa.analyseMetode(filArgs);
}
}
class OrdAnalyse{
void analyseMetode(String filArgs){
Scanner input, innfil;
String[] ord;
int[] antall;
int antUnikeOrd, antOrd;
PrintWriter utfil;
boolean sjekk;
input=new Scanner(System.in);
ord=new String[5000];
antall=new int[5000];
antUnikeOrd=0;
antOrd=0;
sjekk=true;
try{
innfil=new Scanner(new File(filArgs));
//Here it reads the file, word by word.
while(innfil.hasNext()){
String ordLest=innfil.next().toLowerCase();
sjekk=false;
for(int i=0; i<ord.length; i++){
if(ordLest.equals(ord[i])){
antall[i]+=1;
sjekk=true;
}
}
if(!sjekk){
ord[antUnikeOrd]=ordLest;
antall[antUnikeOrd]++;
antUnikeOrd++;
}
antOrd++;
}
innfil.close();
}catch(Exception e){
e.printStackTrace();
}
try{
utfil=new PrintWriter(new File("Oppsummering.txt"));
utfil.println("Antall ord lest: " +antOrd+ " og antall unike ord: "+antUnikeOrd+"
"+ ord.length);
finnOrd(antall, ord, utfil);
for(int i=0; i<ord.length; i++){
utfil.println(ord[i]+(" ")+antall[i]);
}
utfil.close();
}catch(Exception e){
e.printStackTrace();
}
}
void finnOrd(int[] antall, String[] ord, PrintWriter utfil){
int teller=1000;
for(int i=0; i<ord.length; i++){
if(antall[i]>teller){
teller=antall[i];
}
double tiprosent=teller*0.90;
System.out.println(tiprosent + " " + teller);
for(i=0; i<ord.length; i++){
if(antall[i]>tiprosent){
utfil.println("Vanlige ord: "+ord[i]+"t("+antall[i]+" forekomster)");
}
}
}
}
}
I'm not sure what I need to do to fix this error. I would appreciate any help I can get.
(I'm sorry if the code is a bit messy, not sure how I can fix it properly here on stackoverflow)
Thanks alot
Java binds each argument passed to the application launched as an array to the String[] parameter in yourmain` method.
If you don't pass any arguments to the application launcher, for instance like
java Oblig3B
then the array bound will have size 0 and therefore
String filArgs = args[0];
trying to access the first element, at index 0, will fail. Check that you are actually passing arguments.
java Oblig3B "Some agument"
You didn't pass any command line arguments, so the args array is of zero-length. So, attempting any array access will throw an ArrayIndexOutOfBoundsException.
Test the length of the args array before attempting to access it. Here, make sure that the length is at least one before accessing args[0]. Something like:
if (args.length >= 1)
{
String filArgs=args[0];
// Do your processing.
}
else
{
// Handle the error here.
}
If you are running your program via command line you can pass one more parameter while running the command. If you are using an IDE e.g. eclipse you can pass the arguments by setting it via Properties -> Run/Debug settings
Basically, String filArgs=args[0]; is looking for first argument which doesn't exists