something wrong with the calculateWeeklypay methods of each employees - java

well i have now four types of employees. Managers (who receive a fixed weekly salary), Design workers (who receive a fixed hourly wage for up to the first 40 hours they work and "time-and-a-half," i.e., 1.5 times their hourly wage, for overtime hours worked), Sales workers (who receive a $250 plus 5.7% of their gross weekly sales), and Manufacturing (who receive a fixed amount of money per item for each of the items they produce -- each manufacture in this company works on only one type of item). and here are my classes:
employee class
the problem is i get this output:
You chose to open this file: Employees.txt
John Smith Manufacturing 6.75 120 444
0.0
Betty White Manager 1200.0 0 111
0.0
Stan Slimy Sales 10000.0 0 332
250.0
Betty Boop Design 12.5 50 244
0.0
meaning that it is getting 0 for all my calculations and leading to this weekly report:
WEEKLY PAY REPORT FOR Wacky Widgets COMPANY
Employee
0
WEEKLY PAY
250
Total Payroll: $0.0
Total number of managers paid:1
Total number of Design Employees paid:1
Total number of Sales Employees paid:1
Total number of Manufacturing Employees paid:1
i need help with fixing my methods so they can accept the integers of the file and use them in the calculation since all i'm getting at the moment are 0 values. i can provide my read-file method if it is need . thanks
here is the abstract class from which all the other employees type are extending from
[code]
public abstract class Employee {
public abstract double calculateWeeklyPay();
private String fName;
private String lName;
private int EmpId;
private Position p;
/*
public Employee()
{
}*/
/**
* default constructor
*/
public Employee() {
// TODO Auto-generated constructor stub
/*this.getFName();
this.getLName();
this.getEmpId();*/
getFName();
getLName();
this.getEmpId();
}
/**
* #param string first name
* #param string2 last name
* #param y position
*/
public Employee(String string, String string2, String y) {
fName = string;
lName = string2;
// EmpId=string3;
if (y.equals("Design")) {
p = Position.Design;
}
if (y.equals("Sales")) {
p = Position.Sales;
}
if (y.equals("Manufacturing")) {
p = Position.Manufacturing;
}
if (y.equals("Manager")) {
p = Position.Manager;
}
// StringTokenizer str=new StringTokenizer(fName+ lName+y,": .");
}
/**
* #return first name
*/
public String getFName() {
return fName;
}
/**
* #param firstName sets the first name
*/
public void setFName(String firstName) {
this.fName = firstName;
}
/**
* #return last name
*/
public String getLName() {
return lName;
}
/**
* #param lastName
*/
public void setLName(String lastName) {
this.lName = lastName;
}
/*public String toString()
{
// String str = firstName+" "+lastName+" "+"Position: "+getPosition();
return firstName;
}*/
/**
* #return p position
*/
public Position getPosition() {
// String str = firstName+" "+lastName+" "+"Position: "+getPosition();
return p;
}
public String toString() {
String str = fName + " " + lName + " " + "Position: " + getPosition();
return str;
}//https://www.udemy.com/blog/java-abstract-class/
public int getEmpId() {
return EmpId;
}
public void setEmpId(int empId) {
this.EmpId = empId;
}
}
design employee class
public class Design extends Employee {
public double rate;//rate for each hours
public double h;//hours worked
public Design(String fName, String lName, String pos) {
// TODO Auto-generated constructor stub
//double firstParam, int secondParam, int empNum
super(fName, lName, pos);
//toString();
calculateWeeklyPay();
}
#Override
public double calculateWeeklyPay() {
// TODO Auto-generated method stub
double weeklyPay = 0;
if (h <= 40) {
weeklyPay = h * rate;
}
if (h > 40) {
h = h * (3 / 2);
weeklyPay = h * rate;
}
//System.out.println(weeklyPay);
return weeklyPay;
}
public double getRate() {
return rate;
}
public void setRate(double rate) {
this.rate = rate;
}
public double getH() {
return h;
}
public void setH(double h) {
this.h = h;
}
}
sales employee
public class Sales extends Employee {
private double weekSales;
private final double pay = 250;
private final double percent = .057;
public Sales(String fName, String lName, String pos) {
// TODO Auto-generated constructor stub
super(fName, lName, pos);
this.calculateWeeklyPay();
}
#Override
public double calculateWeeklyPay() {
// TODO Auto-generated method stub
double weekPay;
weekPay = pay + percent * this.getWeekSales();
return weekPay;
}
public double getWeekSales() {
return weekSales;
}
public void setWeekSales(double weekSales) {
this.weekSales = weekSales;
}
}
and i have two other employee type of classes but they won't be needed here since if i fix the problem in this one class i can fix the others.
here's is my company class which reads a file a calculates the weekly pay and total weekly pay of all employees classes
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Company implements CompanyInterface {
//private Employee addEmp = new Employee();
// private Position addPosition = new
private ArrayList<Employee> list;
private static int numberOfCompanies;
private String CompanyName;
private int numDesign;
private int numEmployees;
private int numManufacturing;
private int numManager;
private int numSales;
/*String fName="";
String lName="";
String position="";
String first="";
String second="";
String empID="";
Scanner File;*/
//private ArrayList<Employee> list2 ;
private Employee addEmp;
/**
* #param cn is the company name
*/
public Company(String cn) {
cn = "Wacky Widgets";
list = new ArrayList<Employee>();
numDesign = 0;
numEmployees = 0;
numManufacturing = 0;
numSales = 0;
numberOfCompanies++;
setCompanyName(cn);
}
#Override
/**
* #param fName first name
* #param lName last name
* #param pos position
* #return null if everything is right
*/
public String addEmployee(String fName, String lName, String pos,
double firstParam, int secondParam, int empNum) {
String message = null;
// if (pos.equals("DESIGN")&&
numDesign == 1 && numSales != 2 && numManufacturing != 4)
if (pos.equals("Design")) {
if (numDesign == 2)//p2=Position.DESIGN;
{
message = "There are already 2 design persons\nEmployee not
added ";
} else {
addEmp = new Design(fName, lName, pos);
numDesign++;
numEmployees++;
list.add(addEmp);
}
}//else return message;
//if (pos.equals("SALES")&&numDesign<1&&numSales<2&&numManufacturing<4)
else if (pos.equals("Sales")) {
if (numSales == 1) {
message = "There is already a sales person\nEmployee not
added ";
} else {
//p2=Position.SALES;
addEmp = new Sales(fName, lName, pos);
numSales++;
numEmployees++;
list.add(addEmp);
}
}//else return message;
else if (pos.equals("Manufacturing")) {
if (numManufacturing == 4) {
message = "There are already four manufacturing persons
\nEmployee not added ";
} else {
//p2=Position.MANUFACTURING;
addEmp = new Manufacturing(fName, lName, pos);
numManufacturing++;
numEmployees++;
list.add(addEmp);
}
} else if (pos.equals("Manager")) {
if (numManager == 1) {
message = "There is already a manager person\nEmployee not
added ";
} else {
//p2=Position.MANUFACTURING;
addEmp = new Manufacturing(fName, lName, pos);
numManager++;
numEmployees++;
list.add(addEmp);
}
}
//String str=fName+" "+lName+" "+pos+" "+firstParam+" "+empNum;
System.out.println(fName + " " + lName + " " + pos + " " + firstParam + " " + secondParam + "
"+empNum);
//firstParam=Employee.
System.out.println(calculateTotalWeeklyPay());
return message;
}
/**
* Returns number of companies
*
* #return number of companies
*/
public static int getNumCompanies() {
return numberOfCompanies;
}
public void setNumCompanies(int nc) {
numberOfCompanies = nc;
}
/**
* Sets the number of employees
*
* #param ne number of employees
*/
public void setNumemployees(int ne) {
numEmployees = ne;
}
/**
* Returns the number of employees
*
* #return the number of employees
*/
public int getNumEmployees() {
return numEmployees;
}
#Override
public int getNumManager() {
return numManager;
}
/**
* sets the number of designer
*
* #param nd number of designer
*/
public void setNumDesign(int num) {
numDesign = num;
}
#Override
public int getNumDesign() {
return numDesign;
}
public void setNumsales(int num) {
numSales = num;
}
#Override
public int getNumSales() {
return numSales;
}
/**
* Sets the number of manufacturer
*
* #param nm the number of manufacturer
*/
public void setNumManufacturing(int num) {
numManufacturing = num;
}
#Override
public int getNumManufacturing() {
return numManufacturing;
}
public void setNumManager(int num) {
numManager = num;
}
#Override
public String generateWeeklyReport() {
int empID = 0;
String title = "WEEKLY PAY REPORT FOR " + getCompanyName() + " COMPANY" + "\n";
String label = "Employee\n";
String label2 = "WEEKLY PAY \n";
int payWeek = 0;
double total = 0.0;
for (Employee index : list) {
empID += index.getEmpId();
payWeek += index.calculateWeeklyPay();
}
return title + label + empID + "\n" + "\t" + label2 + payWeek + "\n" + "Total Payroll:
$ "+total+"\n "+
"Total number of managers paid:" + getNumManager() + "\n" +
"Total number of Design Employees paid:" + getNumDesign() + "\n" +
"Total number of Sales Employees paid:" + getNumSales() + "\n" +
"Total number of Manufacturing Employees paid:" + getNumManufacturing();
}
#Override
public double calculateTotalWeeklyPay() {
double total = 0;
for (int index = 0; index < list.size(); index++) {
total = list.get(index).calculateWeeklyPay();
//total.add(list.get(index).calculateWeeklyPay());
}
return total;
}
/**
* #return str the arraylist of employees and positions
*/
public String printCompany() {
// TODO Auto-generated method stub
String str = "";
for (int index = 0; index < list.size(); index++) {
str += list.get(index).getFName() + " " + list.get(index).getLName() + "
"+" Position:
"+list.get(index).getPosition()+"\n ";
}//System.out.println(str);
return str;
}
/**
* #return company name
*/
public String getCompanyName() {
return CompanyName;
}
public void setCompanyName(String companyName) {
//companyName="Wacky Widgets";
this.CompanyName = companyName;
}
public String toString() {
// int i =0;
String str = CompanyName + "";
//String str = "";
for (int i = 0; i < list.size(); i++) {
str += "\n" + list.get(i).getFName() + " " + list.get(i).getLName() + "
"+" Position:
"+list.get(i).getPosition()+"\n ";
}
return str;
}
}

