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
Related
I am trying to get a range of card type from a list bins that are associated with that card type, but whenever I ran the code the card-type is printed as null am not sure what I am doing wrong
This are the bins in a text
400000000000,499999999999,visa
500000000000,599999999999,mc
400000000000,499999999999,visa
420008000000,420008999999,visadebit
420008000000,435000999999,visa
540008000000,599999999999,mc
Whenever I Pass 4111111111111111 instead of getting visa i end getting null,
this is what I have done so far
package cardsystem;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
public class Solution {
/**
* An entity to hold bin range details. A bin range is a pair of 12 digit numbers that
* mark the boundaries of the range which is maped to other bin range properties such
* as a card type. The range boundaries are inclusive.
*/
static final class BinRange {
final String start;
final String end;
final String cardType;
BinRange(String start, String end, String cardType) {
this.start = start;
this.end = end;
this.cardType = cardType;
}
}
// I need a hashmap which hold index and CardType. Each index corresponding an interval (start-end).
private static HashMap<Integer, String> cache = new HashMap<>();
private static List<Long> startEndList = new ArrayList<>();
interface CardTypeCache {
/**
* #param cardNumber 12 to 23 digit card number.
* #return the card type for this cardNumber or null if the card number does not
* fall into any valid bin ranges.
*/
String get(String cardNumber);
}
/**
* #param binRanges the list of card bin ranges to build a cache from.
* #return an implementation of CardTypeCache.
*/
public static CardTypeCache buildCache(List<BinRange> binRanges) {
cache = new HashMap<>();
for (int i = 0; i < binRanges.size(); i++) {
cache.put(i, binRanges.get(i).cardType);
}
for (BinRange binRange : binRanges) {
startEndList.add(Long.valueOf(binRange.start)); // Previously, Integer type used, I converted it to 'Long' type
startEndList.add(Long.valueOf(binRange.end));
}
return new CardTypeCacheImpl();
}
static class CardTypeCacheImpl implements CardTypeCache {
public String get(String cardNumber) {
//Integer index = findIndexLinear(Long.valueOf(cardNumber)); // Linear Search
Integer index = findIndexBinary(Long.valueOf(cardNumber)); // Binary Search
return (index != -1) ? cache.get(index) : "null";
}
/**
* Linear Search O(n)
*
* #param cardNumber, Searching an index which is between start-end .
* #return an index. If not found, return -1.
*/
private Integer findIndexLinear(Long cardNumber) {
for (int i = 1; i < startEndList.size(); i += 2) {
if (startEndList.get(i - 1) <= cardNumber && cardNumber <= startEndList.get(i)) {
return i / 2;
}
}
return -1;
}
/**
* Binary Search O(logn)
*
* #param cardNumber, Searching an index which is between start-end .
* #return an index. If not found, return -1.
*/
private Integer findIndexBinary(Long cardNumber) {
int left = 0;
int right = startEndList.size();
while (left < right) {
int mid = left + (right - left) / 2;
if (mid % 2 == 0 && startEndList.get(mid) <= cardNumber && cardNumber <= startEndList.get(mid + 1)) { // right pair (start-end) of mid
return mid / 2;
} else if (mid % 2 == 1 && startEndList.get(mid - 1) <= cardNumber && cardNumber <= startEndList.get(mid)) { // left pair
return mid / 2;
}
if (cardNumber < startEndList.get(mid)) {
right = mid;
} else {
left = mid + 1;
}
}
return -1;
}
}
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out));
File text = new File("D:/dev/CardSystem/src/cardsystem/input.txt");
try (final Scanner scanner = new Scanner(text)) {
List<Solution.BinRange> binRanges = new ArrayList<>();
/*
4111111111111111
400000000000,499999999999,visa
500000000000,599999999999,mc
*/
String cardNumber = scanner.next();
scanner.nextLine();
scanner.useDelimiter("[,\n]");
while (scanner.hasNext()) {
String start = scanner.next();
String end = scanner.next();
String cardType = scanner.next();
binRanges.add(new Solution.BinRange(start, end, cardType));
if (scanner.hasNextLine()) {
scanner.nextLine();
}
}
Solution.CardTypeCache cache = Solution.buildCache(binRanges);
if (cache != null) {
bufferedWriter.write(String.valueOf(cache.get(cardNumber)));
}
}
bufferedWriter.newLine();
bufferedWriter.close();
}
}
What am I doing wrong, been scratching my head for hours
FROM
400000000000,499999999999,visa
500000000000,599999999999,mc
400000000000,499999999999,visa
420008000000,420008999999,visadebit
420008000000,435000999999,visa
540008000000,599999999999,mc
TO
400000000000,499999999999,visa
500000000000,599999999999,mc
400000000000,499999999999,visa
420008000000,420008999999,visadebit
420008000000,435000999999,visa
540008000000,599999999999,mc
you can try and trim the numbers to the left and omit everything that exceeds 12 digits and then you will get a print of the card type to the console
here is a line to add
cardNumber = cardNumber.length() > 13 ? cardNumber.substring(0, 12) : cardNumber;
so the whole function will look like
public String get(String cardNumber) {
cardNumber = cardNumber.length() > 13 ? cardNumber.substring(0, 12) : cardNumber;
Integer index = findIndexLinear(Long.valueOf(cardNumber)); // Linear Search
//Integer index = findIndexBinary(Long.valueOf(cardNumber)); // Binary Search
return (index != -1) ? cache.get(index) : "null";
}
When you print the output:
bufferedWriter.write(String.valueOf(cache.get(cardNumber)));
The cardNumber is "4111111111111111", and you look for it to be in one of the ranges.
4111 1111 1111 1111
4000 0000 0000
I think your card number is outside every range specified in your file. So you can edit your file, i.e.
FROM
400000000000,499999999999,visa
500000000000,599999999999,mc
400000000000,499999999999,visa
420008000000,420008999999,visadebit
420008000000,435000999999,visa
540008000000,599999999999,mc
TO
4000000000000000,4999999999999999,visa
5000000000000000,5999999999999999,mc
4000000000000000,4999999999999999,visa
4200080000000000,4200089999999999,visadebit
4200080000000000,4350009999999999,visa
5400080000000000,5999999999999999,mc
I do not know the site, and I have only asked one question here. I have no idea - how to handle a code problem. I tried a lot - but I could not fix.
I use StringBuilder - for because of its benefits according to the standard string
I want to delete the first character in the string - but the character that appears in the last place - is duplicated - in the last two places.
for example:
i have the String abcdef, when i delete - the first instace - 'a':
i got back the String bcdeff
well i try - to set the length of the String to original length minus one - but this dont give any result.
i try also - to set the string to new String - and after that - send the String that i was save in tmp string - but this do help either.
public void appendBuffer(StringBuilder dictionary)
{
for (int i = 0; i < appendToWindowBuffer; i++) {
if(dictionary.length() == windowSize)
{
dictionary.deleteCharAt(0);
}
if(nextByteIndex<source.length )
{
dictionary.append((char)source[nextByteIndex]);
nextByteIndex++;
}
else
{
currentLookaheadBufferSize--;
}
if(currentSearchBufferSize < searchBufferSize)
{
currentSearchBufferSize++;
}
}
appendToWindowBuffer = 0;
}
full code:
main class
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException
{
System.out.println("main");
String inPath = "C:\\Users\\avraam\\Documents\\final-assignment\\LZ77\\source.txt";
String outPath = "C:\\Users\\avraam\\Documents\\final-assignment\\LZ77\\encoded.txt";
String decompressedPath = "C:\\Users\\avraam\\Documents\\final-assignment\\LZ77\\decoded.txt";
int windowSize = 14;
int lookaheadBufferSize = 6;
LZ77 compress = new LZ77(inPath,outPath,windowSize,lookaheadBufferSize);
compress.compress();
}
}
match class
public class Match {
protected int length;
protected int offset;
protected String value;
public Match(int length, int offset, String value)
{
this.length=length;
this.offset=offset;
this.value = value;
}
public void SetOffset(int offset) { this.offset = offset; }
public void SetLength(int length) { this.length = length; }
public void SetValue(String value) { this.value = value; }
public void AddValue(char value) { this.value += value; }
public void Reset()
{
this.offset = 0;
this.length = 0;
this.value = "";
}
}
LZ77 class
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Arrays;
public class LZ77 {
private String inPath = null;
private String outPath = null;
private File inFile;
private File outFile;
private final int windowSize;
private final int lookaheadBufferSize;
private final int searchBufferSize;
private int nextByteIndex = 0;
//private int lookAheadIndex = 0; //not always should be (windowsize - lookaheadBufferSize.) in the end maybr will be less character in the lookAhead buffer. the index when LookAhead start is equel to the length of SearchBuffer
private int currentSearchBufferSize = 0;
private int currentLookaheadBufferSize = 0;
private int appendToWindowBuffer = 0;
private byte[] source = null;
public LZ77(String inPath,String outPath,int windowSize,int lookaheadBufferSize) throws IOException
{
this.inPath = inPath;
this.outPath = outPath;
this.inFile = new File(inPath);
this.outFile = new File(outPath);
this.windowSize = windowSize;
this.lookaheadBufferSize = lookaheadBufferSize;
this.searchBufferSize = windowSize - lookaheadBufferSize;
this.source = Files.readAllBytes(inFile.toPath());
}
public void compress() throws IOException
{
/*
* 1. create whole windowBuffer (named - `dictionary`)- that will by used by lookahead and by search Buffers.
* 2. create compressed data - where the data that compressed will be send.
* 3. initialize dictionary - look a head buffer by giving it the size of `lookaheadBuffer`.
* 4. start encode.
* 5. make the encode.
*/
System.out.println("compress");
System.out.println("read the file.");
System.out.println("check if source array work: ");
for (int element: source) {
System.out.print((char)element + "");
}
System.out.println("call to bufferInitialize function");
StringBuilder dictionary = new StringBuilder();
bufferInitialize(dictionary);
System.out.println(dictionary.toString());
StringBuilder compressed = new StringBuilder();
encode(dictionary,compressed);
}
public void bufferInitialize(StringBuilder dictionary)
{
System.out.println("bufferInitialize");
for (int i = 0; i < lookaheadBufferSize; i++) {
dictionary.append((char)source[nextByteIndex]);
nextByteIndex++;
currentLookaheadBufferSize++;
}
// initialize the buffer in the beginning with look a head buffer.
}
public void bufferUpdate()
{
// gets int length - and read those number of bytes - from `inPath` source file.
}
public void encode(StringBuilder dictionary,StringBuilder compressed)
{
//while(nextByteIndex < source.length)
while(currentLookaheadBufferSize > 0)
{
Match match = findMatch(dictionary);
System.out.print("<"+match.offset + ","+match.length+","+ dictionary.charAt(currentSearchBufferSize + match.length) + ">");
appendToWindowBuffer = increaseBuffer(match.length);
appendBuffer(dictionary);
}
/**
* do while you reach to the end of the file
* check if there any possible match
* if do so
* find the maxMatch try always to add another character DONE
* call update function -
* the function will update the
* windowbuffer(dictionary), DONE
* nextByteIndex and DONE
* the position of the index that begins the lookAheadBuffer
* and size of the lookahead and
* search buffers, and
* reset the appendToWindowBuffer. DONE
*/
}
public void convertStringToBits()
{
}
public Match findMatch(StringBuilder dictionary)
{
/**
* function get the window buffer - and index to start.
* the function will be find the max match that starts from index 0 to index start (we cant start search after the `start index`)
* because this parts belong to the look a head buffer.
* #param
* #return
*/
Match match= new Match(0,0, "");
String matchedString = null;
int offset;
int matchLookAheadIndex = currentSearchBufferSize;
if(!haveAnyMatch(dictionary))
{
addMatch();
}
else {
matchedString = "" + dictionary.charAt(matchLookAheadIndex);
offset = findMatchIndex(dictionary,matchedString);
while(offset != -1)
{
match.SetLength(match.length + 1);
match.SetOffset(offset);
match.SetValue(matchedString);
matchLookAheadIndex++;
matchedString +=dictionary.charAt(matchLookAheadIndex);
offset = findMatchIndex(dictionary,matchedString);
}
}
return match;
}
public int findMatchIndex(StringBuilder dictionary,String value)
{
int stringLength = value.length();
String tmpMatch = null;
int offsetMatch;
for (int i = currentSearchBufferSize - 1; i >=0; i--)
{
tmpMatch = dictionary.substring(i, i +stringLength );
offsetMatch = currentSearchBufferSize - i;
if(tmpMatch.equals(value))
{
System.out.println("data was match is searchWindow");
System.out.println("the offset from LookAHead is: " + offsetMatch);
return offsetMatch;
}
}
return -1;
}
public boolean haveAnyMatch(StringBuilder dictionary)
{
if (currentSearchBufferSize == 0)
{
System.out.println("dont have match - search buffer is empty now");
return false;
}
if(!isExistInSearchBuffer(dictionary,dictionary.charAt(currentSearchBufferSize)))
{
System.out.println("dont have match - the first character in lookAheadBuffer wasn't found in searchBuffer");
return false;
}
return true;
/*
* check:
* if search buffer is empty
* if the needed character isn't exist in the search buffer
* if the current value is big enough - and match was not found.
*/
}
public boolean isExistInSearchBuffer(StringBuilder dictionary, char isCharAtDictionary)
{
for (int i = 0; i < currentSearchBufferSize; i++) {
if(dictionary.charAt(i) == isCharAtDictionary)
{
return true;
}
}
return false;
}
public void nextMatch(StringBuilder dictionary)
{
/**
* #param: value, window buffer.
* #description: find the current match with the needed value in the search buffer boundaries.
*/
}
public int increaseBuffer(int matchLength)
{
return 1 + matchLength;
/*
* return int - that calulate by how many byte we need to increase the buffer
*/
}
public void addMatch()
{
}
public void addBitSize() {
}
public void appendBuffer(StringBuilder dictionary)
{
for (int i = 0; i < appendToWindowBuffer; i++) {
if(dictionary.length() == windowSize)
{
dictionary.deleteCharAt(0);
}
if(nextByteIndex<source.length )
{
dictionary.append((char)source[nextByteIndex]);
nextByteIndex++;
}
else
{
currentLookaheadBufferSize--;
}
if(currentSearchBufferSize < searchBufferSize)
{
currentSearchBufferSize++;
}
}
appendToWindowBuffer = 0;
}
}
This seems to work:
StringBuilder builder = new StringBuilder("abcdef");
builder.deleteCharAt(0);
System.out.println(builder.toString());
Prints: bcdef
How are you doing it?
the solution that work for me:
i need to write the decompress - to outout file.
I registered to the file - in CHAR - this is not true - need to register output in BYTE
WORNG WAY THAT I DO:
private void writeDecode (StringBuilder decompress) throws IOException
{
Writer write = new FileWriter(this.outFile);
write.write(decompress.toString());
write.close();
}
THE CORRECT WAY
private void WriteToFile(StringBuilder decodedData) throws IOException
{
FileOutputStream outputFileStream = new FileOutputStream(this.outPath);
for(int i = 0; i < decodedData.length(); i++)
{
byte currentByte = (byte)decodedData.charAt(i);
outputFileStream.write(currentByte);
}
outputFileStream.close();
}
I need to register in the file in BYTE - this is the right way.
title: There is a board of size: nxm and a set of words.We need to find such a way of writing words on the board such that one cell include at most one letter and every continuous sequence of letters read horizontally and vertically is a word from a subset of the size K of the set S acquired from file
I don't know how to get data from user in this code. I need code like I describe in the "Title". In this code words can not read from a file.
Does any one help me to solve it out this problem? I need solution before tomorrow. Does any one can do it for me?
import java.util.*;
import java.awt.*;
import java.io.*;
/**
* Solves a crossword puzzle as defined by the heuristics and variables
*/
public class CrosswordSolver {
/**
* Puzzle content (words / border)
*/
private char[][] puzzle;
/**
* Crossword puzzle slots which all need to be fit
*/
private CrosswordSlot[] slots;
/**
* Crossword Puzzle words which can be used to fill the slots
*/
private CrosswordWord[] words;
/**
* Whether there are characters in the field in the puzzle
*/
private int[][] letterUsage;
/**
* The number of backtracks used to try to fill the puzzle.
*/
private int countBacktracks;
public static final char BLANK = ' ';
public static final char FILLED = '#';
CrosswordSolver(char[][] puzzle, CrosswordSlot[] slots, CrosswordWord[] words) {
this.puzzle = puzzle;
this.slots = slots;
this.words = words;
}
/**
* Initialize the puzzle.
*/
private void reinitialize() {
letterUsage = new int[puzzle.length][puzzle[0].length];
countBacktracks = 0;
}
/**
* Solve the crossword puzzle.
*/
private void solve() {
reinitialize();
if (fillPuzzle(0)) {
System.out.println("Solution found!!!");
System.out.println("Backtracks:" + countBacktracks);
} else {
System.out.println("No solution found!!!");
}
}
/**
* Tries to fill the puzzle starting from a slot.
*
* #param slot slot to start filling in from
* #return whether the puzzle could be filled from the current slot
*/
private boolean fillPuzzle(int slot) {
if (slot == slots.length) {
printPuzzle();
return true;
}
for (CrosswordWord word : words) {
if (wordFitInSlot(word, slots[slot])) {
putWordInSlot(word, slots[slot]);
if (fillPuzzle(slot + 1)) {
return true;
} else {
//If we need to backtrack (fillPuzzle(slot + 1) didn't work)
removeWordFromSlot(word, slots[slot]);
}
}
}
countBacktracks++;
return false;
}
/**
* Checks if a word fits in a slot
*
* #param w word to try to fit in slot
* #param slot slot to try to fit the word into
* #return does word fit
*/
private boolean wordFitInSlot(CrosswordWord w, CrosswordSlot slot) {
if (w.getWord().length() != slot.getLength() || w.isUsed()) {
return false;
}
Point position = slot.getStart();
int row = position.y;
int column = position.x;
for (int i = 0; i < slot.getLength(); ++i) {
if (puzzle[row][column] != BLANK && puzzle[row][column] != w.getWord().charAt(i)) {
return false;
}
column += slot.getDirection().x;
row += slot.getDirection().y;
}
return true;
}
/**
* Puts a word inside a slot and sets the word as used.
*
* #param w word to put into the slot
* #param slot slot to put word into
*/
private void putWordInSlot(CrosswordWord w, CrosswordSlot slot) {
Point position = slot.getStart();
int row = position.y;
int column = position.x;
for (int i = 0; i < slot.getLength(); ++i) {
puzzle[row][column] = w.getWord().charAt(i);
letterUsage[row][column]++;
column += slot.getDirection().x;
row += slot.getDirection().y;
}
w.setUsed(true);
}
/**
* Remove word from slot.
*
* #param w word to remove from slot
* #param slot slot to remove the word from
*/
private void removeWordFromSlot(CrosswordWord w, CrosswordSlot slot) {
Point position = slot.getStart();
int row = position.y;
int column = position.x;
for (int i = 0; i < slot.getLength(); ++i) {
letterUsage[row][column]--;
if (letterUsage[row][column] <= 0) {
puzzle[row][column] = BLANK;
}
column += slot.getDirection().x;
row += slot.getDirection().y;
}
w.setUsed(false);
}
/**
* Print the puzzle.
*/
public void printPuzzle() {
printPuzzleBorder();
for (int row = 0; row < puzzle.length; row++) {
System.out.print("|");
for (int col = 0; col < puzzle[row].length; col++) {
System.out.print(puzzle[row][col] + "|");
}
System.out.println();
}
printPuzzleBorder();
System.out.println();
}
/**
* Print the border of the puzzle.
*/
private void printPuzzleBorder() {
for (int i = 0; i < puzzle[0].length * 2; ++i) {
System.out.print("-");
}
System.out.println();
}
public static void main(String args[]) {
CrosswordSlot[] slots = {new CrosswordSlot(new Point(0, 0), new Point(1, 0), 3),
new CrosswordSlot(new Point(0, 0), new Point(0, 1), 3),
new CrosswordSlot(new Point(2, 0), new Point(0, 1), 2),
new CrosswordSlot(new Point(2, 1), new Point(1, 0), 3),
new CrosswordSlot(new Point(4, 0), new Point(0, 1), 2),
};
char[][] smallPuzzle = {{BLANK, BLANK, BLANK, FILLED, BLANK}, {BLANK, FILLED, BLANK, BLANK, BLANK}, {BLANK, BLANK, FILLED, BLANK, FILLED}};
try {
String get_file = "C:/Users/xyz/Desktop/lemma.txt";
System.out.println("File name is:"+get_file);
FileReader fr = new FileReader(get_file);
BufferedReader br = new BufferedReader(fr);
String s1;
FileInputStream fis = new FileInputStream(get_file);
char c1;
while ((s1 = br.readLine()) != null) {
c1= (char)fis.read();
for (int i = 0; i < s1.length(); ++i) {
char c = s1.charAt(i);
if (c1 == 'a' || c1 == 'v' || (c1 == 'a' && c1 == 'd' && c1 == 'v')) {
System.out.println(c1);
//CrosswordWord[] words = {new CrosswordWord("abbey"), new CrosswordWord("accommodate"), new CrosswordWord(" about")};
}
}
} catch (Exception e) {
System.out.println(e);
}
CrosswordWord[] words = {new CrosswordWord("abb"), new CrosswordWord("acb"), new CrosswordWord("add"), new CrosswordWord("ba"), new CrosswordWord("bd")};
CrosswordSolver s = new CrosswordSolver(smallPuzzle, slots, words);
s.printPuzzle();
s.solve();
}
}
/**
* A slot in the crossword puzzle that we will need to fill.
*/
class CrosswordSlot {
private Point start;
private Point direction;
private int length;
public CrosswordSlot(Point start, Point direction, int length) {
this.start = start;
this.direction = direction;
this.length = length;
}
public Point getStart() {
return start;
}
public Point getDirection() {
return direction;
}
public int getLength() {
return length;
}
}
/**
* A word that we will try to fit inside the crossword.
*/
class CrosswordWord {
private String word;
private boolean used;
public CrosswordWord(String word) {
this.word = word;
used = false;
}
public String getWord() {
return word;
}
public boolean isUsed() {
return used;
}
public void setUsed(boolean isUsed) {
used = isUsed;
}
}
I am trying to override the read method of FilterReader in Java. My goal is to substitute one run of characters for another. I have accomplished this, but the code fails to stop and eventually the jvm runs out of memory.
Here is my code so far.
public class Replacer extends FilterReader {
/** string to be replaced */
String find;
/** string that is inserted in place of string find */
String replace;
/** List functioning as a buffer, holds characters
* while checking if we have a match */
LinkedList<Character> buffer;
/**
* Constructs a Replacer with the string to be replaced,
* find, and the string it is replaced with, replace.
*
* #param find the string to be replaced
* #param replace the string to replace find with
* #param in a Reader Object
*/
public Replacer(String find, String replace, Reader in) {
super(in);
this.find = find;
this.replace = replace;
buffer = new LinkedList<Character>();
}
#Override
public int read() throws IOException {
if (this.buffer.size() > 0) return (int)buffer.poll();
boolean isMatch = true;
char x = (char)super.read();
for (int i=0; i < find.length(); i++) {
if (x != this.find.charAt(i)) {
isMatch = false;
this.buffer.add(x);
break;
} else {
this.buffer.add(x);
}
x = (char)super.read();
}
if(isMatch) {
buffer.clear();
for(int i=0; i < replace.length(); i++) {
this.buffer.add(replace.charAt(i));
}
this.buffer.add(x);
}
return (int)buffer.poll();
}
#Override
public int read(char[] b, int off, int len) throws IOException {
int result = -1;
int x = -1;
for (int i = off; i < len; i++) {
x = read();
if (x == -1) {
result = -1;
break;
}
b[i] = (char)x;
result++;
}
return result;
}
}
Here is the test code to run
public class Test {
public static void main(String[] args) throws IOException{
URL mun = new URL("http://www.mun.ca/");
BufferedReader in = new BufferedReader( new Replacer
("head", "balls", new InputStreamReader(mun.openStream())));
String inputLine;
while((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
Any help would be greatly appreciated.
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.!