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.!
Related
I used jflex to generate a Java class and now I want to use it to get lexical analysis of a .txt file. The Java Class begins like this:
/* The following code was generated by JFlex 1.6.1 */
/**
* This class is a scanner generated by
* JFlex 1.6.1
* from the specification file <tt>patch.flex</tt>
*/
public class Patch {
/** This character denotes the end of file */
public static final int YYEOF = -1;
/** initial size of the lookahead buffer */
private static final int ZZ_BUFFERSIZE = 16384;
/** lexical states */
public static final int YYINITIAL = 0;
/**
* ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l
* ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l
* at the beginning of a line
* l is of the form l = 2*k, k a non negative integer
*/
private static final int ZZ_LEXSTATE[] = {
0, 0
};
/**
* Translates characters to character classes
*/
private static final String ZZ_CMAP_PACKED =
"\141\0\1\1\1\2\1\3\1\4\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffab\0";
/**
* Translates characters to character classes
*/
private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED);
/**
* Translates DFA states to action switch labels.
*/
private static final int [] ZZ_ACTION = zzUnpackAction();
private static final String ZZ_ACTION_PACKED_0 =
"\1\0\2\1\3\0\1\2\2\0\2\2";
private static int [] zzUnpackAction() {
int [] result = new int[11];
int offset = 0;
offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result);
return result;
}
private static int zzUnpackAction(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int count = packed.charAt(i++);
int value = packed.charAt(i++);
do result[j++] = value; while (--count > 0);
}
return j;
}
/**
* Translates a state to a row index in the transition table
*/
private static final int [] ZZ_ROWMAP = zzUnpackRowMap();
private static final String ZZ_ROWMAP_PACKED_0 =
"\0\0\0\5\0\12\0\12\0\17\0\24\0\31\0\36"+
"\0\31\0\5\0\36";
private static int [] zzUnpackRowMap() {
int [] result = new int[11];
int offset = 0;
offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result);
return result;
}
private static int zzUnpackRowMap(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int high = packed.charAt(i++) << 16;
result[j++] = high | packed.charAt(i++);
}
return j;
}
/**
* The transition table of the DFA
*/
private static final int [] ZZ_TRANS = zzUnpackTrans();
private static final String ZZ_TRANS_PACKED_0 =
"\1\2\1\3\3\2\6\0\1\4\1\5\1\6\3\0"+
"\1\5\1\7\2\0\1\10\1\0\1\6\4\0\1\11"+
"\1\12\1\0\1\13\3\0";
private static int [] zzUnpackTrans() {
int [] result = new int[35];
int offset = 0;
offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result);
return result;
}
private static int zzUnpackTrans(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int count = packed.charAt(i++);
int value = packed.charAt(i++);
value--;
do result[j++] = value; while (--count > 0);
}
return j;
}
/* error codes */
private static final int ZZ_UNKNOWN_ERROR = 0;
private static final int ZZ_NO_MATCH = 1;
private static final int ZZ_PUSHBACK_2BIG = 2;
/* error messages for the codes above */
private static final String ZZ_ERROR_MSG[] = {
"Unknown internal scanner error",
"Error: could not match input",
"Error: pushback value was too large"
};
/**
* ZZ_ATTRIBUTE[aState] contains the attributes of state <code>aState</code>
*/
private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute();
private static final String ZZ_ATTRIBUTE_PACKED_0 =
"\1\0\1\11\1\1\3\0\1\1\2\0\1\11\1\1";
private static int [] zzUnpackAttribute() {
int [] result = new int[11];
int offset = 0;
offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result);
return result;
}
private static int zzUnpackAttribute(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int count = packed.charAt(i++);
int value = packed.charAt(i++);
do result[j++] = value; while (--count > 0);
}
return j;
}
/** the input device */
private java.io.Reader zzReader;
/** the current state of the DFA */
private int zzState;
/** the current lexical state */
private int zzLexicalState = YYINITIAL;
/** this buffer contains the current text to be matched and is
the source of the yytext() string */
private char zzBuffer[] = new char[ZZ_BUFFERSIZE];
/** the textposition at the last accepting state */
private int zzMarkedPos;
/** the current text position in the buffer */
private int zzCurrentPos;
/** startRead marks the beginning of the yytext() string in the buffer */
private int zzStartRead;
/** endRead marks the last character in the buffer, that has been read
from input */
private int zzEndRead;
/** number of newlines encountered up to the start of the matched text */
private int yyline;
/** the number of characters up to the start of the matched text */
private int yychar;
/**
* the number of characters from the last newline up to the start of the
* matched text
*/
private int yycolumn;
/**
* zzAtBOL == true <=> the scanner is currently at the beginning of a line
*/
private boolean zzAtBOL = true;
/** zzAtEOF == true <=> the scanner is at the EOF */
private boolean zzAtEOF;
/** denotes if the user-EOF-code has already been executed */
private boolean zzEOFDone;
/**
* The number of occupied positions in zzBuffer beyond zzEndRead.
* When a lead/high surrogate has been read from the input stream
* into the final zzBuffer position, this will have a value of 1;
* otherwise, it will have a value of 0.
*/
private int zzFinalHighSurrogate = 0;
/**
* Creates a new scanner
*
* #param in the java.io.Reader to read input from.
*/
public Patch(java.io.Reader in) {
this.zzReader = in;
}
/**
* Unpacks the compressed character translation table.
*
* #param packed the packed character translation table
* #return the unpacked character translation table
*/
private static char [] zzUnpackCMap(String packed) {
char [] map = new char[0x110000];
int i = 0; /* index in packed string */
int j = 0; /* index in unpacked array */
while (i < 44) {
int count = packed.charAt(i++);
char value = packed.charAt(i++);
do map[j++] = value; while (--count > 0);
}
return map;
}
/**
* Refills the input buffer.
*
* #return <code>false</code>, iff there was new input.
*
* #exception java.io.IOException if any I/O-Error occurs
*/
private boolean zzRefill() throws java.io.IOException {
/* first: make room (if you can) */
if (zzStartRead > 0) {
zzEndRead += zzFinalHighSurrogate;
zzFinalHighSurrogate = 0;
System.arraycopy(zzBuffer, zzStartRead,
zzBuffer, 0,
zzEndRead-zzStartRead);
/* translate stored positions */
zzEndRead-= zzStartRead;
zzCurrentPos-= zzStartRead;
zzMarkedPos-= zzStartRead;
zzStartRead = 0;
}
/* is the buffer big enough? */
if (zzCurrentPos >= zzBuffer.length - zzFinalHighSurrogate) {
/* if not: blow it up */
char newBuffer[] = new char[zzBuffer.length*2];
System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length);
zzBuffer = newBuffer;
zzEndRead += zzFinalHighSurrogate;
zzFinalHighSurrogate = 0;
}
/* fill the buffer with new input */
int requested = zzBuffer.length - zzEndRead;
int numRead = zzReader.read(zzBuffer, zzEndRead, requested);
/* not supposed to occur according to specification of java.io.Reader */
if (numRead == 0) {
throw new java.io.IOException("Reader returned 0 characters. See JFlex examples for workaround.");
}
if (numRead > 0) {
zzEndRead += numRead;
/* If numRead == requested, we might have requested to few chars to
encode a full Unicode character. We assume that a Reader would
otherwise never return half characters. */
if (numRead == requested) {
if (Character.isHighSurrogate(zzBuffer[zzEndRead - 1])) {
--zzEndRead;
zzFinalHighSurrogate = 1;
}
}
/* potentially more input available */
return false;
}
/* numRead < 0 ==> end of stream */
return true;
}
/**
* Closes the input stream.
*/
public final void yyclose() throws java.io.IOException {
zzAtEOF = true; /* indicate end of file */
zzEndRead = zzStartRead; /* invalidate buffer */
if (zzReader != null)
zzReader.close();
}
/**
* Resets the scanner to read from a new input stream.
* Does not close the old reader.
*
* All internal variables are reset, the old input stream
* <b>cannot</b> be reused (internal buffer is discarded and lost).
* Lexical state is set to <tt>ZZ_INITIAL</tt>.
*
* Internal scan buffer is resized down to its initial length, if it has grown.
*
* #param reader the new input stream
*/
public final void yyreset(java.io.Reader reader) {
zzReader = reader;
zzAtBOL = true;
zzAtEOF = false;
zzEOFDone = false;
zzEndRead = zzStartRead = 0;
zzCurrentPos = zzMarkedPos = 0;
zzFinalHighSurrogate = 0;
yyline = yychar = yycolumn = 0;
zzLexicalState = YYINITIAL;
if (zzBuffer.length > ZZ_BUFFERSIZE)
zzBuffer = new char[ZZ_BUFFERSIZE];
}
/**
* Returns the current lexical state.
*/
public final int yystate() {
return zzLexicalState;
}
/**
* Enters a new lexical state
*
* #param newState the new lexical state
*/
public final void yybegin(int newState) {
zzLexicalState = newState;
}
/**
* Returns the text matched by the current regular expression.
*/
public final String yytext() {
return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead );
}
/**
* Returns the character at position <tt>pos</tt> from the
* matched text.
*
* It is equivalent to yytext().charAt(pos), but faster
*
* #param pos the position of the character to fetch.
* A value from 0 to yylength()-1.
*
* #return the character at position pos
*/
public final char yycharat(int pos) {
return zzBuffer[zzStartRead+pos];
}
/**
* Returns the length of the matched text region.
*/
public final int yylength() {
return zzMarkedPos-zzStartRead;
}
/**
* Reports an error that occured while scanning.
*
* In a wellformed scanner (no or only correct usage of
* yypushback(int) and a match-all fallback rule) this method
* will only be called with things that "Can't Possibly Happen".
* If this method is called, something is seriously wrong
* (e.g. a JFlex bug producing a faulty scanner etc.).
*
* Usual syntax/scanner level error handling should be done
* in error fallback rules.
*
* #param errorCode the code of the errormessage to display
*/
private void zzScanError(int errorCode) {
String message;
try {
message = ZZ_ERROR_MSG[errorCode];
}
catch (ArrayIndexOutOfBoundsException e) {
message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
}
throw new Error(message);
}
/**
* Pushes the specified amount of characters back into the input stream.
*
* They will be read again by then next call of the scanning method
*
* #param number the number of characters to be read again.
* This number must not be greater than yylength()!
*/
public void yypushback(int number) {
if ( number > yylength() )
zzScanError(ZZ_PUSHBACK_2BIG);
zzMarkedPos -= number;
}
/**
* Resumes scanning until the next regular expression is matched,
* the end of input is encountered or an I/O-Error occurs.
*
* #return the next token
* #exception java.io.IOException if any I/O-Error occurs
*/
public int yylex() throws java.io.IOException {
int zzInput;
int zzAction;
// cached fields:
int zzCurrentPosL;
int zzMarkedPosL;
int zzEndReadL = zzEndRead;
char [] zzBufferL = zzBuffer;
char [] zzCMapL = ZZ_CMAP;
int [] zzTransL = ZZ_TRANS;
int [] zzRowMapL = ZZ_ROWMAP;
int [] zzAttrL = ZZ_ATTRIBUTE;
while (true) {
zzMarkedPosL = zzMarkedPos;
boolean zzR = false;
int zzCh;
int zzCharCount;
for (zzCurrentPosL = zzStartRead ;
zzCurrentPosL < zzMarkedPosL ;
zzCurrentPosL += zzCharCount ) {
zzCh = Character.codePointAt(zzBufferL, zzCurrentPosL, zzMarkedPosL);
zzCharCount = Character.charCount(zzCh);
switch (zzCh) {
case '\u000B':
case '\u000C':
case '\u0085':
case '\u2028':
case '\u2029':
yyline++;
yycolumn = 0;
zzR = false;
break;
case '\r':
yyline++;
yycolumn = 0;
zzR = true;
break;
case '\n':
if (zzR)
zzR = false;
else {
yyline++;
yycolumn = 0;
}
break;
default:
zzR = false;
yycolumn += zzCharCount;
}
}
if (zzR) {
// peek one character ahead if it is \n (if we have counted one line too much)
boolean zzPeek;
if (zzMarkedPosL < zzEndReadL)
zzPeek = zzBufferL[zzMarkedPosL] == '\n';
else if (zzAtEOF)
zzPeek = false;
else {
boolean eof = zzRefill();
zzEndReadL = zzEndRead;
zzMarkedPosL = zzMarkedPos;
zzBufferL = zzBuffer;
if (eof)
zzPeek = false;
else
zzPeek = zzBufferL[zzMarkedPosL] == '\n';
}
if (zzPeek) yyline--;
}
zzAction = -1;
zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL;
zzState = ZZ_LEXSTATE[zzLexicalState];
// set up zzAction for empty match case:
int zzAttributes = zzAttrL[zzState];
if ( (zzAttributes & 1) == 1 ) {
zzAction = zzState;
}
zzForAction: {
while (true) {
if (zzCurrentPosL < zzEndReadL) {
zzInput = Character.codePointAt(zzBufferL, zzCurrentPosL, zzEndReadL);
zzCurrentPosL += Character.charCount(zzInput);
}
else if (zzAtEOF) {
zzInput = YYEOF;
break zzForAction;
}
else {
// store back cached positions
zzCurrentPos = zzCurrentPosL;
zzMarkedPos = zzMarkedPosL;
boolean eof = zzRefill();
// get translated positions and possibly new buffer
zzCurrentPosL = zzCurrentPos;
zzMarkedPosL = zzMarkedPos;
zzBufferL = zzBuffer;
zzEndReadL = zzEndRead;
if (eof) {
zzInput = YYEOF;
break zzForAction;
}
else {
zzInput = Character.codePointAt(zzBufferL, zzCurrentPosL, zzEndReadL);
zzCurrentPosL += Character.charCount(zzInput);
}
}
int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ];
if (zzNext == -1) break zzForAction;
zzState = zzNext;
zzAttributes = zzAttrL[zzState];
if ( (zzAttributes & 1) == 1 ) {
zzAction = zzState;
zzMarkedPosL = zzCurrentPosL;
if ( (zzAttributes & 8) == 8 ) break zzForAction;
}
}
}
// store back cached position
zzMarkedPos = zzMarkedPosL;
if (zzInput == YYEOF && zzStartRead == zzCurrentPos) {
zzAtEOF = true;
return YYEOF;
}
else {
switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) {
case 1:
{ System.out.print(yytext());
}
case 3: break;
case 2:
{ System.out.println("***found match");
}
case 4: break;
default:
zzScanError(ZZ_NO_MATCH);
}
}
}
}
/**
* Runs the scanner on input files.
*
* This is a standalone scanner, it will print any unmatched
* text to System.out unchanged.
*
* #param argv the command line, contains the filenames to run
* the scanner on.
*/
public static void main(String argv[]) {
if (argv.length == 0) {
System.out.println("Usage : java Patch [ --encoding <name> ] <inputfile(s)>");
}
else {
int firstFilePos = 0;
String encodingName = "UTF-8";
if (argv[0].equals("--encoding")) {
firstFilePos = 2;
encodingName = argv[1];
try {
java.nio.charset.Charset.forName(encodingName); // Side-effect: is encodingName valid?
} catch (Exception e) {
System.out.println("Invalid encoding '" + encodingName + "'");
return;
}
}
for (int i = firstFilePos; i < argv.length; i++) {
Patch scanner = null;
try {
java.io.FileInputStream stream = new java.io.FileInputStream(argv[i]);
java.io.Reader reader = new java.io.InputStreamReader(stream, encodingName);
scanner = new Patch(reader);
while ( !scanner.zzAtEOF ) scanner.yylex();
}
catch (java.io.FileNotFoundException e) {
System.out.println("File not found : \""+argv[i]+"\"");
}
catch (java.io.IOException e) {
System.out.println("IO error scanning file \""+argv[i]+"\"");
System.out.println(e);
}
catch (Exception e) {
System.out.println("Unexpected exception:");
e.printStackTrace();
}
}
}
}
}
The shell keep giving me the error
Error: Could not find or load main class Patch
when I use the command like:
java Patch SearchText.txt
Besides, there's no error when I run:
javac Patch.java
I tried to set the path explicitly:
java -cp. Patch SearchText.txt
and got something like this:
{\rtf1\ansi\ansicpg1252\cocoartf1348\cocoasubrtf170
{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
{\colortbl;\red255\green255\blue255;}
\margl1440\margr1440\vieww10800\viewh8400\viewkind0
\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural
\f0\fs24 \cf0 a+b+c+d}AmbertekiMacBook-Air:ADS4 amber95$ java Patch SearchText.txt
Error: Could not find or load main class Patch
Have you tried this?
java -cp ./ Patch file.txt
I'm writing a program for a class that uses data from a file (students' grades) and then averages and organizes it based on highest grade to lowest. I'm almost done except for an error at line 46, where it won't call the method:
findMaxIndex(courseGrade);
Any help would be greatly appreciated!
package project3;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
*
* #author badluckbowers
*/
public class Project3 {
final static int NUM_STUDENTS = 16;
public static String[] nameArray = new String[NUM_STUDENTS];
public static double[] labAvg = new double[NUM_STUDENTS];
public static double[] quizAvg = new double[NUM_STUDENTS];
public static double[] projectAvg = new double[NUM_STUDENTS];
public static double[] examAvg = new double[NUM_STUDENTS];
public static double[] finalExamArray = new double[NUM_STUDENTS];
public static double[] courseGrade = new double[NUM_STUDENTS];
public static char[] gradeArray = new char[NUM_STUDENTS];
/**
* #param args the command line arguments
*/
final static int numLabScores = 15;
final static int pointsLabPossible = 10;
final static int numQuizScores = 12;
final static int pointsQuizPossible = 5;
final static int numProjectScores = 6;
final static int pointsProjectPossible = 25;
final static int numExamScores = 2;
final static int pointsExamPossible = 100;
final static int numFinalExamScores = 1;
final static int pointsFinalExamPossible = 100;
public static void main(String[] args) throws FileNotFoundException {
readFile("scores.txt", nameArray, labAvg, quizAvg, projectAvg, examAvg, finalExamArray);
findMaxIndex(courseGrade);
printArray();
}
public static void readFile(String fileName, String[] nameArray, double[] labAvg, double[] quizAvg, double[] projectAvg, double[] examAvg, double[] finalExamArray) throws FileNotFoundException {
File input = new File(fileName);
if (!input.exists()) {
System.out.println("Error opening scores.txt for input; "
+ "aborting program run.");
System.exit(0);
}
Scanner inputFile = new Scanner(input);
for (int i = 0; i < NUM_STUDENTS; i++) {
nameArray[i] = inputFile.nextLine();
labAvg[i] = calculatePercent(inputFile, numLabScores, pointsLabPossible); //15-1
quizAvg[i] = calculatePercent(inputFile, numQuizScores, pointsQuizPossible); //12-1
projectAvg[i] = calculatePercent(inputFile, numProjectScores, pointsProjectPossible); //6-1
examAvg[i] = calculatePercent(inputFile, numExamScores, pointsExamPossible); //2-1
finalExamArray[i] = calculatePercent(inputFile, numFinalExamScores, pointsFinalExamPossible); //1-1
courseGrade[i] = calculateGrade(labAvg[i], quizAvg[i], projectAvg[i], examAvg[i], finalExamArray[i]);
gradeArray[i] = calculateLetter(courseGrade[i]);
inputFile.nextLine();
}
inputFile.close();
}
public static double calculatePercent(Scanner inFile, int numScores, int pointsPossible) {
double score;
double total = 0;
for (int i = 0; i < numScores; i++) {
score = inFile.nextDouble();
total += score;
}
return (total / (numScores * pointsPossible)) * 100;
}
public static double calculateGrade(double labAvg, double quizAvg, double projectAvg, double examAvg, double finalExamArray) {
return ((labAvg * .15 + quizAvg * .10 + projectAvg * .25 + examAvg * .30 + finalExamArray * .20));
}
public static char calculateLetter(double courseGrade) {
if (courseGrade < 60.0) {
return 'F';
} else if (courseGrade >= 60.0 && courseGrade < 70.0) {
return 'D';
} else if (courseGrade >= 70.0 && courseGrade < 80.0) {
return 'C';
} else if (courseGrade >= 80.0 && courseGrade < 90) {
return 'B';
}
return 'A';
}
//__________________________________________________________________________
// sort stuff
/**
* finds index of smallest element in the part of the array bounded by start
* and array.length-1
*
* #param courseGrade is fully populated
* #param start is index to begin searching for smallest element
* #return index of smallest item between start and array.length-1
* #throws java.io.FileNotFoundException
*/
public static double findMaxIndex(double[] courseGrade, int start) throws FileNotFoundException {
int maxIndex;
maxIndex = start;
for (int index = start + 1; index < courseGrade.length; index++) {
if (courseGrade[index] > courseGrade[maxIndex]) {
maxIndex = index;
}
}
return maxIndex;
}
/**
* the items in the array will be sorted largest to smallest
*
* #param courseGrade
* #throws java.io.FileNotFoundException
*/
public static void sortArray(double[] courseGrade) throws FileNotFoundException {
int maxIndex;
double maxItem;
for (int i = 0; i > courseGrade.length - 1; i++) {
maxIndex = (int) findMaxIndex(courseGrade, i);
//put the smaller item in place of the current item
maxItem = courseGrade[maxIndex];
courseGrade[maxIndex] = courseGrade[i];
courseGrade[i] = maxItem;
System.out.println("Array after pass " + (i + 1) + " of selection sort:");
for (int j = 0; j < courseGrade.length; j++) {
System.out.print(courseGrade[j] + " ");
}
System.out.println("");
}
}
//__________________________________________________________________________
public static void printArray() {
System.out.println("The array elements are: ");
for (int i = 0; i < nameArray.length; i++) {
System.out.println(nameArray[i] + " " + labAvg[i] + " " + quizAvg[i] + " " + projectAvg[i] + " " + examAvg[i] + " " + finalExamArray[i] + " " + courseGrade[i] + " " + gradeArray[i]);
}
System.out.println();
}
}
You need to pass second argument when calling the function findMaxIndex. Because your function definition has two parameters.
findMaxIndex(courseGrade, startIndex);
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;
}
}
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;
guys. Right now, I have an array of objects that I've assigned from reading in a text file, and I need a method that searches for a string that matches with the object and, if found, decreases the capacity of the array and deletes that element. The method is the deletePhone() method in the Provider class, but I can't seem to figure out what I'm doing wrong. This first class is only used to read in the 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());
System.out.println(provObj.rates());
System.out.println(provObj.listByNumber());
System.out.println(provObj.listByBill());
System.out.println(provObj.excludedRecordsList());
}
}
This is the main class that I'm having problems with. It's only the deletePhone() method that I can't seem to figure out.
import java.util.Scanner;
import java.io.File;
import java.util.Arrays;
import java.io.IOException;
import java.text.DecimalFormat;
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.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(scanPhone.next());
int minutes = Integer.parseInt(scanPhone.next());
FlipPhone flip1 = new FlipPhone(number, texts, minutes);
addPhone(flip1);
break;
case 'S':
number = scanPhone.next();
texts = Integer.parseInt(scanPhone.next());
minutes = Integer.parseInt(scanPhone.next());
int data = Integer.parseInt(scanPhone.next());
SmartPhone smart1 = new SmartPhone(number, texts, minutes, data);
addPhone(smart1);
break;
case 'I':
number = scanPhone.next();
texts = Integer.parseInt(scanPhone.next());
minutes = Integer.parseInt(scanPhone.next());
data = Integer.parseInt(scanPhone.next());
int iMessages = Integer.parseInt(scanPhone.next());
IPhone iPhone1 = new IPhone(number, texts,
minutes, data, iMessages);
addPhone(iPhone1);
break;
case 'A':
number = scanPhone.next();
texts = Integer.parseInt(scanPhone.next());
minutes = Integer.parseInt(scanPhone.next());
data = Integer.parseInt(scanPhone.next());
int hotspotMin = Integer.parseInt(scanPhone.next());
Android android1 = new Android(number, texts,
minutes, data, hotspotMin);
addPhone(android1);
break;
default:
String unrecognized = scanPhone.nextLine();
unrecognized = phoneType + unrecognized;
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 - 1] = 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.equals(phones[i].getNumber())) {
deleteIndex = i;
}
}
if (deleteIndex > -1) {
for (int i = deleteIndex; i < phones.length - 1; i++) {
phones[i] = phones[i + 1];
phones[phones.length - 1] = null;
CellPhone[] newPhones = new CellPhone[phones.length - 1];
phones = newPhones;
}
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 - 1] = excRecIn;
}
/**
* Returns list of cell phones in phones array.
*
* #return String
*/
public String toString() {
String result = "";
for (CellPhone phone : phones) {
result += phone + "\n";
}
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() {
DecimalFormat dfmt = new DecimalFormat("$#,000.00");
String summary = "------------------------------"
+ "\nSummary for " + getName()
+ "\n------------------------------"
+ "\nNumber of cell phones: " + phones.length
+ "\nTexts: " + calculateTotalTexts()
+ "\nTalk Minutes: " + calculateTotalMinutes()
+ "\nData: " + calculateTotalData()
+ "\nHotspot Minutes: " + calculateTotalHotspotMin()
+ "\niMessages: " + calculateTotalIMessages()
+ "\nBill Total: " + dfmt.format(calculateTotalBill());
return summary;
}
/**
* Returns string for different rates.
*
* #return String
*/
public String rates() {
DecimalFormat dfmt = new DecimalFormat("0.00");
String rates = "\n------------------------------\n"
+ "Rates for " + getName()
+ "\n------------------------------\n"
+ "FlipPhone Talk Rate: $" + dfmt.format(FlipPhone.TALK_RATE)
+ " Text Rate: $" + dfmt.format(FlipPhone.TEXT_RATE)
+ "\nSmartPhone Talk Rate: $" + dfmt.format(SmartPhone.TALK_RATE)
+ " Text Rate: $" + dfmt.format(SmartPhone.TEXT_RATE)
+ " Max Talk Time: " + SmartPhone.MAX_TALK_TIME
+ "\n iPhone iMessage Rate: $" + dfmt.format(IPhone.IMESSAGE_RATE)
+ "\n Android Hotspot Rate: $" + dfmt.format(Android.HOTSPOT_RATE)
+ "\n";
return rates;
}
/**
* Returns string of phones sorted by number.
*
* #return String
*/
public String listByNumber() {
Arrays.sort(phones);
String listByNumber = "------------------------------"
+ "\nCell Phones by Number"
+ "\n------------------------------\n";
for (CellPhone phone : phones) {
listByNumber += "\n" + phone.toString() + "\n";
}
return listByNumber;
}
/**
* Returns string of phones sorted by bill.
*
* #return String
*/
public String listByBill() {
Arrays.sort(phones, new CellPhoneBillComparator());
String listByBill = "------------------------------"
+ "\nCell Phones by Billing Amount"
+ "\n------------------------------\n";
for (CellPhone phone : phones) {
listByBill += "\n" + phone.toString() + "\n";
}
return listByBill;
}
/**
* Returns string excluded records.
*
* #return String
*/
public String excludedRecordsList() {
String excRecList = "------------------------------"
+ "\nExcluded Records"
+ "\n------------------------------\n";
for (String unrecPhones : excludedRecords) {
excRecList += "\n" + unrecPhones + "\n";
}
return excRecList;
}
}
CellPhone[] newPhones = new CellPhone[phones.length - 1];
phones = newPhones;
This line declares a new array, but does not fill any values, they are all null. You need to loop through newPhones and assign all the values.
CellPhone[] newPhones = new CellPhone[phones.length - 1];
for (int i = 0; i < newPhones.length; i++) {
newPhones[i] = phones[i];
}
phones = newPhones;
Please move phones[phones.length - 1] = null; out of for loop. Then you need some code to copy data between phones and newPhones, move those code to outside of for loop, too.
for (int i = deleteIndex; i < phones.length - 1; i++) {
phones[i] = phones[i + 1];
// Move three lines of code
phones[phones.length - 1] = null; // <= Problem here
CellPhone[] newPhones = new CellPhone[phones.length - 1];
// Need some code to copy data
phones = newPhones;
}
Finally, anyway, you must copy data to the new array, so I think you should copy it from the beginning:
CellPhone[] newPhones = new CellPhone[phones.length - 1];
int oldIndex = 0, newIndex = 0;
while (oldIndex < phones.length) {
if (oldIndex != deleteIndex) { // Skip copying deleted number
newPhones[newIndex++] = phones[oldIndex];
}
oldIndex++;
}
The problem should happen at the loop when you tried to set your last element to null when loop and copy:
if (deleteIndex > -1) {
for (int i = deleteIndex; i < phones.length - 1; i++) {
phones[i] = phones[i + 1];
phones[phones.length - 1] = null; //<====== This line
CellPhone[] newPhones = new CellPhone[phones.length - 1];
phones = newPhones;
}
return true;
}
else {
return false;
}
At any loop time, the 1st row copys the next element to the current index, but it would be a problem that every time you set the last element to null, because that will happen before you can copy it into the previous element of the array.
I would suggest to change to:
if (deleteIndex > -1) {
for (int i = deleteIndex; i < phones.length - 1; i++) {
phones[i] = phones[i + 1];
}
CellPhone[] newPhones = new CellPhone[phones.length - 1];
System.arraycopy(phones, 0, newPhones, 0, phones.length - 1);
return true;
}
else {
return false;
}
if (deleteIndex > -1) {
CellPhone[] tmp = new CellPhone[phones.length - 1]; // smaller array
//copy everything before deleteIndex
System.arraycopy(phones, 0, tmp, 0, deleteIndex);
//copy everything after deleteIndex
if (deleteIndex < phones.length - 1)
{
System.arraycopy(phones, deleteIndex+1, tmp, deleteIndex,
phones.length - 1 - deleteIndex);
}
phones=tmp; // use new smaller array
}
Arrays are a headache, i prefer ArrayLists; try this
public boolean deletePhone(String numberIn) {
boolean phoneExists = false;
List<String> phoneList = new ArrayList<>();
for (int i = 0; i < phones.length; i++) {
if (!numberIn.equals(phones[i].getNumber())) {
phoneList.add(phones[i].getNumber());
phoneExists = true;
}
}
phones = phoneList.toArray(new String[phoneList.size()]);
return phoneExists;
}
If you don't like lists, here's a solution using just arrays:
public boolean deletePhone(String numberIn) {
boolean phoneExists = false;
String[] newPhones;
int newLength = phones.length;
for (int i = 0; i < phones.length; i++) {
if (numberIn.equals(phones[i].getPhones())) {
phones[i] = null;
newLength--;
phoneExists = true;
}
}
newPhones = new CellPhone[newLength];
for (int i = 0, j = 0; i < phones.length; i++) {
if (phones[i] != null) {
newPhones[j++] = phones[i];
}
}
phones = newPhones;
return phoneExists;
}