This stands out:
h = h * (3 / 2);
You're doing integer division here, so you're always multiplying by 1, effectively.
Change that to use floating-point values instead.
h = h * (3.0 / 2);
Alternatively, be explicit about what you're multiplying by - you know it's always time and a half, so I see no reason not to do this:
h = h * 1.5;

Related

Problem with finding the highest exam range

I have an assignment that requires me to create a method called getExamRange that looks at an array which includes the exam scores of several students, takes the lowest and highest scores, and subtracts the minimum exam score from the maximum exam score. I also have to create a getMostImprovedStudent which run the getExamRange method on an array of Students and returns the student with the highest exam range. I'm having trouble getting the correct results when the code is run. What is causing this problem?
Here is the code for the Student.java class:
import java.util.*;
public class Student
{
private static final int NUM_EXAMS = 4;
private String firstName;
private String lastName;
private int gradeLevel;
private double gpa;
private int[] exams;
private int numExamsTaken;
/**
* This is a constructor. A constructor is a method
* that creates an object -- it creates an instance
* of the class. What that means is it takes the input
* parameters and sets the instance variables (or fields)
* to the proper values.
*
* Check out StudentTester.java for an example of how to use
* this constructor.
*/
public Student(String fName, String lName, int grade)
{
firstName = fName;
lastName = lName;
gradeLevel = grade;
exams = new int[NUM_EXAMS];
numExamsTaken = 0;
}
public int getExamRange()
{
Arrays.sort(exams);
int examScore1 = exams[0];
int examScore2 = 0;
int lastPos = 0;
for(int i = 0; i < exams.length - 1; i++)
{
lastPos++;
}
examScore2 = exams[lastPos];
return examScore2 - examScore1;
}
public String getName()
{
return firstName + " " + lastName;
}
public void addExamScore(int score)
{
exams[numExamsTaken] = score;
numExamsTaken++;
}
// This is a setter method to set the GPA for the Student.
public void setGPA(double theGPA)
{
gpa = theGPA;
}
/**
* This is a toString for the Student class. It returns a String
* representation of the object, which includes the fields
* in that object.
*/
public String toString()
{
return firstName + " " + lastName + " is in grade: " + gradeLevel;
}
}
and here is the code for the Classroom.java class:
public class Classroom
{
Student[] students;
int numStudentsAdded;
public Classroom(int numStudents)
{
students = new Student[numStudents];
numStudentsAdded = 0;
}
public Student getMostImprovedStudent()
{
int highestScore = 0;
int score = 0;
int location = 0;
int finalLocation = 0;
for(Student s: students)
{
score = s.getExamRange();
location++;
if(score > highestScore)
{
highestScore = score;
finalLocation = location;
}
}
return students[finalLocation - 1];
}
public void addStudent(Student s)
{
students[numStudentsAdded] = s;
numStudentsAdded++;
}
public void printStudents()
{
for(int i = 0; i < numStudentsAdded; i++)
{
System.out.println(students[i]);
}
}
}
Here are the directions for the assignment which state what the methods are supposed to do:
Taking our Student and Classroom example from earlier, you should fill in the method getMostImprovedStudent, as well as the method getExamRange. The most improved student is the one with the largest exam score range.
To compute the exam score range, you must subtract the minimum exam score from the maximum exam score.
For example, if the exam scores were 90, 75, and 84, the range would be 90 - 75 = 15.
Firstly let us look at the getExamRange function
public int getExamRange(){
if(exams == null ||exams.length == 0){
return 0;
}
int min = exams[0];
int max = exams[0];
for (int i : exams
) {
if(i<min){
min=i;
}
if(i>max){
max=i;
}
}
return max - min;
}
and now on getMostImprovedStudent
public Student getMostImprovedStudent()
{
if(students == null ||students[0] == null || students.length=0){
return null;
}
int highestScore = students[0].getExamRange();
int score = 0;
Student mostImprovedStudent = students[0]
for(int i=0;i<students.length;i++)
{
if(students[i]!=null){
score = students[i].getExamRange();
if(score > highestScore)
{
highestScore = score;
mostImprovedStudent = students[i];
}
}
}
return mostImprovedStudent;
}

