Output and Screenshot
P2.WordFrequency/.classpath
__MACOSX/P2.WordFrequency/._.classpath
P2.WordFrequency/.DS_Store
__MACOSX/P2.WordFrequency/._.DS_Store
P2.WordFrequency/.project
P2.WordFrequency org.eclipse.jdt.core.javabuilder org.eclipse.jdt.core.javanature edu.umd.cs.eclipse.courseProjectManager.autoRunLogNature edu.umd.cs.eclipse.courseProjectManager.autoCVSNature edu.umd.cs.eclipse.courseProjectManager.autoSyncNature
__MACOSX/P2.WordFrequency/._.project
P2.WordFrequency/.settings/org.eclipse.jdt.core.prefs
eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve org.eclipse.jdt.core.compiler.compliance=1.8 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.source=1.8
__MACOSX/P2.WordFrequency/.settings/._org.eclipse.jdt.core.prefs
__MACOSX/P2.WordFrequency/._.settings
P2.WordFrequency/bin/.DS_Store
P2.WordFrequency/bin/frequency/.DS_Store
P2.WordFrequency/bin/tests/.DS_Store
P2.WordFrequency/bin/utils/.DS_Store
__MACOSX/P2.WordFrequency/._bin
P2.WordFrequency/einstein.txt
Collected Quotes from Albert Einstein "Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius -- and a lot of courage -- to move in the opposite direction." "Imagination is more important than knowledge." "Gravitation is not responsible for people falling in love." "I want to know God's thoughts; the rest are details." "The hardest thing in the world to understand is the income tax." "Reality is merely an illusion, albeit a very persistent one." "The only real valuable thing is intuition." "A person starts to live when he can live outside himself." "I am convinced that He (God) does not play dice." "God is subtle but he is not malicious." "Weakness of attitude becomes weakness of character." "I never think of the future. It comes soon enough." "The eternal mystery of the world is its comprehensibility." "Sometimes one pays most for the things one gets for nothing." "Science without religion is lame. Religion without science is blind." "Anyone who has never made a mistake has never tried anything new." "Great spirits have often encountered violent opposition from weak minds." "Everything should be made as simple as possible, but not simpler." "Common sense is the collection of prejudices acquired by age eighteen." "Science is a wonderful thing if one does not have to earn one's living at it." "The secret to creativity is knowing how to hide your sources." "The only thing that interferes with my learning is my education." "God does not care about our mathematical difficulties. He integrates empirically." "The whole of science is nothing more than a refinement of everyday thinking." "Technological progress is like an axe in the hands of a pathological criminal." "Peace cannot be kept by force. It can only be achieved by understanding." "The most incomprehensible thing about the world is that it is comprehensible." "We can't solve problems by using the same kind of thinking we used when we created them." "Education is what remains after one has forgotten everything he learned in school." "The important thing is not to stop questioning. Curiosity has its own reason for existing." "Do not worry about your difficulties in Mathematics. I can assure you mine are still greater." "Equations are more important to me, because politics is for the present, but an equation is something for eternity." "If A is a success in life, then A equals x plus y plus z. Work is x; y is play; and z is keeping your mouth shut." "Two things are infinite: the universe and human stupidity; and I'm not sure about the the universe." "As far as the laws of mathematics refer to reality, they are not certain, as far as they are certain, they do not refer to reality." "Whoever undertakes to set himself up as a judge of Truth and Knowledge is shipwrecked by the laughter of the gods." "I know not with what weapons World War III will be fought, but World War IV will be fought with sticks and stones." "In order to form an immaculate member of a flock of sheep one must, above all, be a sheep." "The fear of death is the most unjustified of all fears, for there's no risk of accident for someone who's dead." "Too many of us look upon Americans as dollar chasers. This is a cruel libel, even if it is reiterated thoughtlessly by the Americans themselves." "Heroism on command, senseless violence, and all the loathsome nonsense that goes by the name of patriotism -- how passionately I hate them!" "No, this trick won't work...How on earth are you ever going to explain in terms of chemistry and physics so important a biological phenomenon as first love?" "My religion consists of a humble admiration of the illimitable superior spirit who reveals himself in the slight details we are able to perceive with our frail and feeble mind." "Yes, we have to divide up our time like that, between our politics and our equations. But to me our equations are far more important, for politics are only a matter of present concern. A mathematical equation stands forever." "The release of atom power has changed everything except our way of thinking...the solution to this problem lies in the heart of mankind. If only I had known, I should have become a watchmaker." "Great spirits have always found violent opposition from mediocrities. The latter cannot understand it when a man does not thoughtlessly submit to hereditary prejudices but honestly and courageously uses his intelligence." "The most beautiful thing we can experience is the mysterious. It is the source of all true art and all science. He to whom this emotion is a stranger, who can no longer pause to wonder and stand rapt in awe, is as good as dead: his eyes are closed." "A man's ethical behavior should be based effectually on sympathy, education, and social ties; no religious basis is necessary. Man would indeeded be in a poor way if he had to be restrained by fear of punishment and hope of reward after death." "The further the spiritual evolution of mankind advances, the more certain it seems to me that the path to genuine religiosity does not lie through the fear of life, and the fear of death, and blind faith, but through striving after rational knowledge." "Now he has departed from this strange world a little ahead of me. That means nothing. People like us, who believe in physics, know that the distinction between past, present, and future is only a stubbornly persistent illusion." "You see, wire telegraph is a kind of a very, very long cat. You pull his tail in New York and his head is meowing in Los Angeles. Do you understand this? And radio operates exactly the same way: you send signals here, they receive them there. The only difference is that there is no cat." "One had to cram all this stuff into one's mind for the examinations, whether one liked it or not. This coercion had such a deterring effect on me that, after I had passed the final examination, I found the consideration of any scientific problems distasteful to me for an entire year." "...one of the strongest motives that lead men to art and science is escape from everyday life with its painful crudity and hopeless dreariness, from the fetters of one's own ever-shifting desires. A finely tempered nature longs to escape from the personal life into the world of objective perception and thought." "He who joyfully marches to music rank and file, has already earned my contempt. He has been given a large brain by mistake, since for him the spinal cord would surely suffice. This disgrace to civilization should be done away with at once. Heroism at command, how violently I hate all this, how despicable and ignoble war is; I would rather be torn to shreds than be a part of so base an action. It is my conviction that killing under the cloak of war is nothing but an act of murder." "A human being is a part of a whole, called by us _universe_, a part limited in time and space. He experiences himself, his thoughts and feelings as something separated from the rest... a kind of optical delusion of his consciousness. This delusion is a kind of prison for us, restricting us to our personal desires and to affection for a few persons nearest to us. Our task must be to free ourselves from this prison by widening our circle of compassion to embrace all living creatures and the whole of nature in its beauty." "Not everything that counts can be counted, and not everything that can be counted counts." (Sign hanging in Einstein's office at Princeton)
__MACOSX/P2.WordFrequency/._einstein.txt
P2.WordFrequency/pubEinstein.txt
(the,60),(of,49),(is,46),(a,39),(to,36),(and,31),(in,19),(not,17),(be,15),(for,14),(that,14),(i,13),(as,12),(one,12),(this,12),(are,11),(by,11),(he,11),(it,11),(our,10),
__MACOSX/P2.WordFrequency/._pubEinstein.txt
P2.WordFrequency/pubSyllabus.txt
(the,63),(a,62),(li,58),(td,49),(tr,35),(of,33),(to,33),(p,30),(h,24),(strong,24),(edu,22),(href,22),(umd,22),(for,21),(and,19),(class,19),(www,19),(https,15),(your,15),(any,14),(you,14),(be,13),(cs,13),(is,13),(student,13),(summer,13),(th,13),(project,12),(projects,12),(ul,12),(as,11),(cmsc,11),(submit,11),(will,11),(academic,10),(in,10),(table,10),(http,9),(on,9),(shtml,9),(by,8),(or,8),(tbody,8),(width,8),(code,7),(must,7),(programming,7),(that,7),(an,6),(are,6),(assignments,6),(at,6),(course,6),(information,6),(server,6),(from,5),(html,5),(id,5),(it,5),(not,5),(pm,5),(this,5),(which,5),(with,5),(absence,4),(all,4),(amp,4),(border,4),(closed,4),(complete,4),(courseevalum,4),(deadline,4),(div,4),(due,4),(e,4),(evaluation,4),(final,4),(grading,4),(have,4),(instructor,4),(more,4),(no,4),(object,4),(office,4),(open,4),(oriented,4),(prior,4),(s,4),(textbooks,4),(title,4),(we,4),(algorithms,3),(assignment,3),(center,3),(conduct,3),(content,3),(dishonesty,3),(documentation,3),(evaluations,3),(exam,3),(excused,3),(g,3),(graded,3),(grades,3),(if,3),(illness,3),(integrity,3),(irpa,3),(late,3),(link,3),(major,3),(make,3),(may,3),(note,3),(notice,3),(only,3),(other,3),(regrade,3),(responsibility,3),(results,3),(scheduled,3),(semester,3),(submission,3),(submitted,3),(syllabus,3),(tests,3),(their,3),(there,3),(university,3),(very,3),(web,3),(accommodations,2),(after,2),(also,2),(assessment,2),(avw,2),(bld,2),(body,2),(but,2),(cellpadding,2),(cellspacing,2),(cheating,2),(collaboration,2),(com,2),(compilable,2),(courseeval,2),(courses,2),(css,2),(day,2),(design,2),(disability,2),(each,2),(etc,2),(events,2),(exams,2),(fabrication,2),(fac,2),(faq,2),(following,2),(grade,2),(hardcoding,2),(head,2),(health,2),(ii,2),(implementation,2),(important,2),(includes,2),(inform,2),(internet,2),(java,2),(lab,2),(last,2),(midterm,2),(need,2),(needs,2),(ol,2),(online,2),(openclosedpolicy,2),(otherwise,2),(penalty,2),(permitted,2),(piazza,2),(plagiarism,2),(please,2),(policy,2),(possible,2),(program,2),(provide,2),(provided,2),(reasonable,2),(receive,2),(recommended,2),(regarding,2),(requests,2),(resources,2),(schedule,2),(score,2),(see,2),(self,2),(shall,2),
__MACOSX/P2.WordFrequency/._pubSyllabus.txt
P2.WordFrequency/pubTest1.txt
(alice,4),(bob,3),(cathy,2),(david,1),(ethan,1),(frank,1),
__MACOSX/P2.WordFrequency/._pubTest1.txt
P2.WordFrequency/pubWar_peace.txt
(the,34540),(and,22234),(to,16674),(of,14880),(a,10542),(he,9998),(in,8976),(that,8190),(his,7985),(was,7356),(with,5664),(it,5600),(had,5365),(her,4725),(not,4676),(him,4637),(at,4530),(i,4522),(s,4403),(but,4049),(as,4023),(on,4002),(you,3798),(for,3528),(she,3487),(is,3323),(said,2842),(all,2795),(from,2695),(be,2439),(by,2436),(were,2425),(what,2397),(they,2255),(who,2162),(one,2133),(this,2075),(which,2057),(have,1975),(pierre,1962),(prince,1926),(so,1902),(an,1627),(up,1577),(there,1560),(them,1529),(or,1525),(when,1498),(did,1482),(been,1476),
__MACOSX/P2.WordFrequency/._pubWar_peace.txt
P2.WordFrequency/src/.DS_Store
__MACOSX/P2.WordFrequency/src/._.DS_Store
P2.WordFrequency/src/frequency/.DS_Store
__MACOSX/P2.WordFrequency/src/frequency/._.DS_Store
P2.WordFrequency/src/frequency/Frequency.java
P2.WordFrequency/src/frequency/Frequency.java
/**
* Word frequency counter
*/
package
frequency
;
import
java
.
util
.
Iterator
;
/**
*
*
@author
UMD CS
*/
public
class
Frequency
implements
Iterable
<
String
>
{
private
Node
first
;
private
int
N
;
Frequency
(){
N
=
0
;
first
=
null
;
}
@
Override
public
Iterator
<
String
>
iterator
()
{
return
new
ListIterator
();
}
/**
*
* List iterator
*
*/
private
class
ListIterator
implements
Iterator
<
String
>
{
private
Node
current
;
private
int
index
;
ListIterator
(){
current
=
first
;
index
=
0
;
}
@
Override
public
boolean
hasNext
()
{
return
current
!=
null
;
}
public
String
next
()
{
if
(
!
hasNext
()){
return
null
;
}
String
word
=
current
.
key
;
int
count
=
current
.
count
;
String
r
=
"("
+
word
+
","
+
Integer
.
toString
(
count
)
+
")"
;
current
=
current
.
next
;
return
r
;
}
@
Override
public
void
remove
()
{
}
}
/**
*
* Node class
*
*/
private
class
Node
{
private
String
key
;
private
int
count
;
private
Node
next
;
Node
(
String
item
){
key
=
item
;
count
=
1
;
next
=
null
;
}
@
Override
public
String
toString
(){
return
"("
+
key
+
","
+
count
+
")"
;
}
}
/*
* Inserts a word into the linked list. If the word exists, increment the
* count by q.
*/
public
void
insert
(
String
word
){
if
(
word
.
equals
(
""
)){
return
;
}
//TODO
/*
* implement here
*/
}
/**
*
*
@param
str input string
* This method splits a string into words and pass the words to insert method
*
*/
public
void
insertWords
(
String
str
){
String
delims
=
"[ .,?!'\"()}{;/<>&=#-:\\ _]+"
;
String
[]
words
=
str
.
split
(
delims
);
for
(
String
s
:
words
){
s
=
s
.
toLowerCase
();
insert
(
s
);
}
}
/**
* prints the word frequency list
*/
public
void
print
(){
Node
c
=
first
;
while
(
c
!=
null
){
System
.
out
.
print
(
"("
+
c
.
key
+
","
+
c
.
count
+
")"
);
c
=
c
.
next
;
}
System
.
out
.
print
(
"\n"
);
}
}
__MACOSX/P2.WordFrequency/src/frequency/._Frequency.java
P2.WordFrequency/src/frequency/WordFrequency.java
P2.WordFrequency/src/frequency/WordFrequency.java
package
frequency
;
import
utils
.
In
;
import
utils
.
Stopwatch
;
/**
*
*
@author
UMD CS
*/
public
class
WordFrequency
{
/**
*
@param
input source
*
@param
* This method receives input resource and return the word frequency string
* DO NOT CHANGE THIS METHOD.
*/
public
static
String
freq
(
String
inputSource
,
int
maxLines
){
In
in
;
// Frequency class can only count the frequency of strings. DO NOT CHANGE THIS.
Frequency
freq
=
new
Frequency
();
int
MAX
=
100
;
String
inputSourceName
=
inputSource
;
try
{
in
=
new
In
(
inputSourceName
);
while
(
!
in
.
isEmpty
())
{
String
s
=
in
.
readLine
();
//System.out.println(s);
freq
.
insertWords
(
s
);
}
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
StringBuilder
strFrequency
=
new
StringBuilder
();
int
cnt
=
0
;
for
(
String
s
:
freq
){
strFrequency
.
append
(
s
);
strFrequency
.
append
(
","
);
cnt
++
;
if
(
cnt
>=
maxLines
){
break
;}
}
return
strFrequency
.
toString
();
}
/**
*
*/
public
static
void
main
(
String
[]
args
)
{
In
in
;
Frequency
freq
=
new
Frequency
();
int
MAX
=
100
;
// String inputSourceName = "http://www.cs.umd.edu/class/summer2015/cmsc132/projects/P3_WordFrequency/test1.html";
String
inputSourceName
=
"einstein.txt"
;
// read one line at a time from URL
System
.
out
.
println
(
"read from "
+
inputSourceName
);
System
.
out
.
println
(
"---------------------------------------------------------------------------"
);
Stopwatch
sw
=
new
Stopwatch
();
try
{
in
=
new
In
(
inputSourceName
);
while
(
!
in
.
isEmpty
())
{
String
s
=
in
.
readLine
();
//System.out.println(s);
freq
.
insertWords
(
s
);
}
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
System
.
out
.
println
(
"Elapsed time:"
+
sw
.
elapsedTime
());
int
cnt
=
0
;
for
(
String
s
:
freq
){
System
.
out
.
println
(
s
);
cnt
++
;
if
(
cnt
>=
MAX
){
break
;}
}
}
}
__MACOSX/P2.WordFrequency/src/frequency/._WordFrequency.java
__MACOSX/P2.WordFrequency/src/._frequency
P2.WordFrequency/src/tests/.DS_Store
__MACOSX/P2.WordFrequency/src/tests/._.DS_Store
P2.WordFrequency/src/tests/PublicTests.java
P2.WordFrequency/src/tests/PublicTests.java
package
tests
;
import
static
org
.
junit
.
Assert
.
*
;
import
org
.
junit
.
Test
;
import
frequency
.
WordFrequency
;
public
class
PublicTests
{
@
Test
public
void
testEinstein
()
{
String
answer
=
WordFrequency
.
freq
(
"einstein.txt"
,
20
);
assertTrue
(
TestsSupport
.
isCorrect
(
"pubEinstein.txt"
,
answer
));
}
@
Test
public
void
test1
()
{
String
answer
=
WordFrequency
.
freq
(
"test1.txt"
,
10
);
assertTrue
(
TestsSupport
.
isCorrect
(
"pubTest1.txt"
,
answer
));
}
@
Test
public
void
testSyllabus
()
{
String
answer
=
WordFrequency
.
freq
(
"https://www.cs.umd.edu/class/summer2015/cmsc132/syllabus.shtml"
,
200
);
assertTrue
(
TestsSupport
.
isCorrect
(
"pubSyllabus.txt"
,
answer
));
}
@
Test
public
void
testWar_peace
()
{
String
answer
=
WordFrequency
.
freq
(
"war_peace.txt"
,
50
);
assertTrue
(
TestsSupport
.
isCorrect
(
"pubWar_peace.txt"
,
answer
));
}
}
__MACOSX/P2.WordFrequency/src/tests/._PublicTests.java
P2.WordFrequency/src/tests/TestsSupport.java
P2.WordFrequency/src/tests/TestsSupport.java
package
tests
;
import
java
.
io
.
BufferedReader
;
import
java
.
io
.
FileReader
;
import
java
.
io
.
FileWriter
;
import
java
.
io
.
IOException
;
import
java
.
util
.
Scanner
;
import
javax
.
swing
.
JOptionPane
;
public
class
TestsSupport
{
/* Leave the following variable set to false. We use while developing the */
/* expected solutions for a test. If you change it to false you will corrupt */
/* your *.txt files containing expected results. */
private
static
boolean
generateOfficialResults
=
false
;
/**
* Feel free to use the correctResults method while developing your own tests.
* Notice that if you define text files with some expected results, the text
* files must be named starting with "studentTest" and ending with the .txt
* extension. If you don't name files this way, then the submit server will
* generate an authorization error.
*
@param
filename
*
@param
results
*
@return
true if the contents of the file corresponds to those in results
*/
public
static
boolean
isCorrect
(
String
filename
,
String
results
)
{
officialUseIgnore
(
filename
,
results
);
String
officialResults
=
""
;
try
{
BufferedReader
fin
=
new
BufferedReader
(
new
FileReader
(
filename
));
String
line
;
while
((
line
=
fin
.
readLine
())
!=
null
)
{
officialResults
+=
line
+
"\n"
;
}
fin
.
close
();
}
catch
(
IOException
e
)
{
System
.
out
.
println
(
"File operation in isCorrect failed."
);
return
false
;
}
results
=
removeBlanks
(
results
);
officialResults
=
removeBlanks
(
officialResults
);
if
(
results
.
equals
(
officialResults
))
{
return
true
;
}
return
false
;
}
public
static
boolean
sameContents
(
String
firstFile
,
String
secondFile
)
{
if
(
removeBlanks
(
fileData
(
firstFile
)).
equals
(
removeBlanks
(
fileData
(
secondFile
))))
return
true
;
return
false
;
}
public
static
String
fileData
(
String
fileName
)
{
StringBuffer
stringBuffer
=
new
StringBuffer
();
try
{
FileReader
fileReader
=
new
FileReader
(
fileName
);
BufferedReader
bufferedReader
=
new
BufferedReader
(
fileReader
);
Scanner
fileScanner
=
new
Scanner
(
bufferedReader
);
while
(
fileScanner
.
hasNextLine
())
stringBuffer
.
append
(
fileScanner
.
nextLine
());
fileScanner
.
close
();
}
catch
(
IOException
e
)
{
System
.
out
.
println
(
e
.
getMessage
());
}
return
stringBuffer
.
toString
();
}
public
static
String
removeBlanks
(
String
src
)
{
StringBuffer
resultsBuf
=
new
StringBuffer
();
char
curr
;
for
(
int
i
=
0
;
i
<
src
.
length
();
i
++
)
{
curr
=
src
.
charAt
(
i
);
if
(
curr
!=
' '
&&
curr
!=
'\n'
)
resultsBuf
.
append
(
curr
);
}
return
resultsBuf
.
toString
();
}
public
static
boolean
writeToFile
(
String
filename
,
String
message
)
{
try
{
FileWriter
output
=
new
FileWriter
(
filename
);
output
.
write
(
message
);
output
.
close
();
}
catch
(
IOException
exception
)
{
System
.
out
.
println
(
"ERROR: Writing to file "
+
filename
+
" failed."
);
return
false
;
}
return
true
;
}
/**
* We use this method to generate text files with the expected results for a test.
*
@param
filename
*
@param
results
*/
private
static
void
officialUseIgnore
(
String
filename
,
String
results
)
{
if
(
generateOfficialResults
)
{
String
warningMessage
=
"Warning: You will overwrite result files."
;
warningMessage
+=
" Do you want to continue?"
;
if
(
JOptionPane
.
showConfirmDialog
(
null
,
warningMessage
)
==
JOptionPane
.
YES_OPTION
)
{
TestsSupport
.
writeToFile
(
filename
,
results
);
System
.
out
.
println
(
"File "
+
filename
+
" has been updated."
);
}
}
}
}
__MACOSX/P2.WordFrequency/src/tests/._TestsSupport.java
__MACOSX/P2.WordFrequency/src/._tests
P2.WordFrequency/src/utils/.DS_Store
__MACOSX/P2.WordFrequency/src/utils/._.DS_Store
P2.WordFrequency/src/utils/In.java
P2.WordFrequency/src/utils/In.java
package
utils
;
/*************************************************************************
* Compilation: javac In.java
* Execution: java In (basic test --- see source for required files)
*
* Reads in data of various types from standard input, files, and URLs.
*
*************************************************************************/
import
java
.
io
.
BufferedInputStream
;
import
java
.
io
.
File
;
import
java
.
io
.
IOException
;
import
java
.
io
.
InputStream
;
import
java
.
net
.
URL
;
import
java
.
net
.
HttpURLConnection
;
import
java
.
net
.
URLConnection
;
import
java
.
util
.
ArrayList
;
import
java
.
util
.
InputMismatchException
;
import
java
.
util
.
Locale
;
import
java
.
util
.
Scanner
;
import
java
.
util
.
regex
.
Pattern
;
/**
* <i>Input</i>. This class provides methods for reading strings
* and numbers from standard input, file input, URLs, and sockets.
* <p>
* The Locale used is: language = English, country = US. This is consistent
* with the formatting conventions with Java floating-point literals,
* command-line arguments (via {
@link
Double#parseDouble(String)})
* and standard output.
* <p>
* For additional documentation, see
* <a href="http://introcs.cs.princeton.edu/31datatype">Section 3.1</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i>
* by Robert Sedgewick and Kevin Wayne.
* <p>
* Like {
@link
Scanner}, reading a token also consumes preceding Java
* whitespace, reading a full line consumes
* the following end-of-line delimeter, while reading a character consumes
* nothing extra.
* <p>
* Whitespace is defined in {
@link
Character#isWhitespace(char)}. Newlines
* consist of \n, \r, \r\n, and Unicode hex code points 0x2028, 0x2029, 0x0085;
* see <tt><a href="http://www.docjar.com/html/api/java/util/Scanner.java.html">
* Scanner.java</a></tt> (NB: Java 6u23 and earlier uses only \r, \r, \r\n).
*
*
@author
David Pritchard
*
@author
Robert Sedgewick
*
@author
Kevin Wayne
*/
public
final
class
In
{
private
Scanner
scanner
;
/*** begin: section (1 of 2) of code duplicated from In to StdIn */
// assume Unicode UTF-8 encoding
private
static
final
String
CHARSET_NAME
=
"UTF-8"
;
// assume language = English, country = US for consistency with System.out.
private
static
final
Locale
LOCALE
=
Locale
.
US
;
// the default token separator; we maintain the invariant that this value
// is held by the scanner's delimiter between calls
private
static
final
Pattern
WHITESPACE_PATTERN
=
Pattern
.
compile
(
"\\p{javaWhitespace}+"
);
// makes whitespace characters significant
private
static
final
Pattern
EMPTY_PATTERN
=
Pattern
.
compile
(
""
);
// used to read the entire input. source:
// http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html
private
static
final
Pattern
EVERYTHING_PATTERN
=
Pattern
.
compile
(
"\\A"
);
/*** end: section (1 of 2) of code duplicated from In to StdIn */
/**
* Create an input stream from standard input.
*/
public
In
()
{
scanner
=
new
Scanner
(
new
BufferedInputStream
(
System
.
in
),
CHARSET_NAME
);
scanner
.
useLocale
(
LOCALE
);
}
/**
* Create an input stream from a socket.
*/
public
In
(
java
.
net
.
Socket
socket
)
{
try
{
InputStream
is
=
socket
.
getInputStream
();
scanner
=
new
Scanner
(
new
BufferedInputStream
(
is
),
CHARSET_NAME
);
scanner
.
useLocale
(
LOCALE
);
}
catch
(
IOException
ioe
)
{
System
.
err
.
println
(
"Could not open "
+
socket
);
}
}
/**
* Create an input stream from a URL.
*/
public
In
(
URL url
)
{
try
{
URLConnection
site
=
url
.
openConnection
();
InputStream
is
=
site
.
getInputStream
();
scanner
=
new
Scanner
(
new
BufferedInputStream
(
is
),
CHARSET_NAME
);
scanner
.
useLocale
(
LOCALE
);
}
catch
(
IOException
ioe
)
{
System
.
err
.
println
(
"Could not open "
+
url
);
}
}
/**
* Create an input stream from a file.
*/
public
In
(
File
file
)
{
try
{
scanner
=
new
Scanner
(
file
,
CHARSET_NAME
);
scanner
.
useLocale
(
LOCALE
);
}
catch
(
IOException
ioe
)
{
System
.
err
.
println
(
"Could not open "
+
file
);
}
}
/**
* Create an input stream from a filename or web page name.
*/
public
In
(
String
s
)
{
try
{
// first try to read file from local file system
File
file
=
new
File
(
s
);
if
(
file
.
exists
())
{
scanner
=
new
Scanner
(
file
,
CHARSET_NAME
);
scanner
.
useLocale
(
LOCALE
);
return
;
}
// next try for files included in jar
URL url
=
getClass
().
getResource
(
s
);
// or URL from web
if
(
url
==
null
)
{
url
=
new
URL
(
s
);
}
URLConnection
site
=
url
.
openConnection
();
// in order to set User-Agent, replace above line with these two
// HttpURLConnection site = (HttpURLConnection) url.openConnection();
// site.addRequestProperty("User-Agent", "Mozilla/4.76");
InputStream
is
=
site
.
getInputStream
();
scanner
=
new
Scanner
(
new
BufferedInputStream
(
is
),
CHARSET_NAME
);
scanner
.
useLocale
(
LOCALE
);
}
catch
(
IOException
ioe
)
{
System
.
err
.
println
(
"Could not open "
+
s
);
}
}
/**
* Create an input stream from a given Scanner source; use with
* <tt>new Scanner(String)</tt> to read from a string.
* <p>
* Note that this does not create a defensive copy, so the
* scanner will be mutated as you read on.
*/
public
In
(
Scanner
scanner
)
{
this
.
scanner
=
scanner
;
}
/**
* Does the input stream exist?
*/
public
boolean
exists
()
{
return
scanner
!=
null
;
}
/*** begin: section (2 of 2) of code duplicated from In to StdIn,
* with all methods changed from "public" to "public static" ***/
/**
* Is the input empty (except possibly for whitespace)? Use this
* to know whether the next call to {
@link
#readString()},
* {
@link
#readDouble()}, etc will succeed.
*/
public
boolean
isEmpty
()
{
return
!
scanner
.
hasNext
();
}
/**
* Does the input have a next line? Use this to know whether the
* next call to {
@link
#readLine()} will succeed. <p> Functionally
* equivalent to {
@link
#hasNextChar()}.
*/
public
boolean
hasNextLine
()
{
return
scanner
.
hasNextLine
();
}
/**
* Is the input empty (including whitespace)? Use this to know
* whether the next call to {
@link
#readChar()} will succeed. <p> Functionally
* equivalent to {
@link
#hasNextLine()}.
*/
public
boolean
hasNextChar
()
{
scanner
.
useDelimiter
(
EMPTY_PATTERN
);
boolean
result
=
scanner
.
hasNext
();
scanner
.
useDelimiter
(
WHITESPACE_PATTERN
);
return
result
;
}
/**
* Read and return the next line.
*/
public
String
readLine
()
{
String
line
;
try
{
line
=
scanner
.
nextLine
();
}
catch
(
Exception
e
)
{
line
=
null
;
}
return
line
;
}
/**
* Read and return the next character.
*/
public
char
readChar
()
{
scanner
.
useDelimiter
(
EMPTY_PATTERN
);
String
ch
=
scanner
.
next
();
assert
(
ch
.
length
()
==
1
)
:
"Internal (Std)In.readChar() error!"
+
" Please contact the authors."
;
scanner
.
useDelimiter
(
WHITESPACE_PATTERN
);
return
ch
.
charAt
(
0
);
}
/**
* Read and return the remainder of the input as a string.
*/
public
String
readAll
()
{
if
(
!
scanner
.
hasNextLine
())
return
""
;
String
result
=
scanner
.
useDelimiter
(
EVERYTHING_PATTERN
).
next
();
// not that important to reset delimeter, since now scanner is empty
scanner
.
useDelimiter
(
WHITESPACE_PATTERN
);
// but let's do it anyway
return
result
;
}
/**
* Read and return the next string.
*/
public
String
readString
()
{
return
scanner
.
next
();
}
/**
* Read and return the next int.
*/
public
int
readInt
()
{
return
scanner
.
nextInt
();
}
/**
* Read and return the next double.
*/
public
double
readDouble
()
{
return
scanner
.
nextDouble
();
}
/**
* Read and return the next float.
*/
public
float
readFloat
()
{
return
scanner
.
nextFloat
();
}
/**
* Read and return the next long.
*/
public
long
readLong
()
{
return
scanner
.
nextLong
();
}
/**
* Read and return the next short.
*/
public
short
readShort
()
{
return
scanner
.
nextShort
();
}
/**
* Read and return the next byte.
*/
public
byte
readByte
()
{
return
scanner
.
nextByte
();
}
/**
* Read and return the next boolean, allowing case-insensitive
* "true" or "1" for true, and "false" or "0" for false.
*/
public
boolean
readBoolean
()
{
String
s
=
readString
();
if
(
s
.
equalsIgnoreCase
(
"true"
))
return
true
;
if
(
s
.
equalsIgnoreCase
(
"false"
))
return
false
;
if
(
s
.
equals
(
"1"
))
return
true
;
if
(
s
.
equals
(
"0"
))
return
false
;
throw
new
InputMismatchException
();