Converting the same String value into an Object

I have an object share:
Share tea = new Share("TEA", "Common", 0, 100);
ArrayList<Share> shares = new ArrayList<Share>();
shares.add(tea);
What I'd like to do is, reading parameters from the keybord, convert directly the "tea" string into a share tea object :
Trade trade = new Trade( tea, Boolean.parseBoolean(buyOrSell), Integer.parseInt(quantity), Double.parseDouble(tradePrice));
What should I put instead of tea because my constructor is waiting a Share and not a String. The user is entering a string and I don't need ton create a new instance, I have to use the Share object "tea" that already exists.
The Share.java class :
public class Share {
private String shareSymbol = "";
private String type = "Common";
private double lastDividend = 0;
private double fixedDividend = 0;
private int parValue = 0;
// Calucul values
public String getShareSymbol() {
return shareSymbol;
}
public String getType() {
return type;
}
public double getLastDividend() {
return lastDividend;
}
public double getFixedDividend() {
return fixedDividend;
}
public int getParValue() {
return parValue;
}
// Constructor without Fixed Dividend
public Share(String shareSymbol, String type, int lastDividend, int parValue) {
this.shareSymbol = shareSymbol;
this.type = type;
this.lastDividend = lastDividend;
this.parValue = parValue;
}
// Constructor with Fixed Dividend
public Share(String shareSymbol, String type, int lastDividend,
int fixedDividend, int parValue) {
this(shareSymbol, type, lastDividend, parValue);
this.fixedDividend = fixedDividend / 100.0;
}
public String toString(){
String result="";
result += shareSymbol + " "+type + " " + lastDividend + " " + fixedDividend + " " + parValue + "\n";
return result;
}
}
The Trade.java class :
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
// The class trade allows the stock, the quantity and the price to be intialised
public class Trade {
Share share;
private int quantity;
double price;
private double dividendYield;
private double pERatio;
private boolean buyOrSell;
private Date tradeDate;
public Trade(Share share, boolean buyOrSell, int quantity, double price) {
this.share = share;
this.buyOrSell = buyOrSell;
this.quantity = quantity;
this.price = price;
tradeDate = Calendar.getInstance().getTime();
}
public String toString() {
String result = "";
result += "stock symbol : " + share.getShareSymbol() + " \n";
result += "Buy or Sell : " + buyOrSell + " \n";
result += "quantity :" + quantity + " \n";
result += "price : " + price + " \n";
result += "Dividend Yield : " + dividendYield + " \n";
result += "P/E Ratio : " + pERatio + " \n";
result += "tradeDate : " + tradeDate + " \n\n";
return result;
}
public Share getShare() {
return share;
}
public int getQuantity() {
return quantity;
}
public double getPrice() {
return price;
}
public double getDividendYield() {
return dividendYield;
}
public double getpERatio() {
return pERatio;
}
public Date getTradeDate() {
return tradeDate;
}
public double calcDividendYield() {
if ("Common".equalsIgnoreCase(share.getType())) {
dividendYield = share.getLastDividend() / price;
} else if ("Preferred".equalsIgnoreCase(share.getType())) {
dividendYield = share.getFixedDividend() * share.getParValue()
/ price;
}
return dividendYield;
}
public double calcPERatio() {
if (dividendYield > 0)
pERatio = price / dividendYield;
return pERatio;
}
}
Your constructor is waiting a share. So give it:
/* Read parameters from keyboard, stock in s1, s2, i1 and i2 variables */
Trade trade = new Trade( new Share(s1,s2,i1,i2), Boolean.parseBoolean(buyOrSell), Integer.parseInt(quantity), Double.parseDouble(tradePrice));
Otherwise you can implement a method (in Share class) that do it for you
public static Share stringToShare(String s1, String s2, int t1, int t2){
return new Share(s1, s2, t1, t2);
}
And then:
Trade trade = new Trade( Share.stringToShare(...), Integer.parseInt(quantity), Double.parseDouble(tradePrice));
EDIT: better use real variable names that means something, not s1, s2, etc.
I've got around of this, by creating a new constructor :
Trade trade = new Trade(shares, stockSymbol, Boolean.parseBoolean(buyOrSell),
Integer.parseInt(quantity), Double.parseDouble(tradePrice));
This is then the new constructor :
public Trade(ArrayList<Share> shares, String stockSymbol,
boolean buyOrSell, int quantity, double price) {
Iterator<Share> iter = shares.iterator();
int index = -1;
while (iter.hasNext()) {
Share share = iter.next();
index++;
if (stockSymbol.equalsIgnoreCase((share.getShareSymbol()))) {
this.share = shares.get(index);
this.buyOrSell = buyOrSell;
this.quantity = quantity;
this.price = price;
tradeDate = Calendar.getInstance().getTime();
break;
}
}
}
It's a bit complacated, because I had also to create a new method to get the Share for the given String(having the same name, for instance). But that does What i needed.
It would be cleaner though to make it with Java Reflection, without having to create a new constructor. So if any one have an idea with a code more clever, I would be happy!

Handling blank lines with txt input file and Scanner

I have my program complete. The one thing I need is a way for it to handle blank lines. I have read other posts but none have helped me implement them into my own code. I've tried various syntax within the loop that reads the file, but none have worked. Can someone help me please. This seems like it should be easier than it feels like currently. I'm trying to implement this into my code but am having trouble doing it. Below are my two classes and the input.txt. As is, this program runs as intended. Thanks for any help.
String line = in.nextLine();
while (line.length() == 0) {
if (in.hasNext()) {
line = in.nextLine();
} else {
break;
}
}
if (line.length() == 0) {
// reaches the end of input file
}
Product.java
/**
* Product
*
* A simple class framework used to demonstrate the design
* of Java classes.
*
* #author
* #version 02042015
*/
import java.util.*;
public class Product {
private String name;
private String code;
private int quantity;
private double price;
private String type;
private ArrayList<Integer> userRatings;
/*
* Product constructor
*/
public Product() {
name = "";
code = "";
quantity = 0;
price = 0.0;
type = "";
userRatings = new ArrayList<Integer>();
}
public Product(Product productObject) {
this.name = productObject.getName();
this.code = productObject.getInventoryCode();
this.quantity = productObject.getQuantity();
this.price = productObject.getPrice();
this.type = productObject.getType();
this.userRatings = new ArrayList<Integer>();
}
public Product(String name, String code, int quantity, double price, String type) {
this.name = name;
this.code = code;
this.quantity = quantity;
this.price = price;
this.type = type;
this.userRatings = new ArrayList<Integer>();
}
/*
* setName
* #param name - new name for the product
*/
public void setName(String name) {
this.name = name;
}
/*
* getName
* #return the name of the product
*/
public String getName() {
return name;
}
/*
* setType
* #param type - the type of the product
*/
public void setType(String type) {
this.type = type;
}
/*
* getType
* #return - the product type
*/
public String getType() {
return type;
}
/*
* setPrice
* #param price - the price of the product
*/
public void setPrice(double price) {
this.price = price;
}
/*
* getPrice
* #return the price of the product
*/
public double getPrice() {
return price;
}
/*
* setQuantity
* #param quantity - the number of this product in inventory
*/
public void setQuantity(int quantity) {
this.quantity = quantity;
}
/*
* getQuantity
* #return the number of this product in inventory
*/
public int getQuantity() {
return quantity;
}
/*
* setInventoryCode
* #param code - the new inventory code for the product
*/
public void setInventoryCode(String code) {
if(code.length()!= 8){
System.out.println("An invalid code has been entered. Please enter a code that is 8 characters in length.");
}
else{
}
this.code=code;
}
/*
* getInventoryCode
* #return the inventory code of the product
*/
public String getInventoryCode() {
return code;
}
/*
* setRatings
* #param code the new set of ratings for the product
*/
public void setRatings(ArrayList<Integer> Ratings){
this.userRatings = Ratings;
}
/*
* getRatings
* #return the ratings of the product
*/
public ArrayList<Integer> getRatings(){
return userRatings;
}
/*
* addUserRating
* NOTE: Each individual rating is stored with the product, so you need to maintain a list
* of user ratings. This method should append a new rating to the end of that list
* #param rating - the new rating to add to this product
*/
public void addUserRating(Integer rating1) {
if(rating1 > 5 || rating1 < 0){
System.out.println("You have entered an invalid rating. Please enter a rating between one and five stars.");
}
this.userRatings.add(rating1);
}
/*
* getUserRating
* NOTE: See note on addUserRating above. This method should be written to allow you
* to access an individual value from the list of user ratings
* #param index - the index of the rating we want to see
* #return the rating indexed by the value index
*/
public int getUserRating(int index) {
int a = this.userRatings.get(index);
return a;
}
/*
* getUserRatingCount
* NOTE: See note on addUserRating above. This method should be written to return
* the total number of ratings this product has associated with it
* #return the number of ratings associated with this product
*/
public int getUserRatingCount() {
int a = this.userRatings.size();
return a;
}
/*
* getAvgUserRating
* NOTE: see note on addUserRating above. This method should be written to compute
* the average user rating on demand from a stored list of ratings.
* #return the average rating for this product as a whole integer value (use integer math)
*/
public String getAvgUserRating() {
int sum = 0;
String avgRating = "";
if (userRatings.size() != 0){
for (int i = 0; i < this.userRatings.size(); i++) {
int a = getUserRating(i);
sum += a;
}
double avg = sum/this.userRatings.size();
if(avg >= 3.5){
avgRating = "****";
}
else if(avg >= 2.5){
avgRating = "***";
}
else if(avg >= 1.5){
avgRating = "**";
}
else if(avg >= 0.5){
avgRating = "*";
}
else{
}
}
else{
avgRating = "";
}
return avgRating;
}
}
Project02.java
/**
* Inventory Reporting Program
*
* A simple set of methods used to report and summarize
* the information read from an inventory file of product data
*
* #author
* #version 02042015
*/
import java.util.*;
import java.io.*;
public class Project02 {
public static void main(String[] args) {
//Establish the scanner so user input can be properly read.
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter an inventory filename: ");
String fname = keyboard.nextLine();
ArrayList<Product> products = loadProducts(fname);
generateSummaryReport(products);
highestAvgRating(products);
lowestAvgRating(products);
largestTotalDollarAmount(products);
smallestTotalDollarAmount(products);
}
public static void generateSummaryReport (ArrayList<Product> Products){
int counter = 0;
System.out.println("Product Inventory Summary Report");
System.out.println("----------------------------------------------------------------------------------");
System.out.println();
System.out.printf("%-33s%-10s%-6s%-7s%-7s%-7s%-7s", "Product Name", "I Code", "Type", "Rating", "# Rat.", "Quant.", "Price");
System.out.println();
System.out.printf("%-33s%-10s%-6s%-7s%-7s%-7s%-7s", "-------------------------------", "---------", "----", "------", "------", "------", "------");
System.out.println();
while(counter < Products.size()){
System.out.printf("%-33s%-10s%-6s%-7s%6s%7s%7s", Products.get(counter).getName(), Products.get(counter).getInventoryCode(), Products.get(counter).getType(), Products.get(counter).getAvgUserRating(), Products.get(counter).getUserRatingCount(), Products.get(counter).getQuantity(), Products.get(counter).getPrice());
System.out.println();
counter++;
}
System.out.println("----------------------------------------------------------------------------------");
System.out.println("Total products in the database: " + Products.size());
}
/*
* loadProducts
* Given a filename, opens the file and reads Products from
* the file into an ArrayList of Product objects. Returns
* the ArrayList.
*
*
* #param fname - String containing the input file name
* #return - An ArrayList of Product objects
*/
public static ArrayList<Product> loadProducts(String fname) {
int a = 0;
Integer b = 0;
ArrayList<Product> products = new ArrayList<Product>();
try {
Scanner inFile = new Scanner(new File(fname));
while (inFile.hasNext()) {
int counter = 0;
String name = inFile.nextLine();
String code = inFile.nextLine();
int quantity = inFile.nextInt();
double price = inFile.nextDouble();
String type = inFile.next();
Product productObject = new Product(name, code, quantity, price, type);
while(inFile.hasNextInt() && counter==0){
a = inFile.nextInt();
if(a != -1){
b = new Integer(a);
productObject.addUserRating(b);
}
else{
counter = 1;
}
}
products.add(productObject);
if(inFile.hasNext()){
inFile.nextLine();
}
}
inFile.close();
}
catch (FileNotFoundException e) {
System.out.println("ERROR: " + e);
}
return products;
}
//Finds the item with the highest average user rating in stock
public static void highestAvgRating(ArrayList<Product> Products){
int counter = 0;
int a = 1;
while (counter <= Products.size()-1){
if(Products.get(counter).getAvgUserRating().length() > Products.get(a).getAvgUserRating().length()){
a = counter;
}
else{
}
counter++;
}
System.out.println("Highest Average User Rating In Stock: " + Products.get(a).getName() + " ("+Products.get(a).getAvgUserRating() + ")");
}
//Finds the item with the lowest average user rating in stock
public static void lowestAvgRating(ArrayList<Product> Products){
int counter = 0;
int a = 1;
while (counter <= Products.size()-1){
if(Products.get(counter).getAvgUserRating().length()<Products.get(a).getAvgUserRating().length()){
a=counter;
}
else{
}
counter++;
}
System.out.println("Lowest Average User Rating In Stock: "+Products.get(a).getName() + " ("+Products.get(a).getAvgUserRating() + ")");
}
//Finds the item with the largest total dollar amount in inventory (quantity * price)
public static void largestTotalDollarAmount(ArrayList<Product> Products){
int counter = 0;
int a = 1;
while (counter <= Products.size()-1){
if((Products.get(counter).getPrice())*(Products.get(counter).getQuantity()) > ((Products.get(a).getPrice())*(Products.get(a).getQuantity()))){
a=counter;
}
else{
}
counter++;
}
System.out.println("Item With The Largest Total Dollar Amount In Inventory: " + Products.get(a).getName() + " ($" + ((Products.get(a).getPrice())*(Products.get(a).getQuantity())) + ")");
}
//Finds the item with the smallest total dollar amount in inventory (quantity * price)
public static void smallestTotalDollarAmount(ArrayList<Product> Products){
int counter = 0;
int a = 1;
while (counter <= Products.size()-1){
if((Products.get(counter).getPrice())*(Products.get(counter).getQuantity()) < ((Products.get(a).getPrice())*(Products.get(a).getQuantity()))){
a=counter;
}
else{
}
counter++;
}
System.out.println("Item With The Smallest Total Dollar Amount In Inventory: " + Products.get(a).getName() + " ($" + ((Products.get(a).getPrice())*(Products.get(a).getQuantity())) + ")");
}
}
input.txt
The Shawshank Redemption
C0000001
100
19.95
DVD
4
5
3
1
-1
The Dark Knight
C0000003
50
19.95
DVD
5
2
3
-1
Casablanca
C0000007
137
9.95
DVD
5
4
5
3
-1
The Girl With The Dragon Tattoo
C0000015
150
14.95
Book
4
4
2
-1
Vertigo
C0000023
55
9.95
DVD
5
5
3
5
2
4
-1
A Game of Thrones
C0000019
100
8.95
Book
-1
When you decompose your question, you find there are two main concerns:
Read the input line-by-line
Skip the blank lines.
The first concern can be addressed with while (in.hasNext) in.nextLine(). To address the second concern, simply add a continue when you find the line is empty:
while (in.hasNextLine()) {
line = in.nextLine();
// skip blank lines
if (line.length() == 0) continue;
// do your magic
}
Now, how to get this in to your main program? It would be nice if we could somehow do: inFile.nextNonBlankLine(), right? So let's create our own scanner that has that method!
First things first, how would we like to use our own scanner? One example could be:
SkipBlankScanner in = new SkipBlankScanner(inFile);
while (in.hasNextNonBlankLine()) {
line = in.nextNonBlankLine();
}
Unfortunately Scanner is a final class, so we can't extend it to add our functionality. The next best thing is to use a delegate:
public class SkipBlankScanner {
private Scanner delegate;
private String line;
public SkipBlankScanner(Scanner delegate) {
this.delegate = delegate;
}
public boolean hasNextNonBlankLine() {
while (delegate.hasNextLine())
// return true as soon as we find a non-blank line:
if ((line = delegate.nextLine()).length > 0)
return true;
// We've reached the end and didn't find any non-blank line:
return false;
}
public String nextNonBlankLine() {
String result = line;
// in case we didn't call "hasNextNonBlankLine" before:
if (result == null && hasNextNonBlankLine())
result = line;
// try to read past the end:
if (result == null) throw new IllegalStateException();
line = null;
return result;
}
}
And there you have it, your very own Scanner that will ignore blank lines!
You could take this even further, and create a Scanner that will scan for entire Products, e.g. (with some Java-8):
public class ProductScanner {
private SkipBlankScanner scanner;
private Product product;
public ProductScanner(SkipBlankScanner scanner) {
this.scanner = scanner;
}
public boolean hasNextProduct() {
Product next = new Product();
if (fill(line -> next.setTitle(line)) &&
fill(line -> next.setInventoryCode(line)) &&
fill(line -> next.setQuantity(Integer.parseInt(line))) &&
fill(line -> next.setPrice(Double.parseDouble(line))) &&
fill(line -> next.setType(line))) {
try {
while (scanner.hasNextNonBlankLine() {
int rating = Integer.parseInt(scanner.nextNonBlankLine());
if (rating < 0) {
product = next;
return true;
}
next.addUserRating(rating);
}
} catch (NumberFormatException e) {
}
}
return false;
}
private boolean fill(Consumer<String> action) {
if (scanner.hasNextNonBlankLine() {
try {
action.accept(scanner.nextNonBlankLine());
return true;
} catch (Exception e) {
}
}
return false;
}
public Product nextProduct() {
Product result = product;
if (result == null && hasNextProduct())
result = product;
if (result == null)
throw new IllegalStateException();
product = null;
return result;
}
}

Data validation to an throw exception

I am trying to read in a figure for a brokers earnings for quarter one of the year.I want to ensure that 0 or less can not be entered but when I enter 0 it just takes it in anyway and does not throw the exception?
What am I doing wrong?Any help would be greatly appreciated.
public void setQuarter1(double newQuarter1)
{
if ( newQuarter1 > 0)
quarter1 = newQuarter1;
else
throw new IllegalArgumentException("new quarter must be > 0.0");
}
Ok heres my whole assignment code
import java.util.Scanner;
public class Broker {
//(a) declare instance variables
private String department, firstName, lastName;
private double quarter1, quarter2, quarter3, quarter4;
//(b) Access methods for instance variables
public void setDepartmentName(String newName)
{
department=newName;
}
public String getDepartment ()
{
return department;
}
//set and get methods for first name
public void setFirstName (String newFirstName)
{
firstName=newFirstName;
}
public String getFirstName ()
{
return firstName;
}
//set and get methods for last name
public void setLastName(String newLastName)
{
lastName=newLastName;
}
public String getLastName ()
{
return lastName;
}
//set and get methods for Quarter 1
public void setQuarter1(double newQuarter1)
{
if ( newQuarter1 > 0)
quarter1 = newQuarter1;
else
throw new IllegalArgumentException(
"new quarter must be > 0.0");
}
public double getQuarter1()
{
return quarter1;
}
//set and get methods for Quarter 2
public void setQuarter2(double newQuarter2)
{
quarter2 = newQuarter2;
}
public double getQuarter2 ()
{
return quarter2;
}
//set and get methods for Quarter 3
public void setQuarter3(double newQuarter3)
{
quarter2 = newQuarter3;
}
public double getQuarter3 ()
{
return quarter3;
}
//set and get methods for Quarter 4
public void setQuarter4(double newQuarter4)
{
quarter4 = newQuarter4;
}
public double getQuarter4 ()
{
return quarter4;
}
//(c) class variable annualbrokerage total and two access methods
private static double brokerageTotal;
public void setbrokerageTotal(double newBrokerageTotal)
{
newBrokerageTotal=brokerageTotal;
}
//(c) constructor to initialise instance variables department,firstname and lastname
public Broker (String dept, String first, String last )
{
department = dept;
firstName = first;
lastName = last;
}
// (d) constructor to initialise all instance variables from (a)
public Broker (String dept, String first, String last,double q1,double q2,double q3,double q4 )
{
department = dept;
firstName = first;
lastName = last;
quarter1 = q1;
quarter2 = q2;
quarter3 = q3;
quarter4 = q4;
}
// (e) no-argument constructor to initialise default broker instance
public Broker ()
{
department = null;
firstName = null;
lastName = null;
quarter1 = 0;
quarter2 = 0;
quarter3 = 0;
quarter4 = 0;
}
//(f) Method to read in quarters from user
public void readInQuarters ()
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter Q1,Q2,Q3 and Q4 figures for broker:");
quarter1 = input.nextInt();
quarter2 = input.nextInt();
quarter3 = input.nextInt();
quarter4 = input.nextInt();
} //end of read in quarters method
// (g) getBrokerTotal Method to return total trades for 4 quarters
public double getBrokerTotal()
{
//code to calculate broker quarterly totals
double brokerTotal = quarter1 + quarter2 + quarter3 + quarter4;
return brokerTotal;
} //end of getBrokerTotal method
//(e) getBonus method to calculate brokers bonus
public double getBonus()
{
double bonusRate=0;
double bonus=0;
//bonus rate depending on department rate
if("Dublin"==department)
bonusRate=.12;
else if("London"==department)
bonusRate=.15;
else
bonusRate=.10;
bonus = (quarter1 + quarter2 + quarter3 + quarter4)*(bonusRate);
return bonus;
}
//(i) to string method for broker class
public String toString()
{
return String.format(" Name: "+ getFirstName()+"\n Surname: "+getLastName()+"\n Department: "+getDepartment()+"\n Total: "+getBrokerTotal()+"\n Bonus: "+getBonus()+"\n\n");
}//end of toString method
//(i) Static methods to read in broker array and output quarterly totals
//Quarter1 totals method
public static double getQuarter1Total (Broker[]brokerQuarter1Array)
{
double quarter1Total = brokerQuarter1Array[0].getQuarter1()+ brokerQuarter1Array[1].getQuarter1()+ brokerQuarter1Array[2].getQuarter1()+ brokerQuarter1Array[3].getQuarter1()
+ brokerQuarter1Array[4].getQuarter1() + brokerQuarter1Array[5].getQuarter1();
return quarter1Total;
}
//Quarter2 totals method
public static double getQuarter2Total (Broker[]brokerQuarter2Array)
{
double quarter2Total = brokerQuarter2Array[0].getQuarter2()+ brokerQuarter2Array[1].getQuarter2()+ brokerQuarter2Array[2].getQuarter2()+ brokerQuarter2Array[3].getQuarter2()
+ brokerQuarter2Array[4].getQuarter2() + brokerQuarter2Array[5].getQuarter2();
return quarter2Total;
}
//Quarter3 totals method
public static double getQuarter3Total (Broker[]brokerQuarter3Array)
{
double quarter3Total = brokerQuarter3Array[0].getQuarter3()+ brokerQuarter3Array[1].getQuarter3()+ brokerQuarter3Array[2].getQuarter3()+ brokerQuarter3Array[3].getQuarter3()
+ brokerQuarter3Array[4].getQuarter3() + brokerQuarter3Array[5].getQuarter3();
return quarter3Total;
}
//Quarter4 totals method
public static double getQuarter4Total (Broker[]brokerQuarter4Array)
{
double quarter4Total = brokerQuarter4Array[0].getQuarter4()+ brokerQuarter4Array[1].getQuarter4()+ brokerQuarter4Array[2].getQuarter4()+ brokerQuarter4Array[3].getQuarter4()
+ brokerQuarter4Array[4].getQuarter4() + brokerQuarter4Array[5].getQuarter4();
return quarter4Total;
}
// Static method to calculate total brokerage totals for all brokers
public static void setBrokerageTotal (Broker[] brokerTotalsArray)
{
double annualBrokerageTotal= brokerTotalsArray[0].getBrokerTotal() + brokerTotalsArray[1].getBrokerTotal()
+ brokerTotalsArray[2].getBrokerTotal() + brokerTotalsArray[3].getBrokerTotal() + brokerTotalsArray[4].getBrokerTotal() + brokerTotalsArray[5].getBrokerTotal();
}
// Static method to get the total bonuses for all brokers cobined
public static double getBrokerageBonus (Broker [] brokerageBonusTotalArray)
{
double totalBrokerageBonus = brokerageBonusTotalArray[0].getBonus()+ brokerageBonusTotalArray[1].getBonus()+ brokerageBonusTotalArray[2].getBonus()+ brokerageBonusTotalArray[3].getBonus()
+ brokerageBonusTotalArray[4].getBonus() + brokerageBonusTotalArray[5].getBonus();
return totalBrokerageBonus;
}
public static void main(String[]args)
{
//Part-B
///(a) create broker1 with the no argument constructor
Broker broker1=new Broker();
broker1.setDepartmentName("Dublin");
broker1.setFirstName("John");
broker1.setLastName("Wall");
broker1.setQuarter1(12);
broker1.setQuarter2(24);
broker1.setQuarter3(26);
broker1.setQuarter4(17);
System.out.print(broker1);
//(b) create broker2
Broker broker2 = new Broker("London","Sarah","May");
broker2.setQuarter1(8);
broker2.setQuarter2(11);
broker2.setQuarter3(7);
broker2.setQuarter4(9);
System.out.print(broker2);
//(c) create broker3
Broker broker3 = new Broker("London","Ruth","Lavin");
//call read in quarters method
broker3.readInQuarters();
System.out.print(broker3);
//(d) create broker4,broker5,broker6
Broker broker4=new Broker("Dublin","Conor","Smith",21,23,26,31);
Broker broker5=new Broker("Paris","Jerome","Duignan",14,14,17,18);
Broker broker6=new Broker("Paris","Patick","Bateman",23,24,26,35);
//(e) Create broker array
Broker[] brokers;
brokers=new Broker [6];
brokers[0]=broker1;brokers[1]=broker2;brokers[2]=broker3;brokers[3]=broker4;brokers[4]=broker5;brokers[5]=broker6;
//(f) Output second table
String[] headings ={"Dept","Firstname","Surname","Q1","Q2","Q3","Q4","Total","Bonus"};
//loop to print the headings
for (int i = 0; i < headings.length; i++)
{
System.out.print(headings[i]+" ");
}
//print a space under the headings
System.out.println(" \n");
//loop to print the main table plus format specifiers to align the text
for (int i = 0; i < 5; i++)
{
System.out.printf("%-7s %-13s %-11s %-6s %-6s %-6s %-6s %-10s %.1f \n\n",brokers[i].getDepartment(), brokers[i].getFirstName(),brokers[i].getLastName(),brokers[i].getQuarter1(),brokers[i].getQuarter2(),brokers[i].getQuarter3(),brokers[i].getQuarter4(),brokers[i].getBrokerTotal(),brokers[i].getBonus());
}
// console printout for quarterly totals
System.out.printf("%33s \n","Quarterly ");
System.out.printf("%29 %9s %6s %6s %6s %6s \n","Total ",getQuarter1Total(brokers),getQuarter2Total(brokers),getQuarter3Total(brokers),getQuarter4Total(brokers),getBrokerageBonus(brokers));
} //end of method main
} //end of class broker
er
You aren't using your setters. The problem is here
public void readInQuarters () {
Scanner input = new Scanner(System.in);
System.out.println("Please enter Q1,Q2,Q3 and Q4 figures for broker:");
quarter1 = input.nextInt(); // <-- Use your setters!
quarter2 = input.nextInt();
quarter3 = input.nextInt();
quarter4 = input.nextInt();
// should be,
setQuarter1(input.nextInt()); // and so on... although I will point out, you should
// be reading double(s) apparently.
}
Hello Friend I have give a suggestion which is am also use in our project
call this method before submitting the value. And if return true then update data other wise show mgs in validate method of where from call update
boolean validate() {
int c = Integer.parseInt(txtFieldSetupTopElevation.getText().toString().trim());
if (c <= 0) {
// Here use code for show msg error or information
// return true if value is greater than 0 other wise return else
return false;
}
}
Sandeep

Why do I keep getting a NoSuchElementException?

This is the code I currently have. For some reason, I keep getting and error called: NoSuchElementException: No line found. The exception occurs at the line:
"String number = scanPhone.nextLine();" and in the Provider class and at the line:"provObj.readCellPhoneFile(fileNameIn);"in the CellPhonesPart2 class. Does anyone know what's wrong with it?
import java.util.Scanner;
import java.io.File;
import java.util.Arrays;
import java.io.IOException;
public class Provider {
private String name;
private CellPhone[] phones;
private String[] excludedRecords;
/**
* Constructor for Provider class.
*/
public Provider() {
name = "not yet assigned";
phones = new CellPhone[0];
excludedRecords = new String[0];
}
/**
* Reads in file name and assigns data.
*
* #param fileNameIn Input for file name from main
* #throws IOException from scanning file name
*/
public void readCellPhoneFile(String fileNameIn) throws IOException {
//Reads in file name and creates Scanner object
File fileIn = new File(fileNameIn);
Scanner scanFile = new Scanner(fileIn);
//Assigns name from first line
name = scanFile.nextLine();
//Assigns data from file to different categories
while (scanFile.hasNext()) {
Scanner scanPhone = new Scanner(scanFile.nextLine());
scanPhone.useDelimiter(", *");
String phoneType = scanPhone.nextLine();
char phoneChar = phoneType.toUpperCase().charAt(0);
//Assigns phone to different category
switch (phoneChar) {
case 'F':
String number = scanPhone.nextLine();
int texts = Integer.parseInt(scanPhone.nextLine());
int minutes = Integer.parseInt(scanPhone.nextLine());
FlipPhone flip1 = new FlipPhone(number, texts, minutes);
addPhone(flip1);
break;
case 'S':
number = scanPhone.nextLine();
texts = Integer.parseInt(scanPhone.nextLine());
minutes = Integer.parseInt(scanPhone.nextLine());
int data = Integer.parseInt(scanPhone.nextLine());
SmartPhone smart1 = new SmartPhone(number, texts, minutes, data);
addPhone(smart1);
break;
case 'I':
number = scanPhone.nextLine();
texts = Integer.parseInt(scanPhone.nextLine());
minutes = Integer.parseInt(scanPhone.nextLine());
data = Integer.parseInt(scanPhone.nextLine());
int iMessages = Integer.parseInt(scanPhone.nextLine());
IPhone iPhone1 = new IPhone(number, texts,
minutes, data, iMessages);
addPhone(iPhone1);
break;
case 'A':
number = scanPhone.nextLine();
texts = Integer.parseInt(scanPhone.nextLine());
minutes = Integer.parseInt(scanPhone.nextLine());
data = Integer.parseInt(scanPhone.nextLine());
int hotspotMin = Integer.parseInt(scanPhone.nextLine());
Android android1 = new Android(number, texts,
minutes, data, hotspotMin);
addPhone(android1);
break;
default:
String unrecognized = scanPhone.nextLine();
addExcludedRecord(unrecognized);
}
}
}
/**
* Returns string for provider name.
*
* #return String
*/
public String getName() {
return name;
}
/**
* Assigns a name input as provider name.
*
* #param nameIn Input for provider name
*/
public void setName(String nameIn) {
name = nameIn;
}
/**
* Returns CellPhone array for phones.
*
* #return CellPhone[]
*/
public CellPhone[] getPhones() {
return phones;
}
/**
* Returns string array for excluded records.
*
* #return String[]
*/
public String[] getExcludedRecords() {
return excludedRecords;
}
/**
* Adds phone to array of phones.
*
* #param newPhoneIn Input for phone object
*/
public void addPhone(CellPhone newPhoneIn) {
//Increases size of phones array
CellPhone[] newPhones = new CellPhone[phones.length + 1];
for (int i = 0; i < phones.length; i++) {
newPhones[i] = phones[i];
}
phones = newPhones;
//Adds CellPhone object to phones array
phones[phones.length] = newPhoneIn;
}
/**
* Determines if phone number is found and deleted.
*
* #return boolean
* #param numberIn Input for phone number
*/
public boolean deletePhone(String numberIn) {
boolean delete = false;
int deleteIndex = -1;
//Searches for phone number match
for (int i = 0; i < phones.length; i++) {
if (numberIn == phones[i].getNumber()) {
deleteIndex = i;
//Decreases size of phones array
CellPhone[] newPhones = new CellPhone[phones.length - 1];
for (i = 0; i < phones.length; i++) {
newPhones[i] = phones[i];
}
phones = newPhones;
}
}
if (deleteIndex > -1) {
for (int i = deleteIndex; i < phones.length - 1; i++) {
phones[i] = phones[i + 1];
}
return true;
}
else {
return false;
}
}
/**
* Adds unrecognized phone to excluded records.
*
* #param excRecIn Input for unrecognized phone
*/
public void addExcludedRecord(String excRecIn) {
//Increases capacity of excludedRecords
String[] newExcRecords = new String[excludedRecords.length + 1];
for (int i = 0; i < excludedRecords.length; i++) {
newExcRecords[i] = excludedRecords[i];
}
excludedRecords = newExcRecords;
//Adds excRecIn to array
excludedRecords[excludedRecords.length] = excRecIn;
}
/**
* Returns list of cell phones in phones array.
*
* #return String
*/
public String toString() {
String result = "";
for (CellPhone phone : phones) {
result += phone;
}
return result;
}
/**
* Calculates total bill for all phones.
*
* #return double
*/
public double calculateTotalBill() {
double totalBill = 0;
for (int i = 0; i < phones.length; i++) {
totalBill += phones[i].calculateBill();
}
return totalBill;
}
/**
* Calculates total number of texts for all phones.
*
* #return int
*/
public int calculateTotalTexts() {
int totalTexts = 0;
for (int i = 0; i < phones.length; i++) {
totalTexts += phones[i].getTexts();
}
return totalTexts;
}
/**
* Calculates total number of minutes for all phones.
*
* #return int
*/
public int calculateTotalMinutes() {
int totalMinutes = 0;
for (int i = 0; i < phones.length; i++) {
totalMinutes += phones[i].getMinutes();
}
return totalMinutes;
}
/**
* Calculates total data for smartphones.
*
* #return int
*/
public int calculateTotalData() {
int totalData = 0;
for (int i = 0; i < phones.length; i++) {
if (phones[i] instanceof SmartPhone) {
totalData += ((SmartPhone) phones[i]).getData();
}
}
return totalData;
}
/**
* Calculates total hotspot minutes for Androids.
*
* #return int
*/
public int calculateTotalHotspotMin() {
int totalHotspotMin = 0;
for (int i = 0; i < phones.length; i++) {
if (phones[i] instanceof Android) {
totalHotspotMin += ((Android) phones[i]).getHotspotMin();
}
}
return totalHotspotMin;
}
/**
* Calculates total iMessage count for iPhones.
*
* #return int
*/
public int calculateTotalIMessages() {
int totalIMessages = 0;
for (int i = 0; i < phones.length; i++) {
if (phones[i] instanceof IPhone) {
totalIMessages += ((IPhone) phones[i]).getIMessages();
}
}
return totalIMessages;
}
/**
* Returns string for summary report.
*
* #return String
*/
public String summary() {
String summary = "------------------------------"
+ "\nSummary for " + getName()
+ "\n------------------------------"
+ "\nNumber of cell phones: " + getPhones()
+ "Texts: " + calculateTotalTexts()
+ "Talk Minutes: " + calculateTotalMinutes()
+ "Data: " + calculateTotalData()
+ "Hotspot Minutes: " + calculateTotalHotspotMin()
+ "iMessages: " + calculateTotalIMessages()
+ "Bill Total: $" + calculateTotalBill()
+ "\n\n------------------------------"
+ "\nRates for " + getName()
+ "\n------------------------------"
+ rates()
+ "\n------------------------------"
+ "\nCell Phones by Number"
+ "\n------------------------------\n"
+ listByNumber()
+ "\n------------------------------"
+ "\nCell Phones by Billing Amount"
+ "\n------------------------------\n"
+ listByBill()
+ "\n------------------------------"
+ "\nExcluded Records"
+ "\n------------------------------\n"
+ excludedRecordsList();
return summary;
}
/**
* Returns string for different rates.
*
* #return String
*/
public String rates() {
String rates = "FlipPhone Talk Rate: $" + FlipPhone.TALK_RATE
+ "\tText Rate: $" + FlipPhone.TEXT_RATE
+ "SmartPhone Talk Rate: $" + SmartPhone.TALK_RATE
+ "\tText Rate: $" + SmartPhone.TEXT_RATE
+ "\tMax Talk Time: " + SmartPhone.MAX_TALK_TIME
+ "\n\tiPhone iMessage Rate: $" + IPhone.IMESSAGE_RATE
+ "\n\tAndroid HotspotRate: $" + Android.HOTSPOT_RATE;
return rates;
}
/**
* Returns string of phones sorted by number.
*
* #return String
*/
public String listByNumber() {
String listByNumber = "";
for (CellPhone phone : phones) {
listByNumber += phone.toString();
}
Arrays.sort(phones);
return listByNumber;
}
/**
* Returns string of phones sorted by bill.
*
* #return String
*/
public String listByBill() {
String listByBill = "";
for (CellPhone phone : phones) {
listByBill += phone.toString();
}
Arrays.sort(phones, new CellPhoneBillComparator());
return listByBill;
}
/**
* Returns string excluded records.
*
* #return String
*/
public String excludedRecordsList() {
String excRecList = "";
for (String phone : excludedRecords) {
excRecList += phone;
}
return excRecList;
}
}
It reads in the file from this class:
public class CellPhonesPart2 {
/**
* Creates objects from different classes and prints objects.
*
* #param args Reads in file
* #throws IOException from scanning input file
*/
public static void main(String[] args) throws IOException {
String fileNameIn = args[0];
Provider provObj = new Provider();
provObj.readCellPhoneFile(fileNameIn);
System.out.println(provObj.summary());
}
}
Scanner scanPhone = new Scanner(scanFile.nextLine());
// this is causing your error. scanPhone is ultimately just a one line String
// this line will be found
String phoneType = scanPhone.nextLine();
// this line won't because scanPhone is only one line
String number = scanPhone.nextLine();
Edit: possible Solution
while (scanFile.hasNextLine()) {
Scanner scanPhone = new Scanner(scanFile.nextLine());
scanPhone.useDelimiter(", *");
String phoneType = scanPhone.next();
char phoneChar = phoneType.toUpperCase().charAt(0);
//Assigns phone to different category
switch (phoneChar) {
case 'F':
String number = scanPhone.next();
int texts = Integer.parseInt(scanePhone.next());
int minutes = Integer.parseInt(scanPhone.next());
FlipPhone flip1 = new FlipPhone(number, texts, minutes);
addPhone(flip1);
break;
Changed all the scanPhone.nextLine()'s to scanPhone.next()
Also, try using while (scanFile.hasNextLine()); instead of hasNext()
you should use an appropriate hasNext() before calling nextLine();
Scanner may be empty.!

Categories

Resources