import java.util.*;
/**
* A game of Nim.
*
* @author Julie Workman
* @version 2.0
*/
public class Game {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Create Player 1...");
Player p1 = createPlayer(in);
System.out.println("\nCreate Player 2...");
Player p2 = createPlayer(in);
System.out.print("\nHow many sticks? ");
int numSticks = in.nextInt();
Pile pile = new Pile(numSticks);
boolean done=false;
while(!done) {
done = play(p1, pile);
if (done) {
System.out.println("\n" + p2.getName()+ " is the winner!!!");
} else {
done = play(p2, pile);
if (done) {
System.out.println("\n" + p1.getName() + " is the winner!!!");
}
}
}
}
/**
* Creates a player based on user input.
* @param in the Scanner to use for input
* @return a GreedyPlayer, TimidPlayer, or RandomPlayer
*/
public static Player createPlayer(Scanner in) {
System.out.print("Player's name? ");
String name = in.next();
System.out.print("Player type (0 - Greedy, 1 - Timid, 2 - Random)? ");
int type = in.nextInt();
if (type == 0) {
in.nextLine(); // remove \n from input stream
System.out.print("What's your jeer? ");
String jeer = in.nextLine();
return new GreedyPlayer(name, jeer);
} else if (type == 1) {
return new TimidPlayer(name);
} else {
return new RandomPlayer(name);
}
}
/**
* Plays a turn of Nim.
* @param p the player whose turn it is
* @param pile the pile of sticks
* @return true if the game is over, false otherwise
*/
public static boolean play(Player p, Pile pile) {
int sticksTaken = p.takeTurn(pile);
System.out.println("\n" + p.getName() + " takes " + sticksTaken + " sticks.\n" +
"There are " + pile.getSticks() + " left in the pile.");
if (pile.getSticks() <= 0) {
return true;
}
return false;
}
}
The play
method runs a turn of the game. It takes in a Player
(the current player)
and the Pile
as inputs, and returns a boolean
indicating whether the game is over.
The play
method runs a turn of the game. It takes in a Player
(the current player)
and the Pile
as inputs, and returns a boolean
indicating whether the game is over.
The implementation of this method is further down in this file.
Instead of directly using a constructor, we use the createPlayer
method to create
a Player
. The method takes in the Scanner
object a parameter, using it to ask the
user what kind of Player
to create. The method then returns the created Player
.
This type of method is called a "factory method".
The implementation of this method is further down in this file.
Instead of directly using a constructor, we use the createPlayer
method to create
a Player
. The method takes in the Scanner
object a parameter, using it to ask the
user what kind of Player
to create. The method then returns the created Player
.
This type of method is called a "factory method".
Like before, this loop runs the game logic. Notice that the game never knows what type
of Player
it is playing with — it doesn't care, as long as the p1
and p2
can
take turns.
Like before, this loop runs the game logic. Notice that the game never knows what type
of Player
it is playing with — it doesn't care, as long as the p1
and p2
can
take turns.
Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.
NoSuchElementException
- if no line was foundIllegalStateException
- if this scanner is closedThis method is where the "wall" between the game and Player
is pierced. The method
does the work of deciding exactly what kind of Player
to create.
Notice that the method returns a Player
, not a GreedyPlayer
, TimidPlayer
, or RandomPlayer
.
The static type of the returned object is Player
, but the dynamic type
might be GreedyPlayer
, TimidPlayer
, or RandomPlayer
.
This method is where the "wall" between the game and Player
is pierced. The method
does the work of deciding exactly what kind of Player
to create.
Notice that the method returns a Player
, not a GreedyPlayer
, TimidPlayer
, or RandomPlayer
.
The static type of the returned object is Player
, but the dynamic type
might be GreedyPlayer
, TimidPlayer
, or RandomPlayer
.
hasNext()
returned
true
.hasNext()
returned
true
.next
in interface Iterator<String>
NoSuchElementException
- if no more tokens are availableIllegalStateException
- if this scanner is closedThis game play remains the same no matter what kind of Player
is playing.
This game play remains the same no matter what kind of Player
is playing.
String
class represents character strings. All
string literals in Java programs, such as "abc"
, are
implemented as instances of this class.
String
class represents character strings. All
string literals in Java programs, such as "abc"
, are
implemented as instances of this class.
Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:
String str = "abc";
is equivalent to:
char data[] = {'a', 'b', 'c'}; String str = new String(data);
Here are some more examples of how strings can be used:
System.out.println("abc"); String cde = "cde"; System.out.println("abc" + cde); String c = "abc".substring(2, 3); String d = cde.substring(1, 2);
The class String
includes methods for examining
individual characters of the sequence, for comparing strings, for
searching strings, for extracting substrings, and for creating a
copy of a string with all characters translated to uppercase or to
lowercase. Case mapping is based on the Unicode Standard version
specified by the Character
class.
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.
Unless otherwise noted, passing a null
argument to a constructor
or method in this class will cause a NullPointerException
to be
thrown.
A String
represents a string in the UTF-16 format
in which supplementary characters are represented by surrogate
pairs (see the section Unicode
Character Representations in the Character
class for
more information).
Index values refer to char
code units, so a supplementary
character uses two positions in a String
.
The String
class provides methods for dealing with
Unicode code points (i.e., characters), in addition to those for
dealing with Unicode code units (i.e., char
values).
Unless otherwise noted, methods for comparing Strings do not take locale
into account. The Collator
class provides methods for
finer-grain, locale-sensitive String comparison.
javac
compiler
may implement the operator with StringBuffer
, StringBuilder
,
or java.lang.invoke.StringConcatFactory
depending on the JDK version. The
implementation of string conversion is typically through the method toString
,
defined by Object
and inherited by all classes in Java.int
.
int
.
An invocation of this method of the form
nextInt()
behaves in exactly the same way as the
invocation nextInt(radix)
, where radix
is the default radix of this scanner.
int
scanned from the inputInputMismatchException
- if the next token does not match the Integer
regular expression, or is out of rangeNoSuchElementException
- if input is exhaustedIllegalStateException
- if this scanner is closednull
then the string
"null"
is printed. Otherwise, the string's characters are
converted into bytes according to the character encoding given to the
constructor, or the default charset if none
specified. These bytes are written in exactly the manner of the
write(int)
method.null
then the string
"null"
is printed. Otherwise, the string's characters are
converted into bytes according to the character encoding given to the
constructor, or the default charset if none
specified. These bytes are written in exactly the manner of the
write(int)
method.s
- The String
to be printedprint(String)
and then
println()
.print(String)
and then
println()
.x
- The String
to be printed.Console.charset()
if the Console
exists,
stdout.encoding otherwise.
Console.charset()
if the Console
exists,
stdout.encoding otherwise.
For simple stand-alone Java applications, a typical way to write a line of output data is:
System.out.println(data)
See the println
methods in class PrintStream
.
A Scanner
breaks its input into tokens using a
delimiter pattern, which by default matches whitespace. The resulting
tokens may then be converted into values of different types using the
various next
methods.
For example, this code allows a user to read a number from the console.
var con = System.console();
if (con != null) {
Scanner sc = new Scanner(con.reader()
);
int i = sc.nextInt();
}
As another example, this code allows long
types to be
assigned from entries in a file myNumbers
:
Scanner sc = new Scanner(new File("myNumbers"));
while (sc.hasNextLong()) {
long aLong = sc.nextLong();
}
The scanner can also use delimiters other than whitespace. This example reads several items in from a string:
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();
prints the following output:
1 2 red blue
The same output can be generated with this code, which uses a regular expression to parse all four tokens at once:
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input);
s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)");
MatchResult result = s.match();
for (int i=1; i<=result.groupCount(); i++)
System.out.println(result.group(i));
s.close();
The default whitespace delimiter used
by a scanner is as recognized by Character.isWhitespace()
. The reset()
method will reset the value of the scanner's delimiter to the default
whitespace delimiter regardless of whether it was previously changed.
A scanning operation may block waiting for input.
The next()
and hasNext()
methods and their
companion methods (such as nextInt()
and
hasNextInt()
) first skip any input that matches the delimiter
pattern, and then attempt to return the next token. Both hasNext()
and next()
methods may block waiting for further input. Whether a
hasNext()
method blocks has no connection to whether or not its
associated next()
method will block. The tokens()
method
may also block waiting for input.
The findInLine()
,
findWithinHorizon()
,
skip()
, and findAll()
methods operate independently of the delimiter pattern. These methods will
attempt to match the specified pattern with no regard to delimiters in the
input and thus can be used in special circumstances where delimiters are
not relevant. These methods may block waiting for more input.
When a scanner throws an InputMismatchException
, the scanner
will not pass the token that caused the exception, so that it may be
retrieved or skipped via some other method.
Depending upon the type of delimiting pattern, empty tokens may be
returned. For example, the pattern "\\s+"
will return no empty
tokens since it matches multiple instances of the delimiter. The delimiting
pattern "\\s"
could return empty tokens since it only passes one
space at a time.
A scanner can read text from any object which implements the Readable
interface. If an invocation of the underlying
readable's read()
method throws an IOException
then the scanner assumes that the end of the input
has been reached. The most recent IOException
thrown by the
underlying readable can be retrieved via the ioException()
method.
When a Scanner
is closed, it will close its input source
if the source implements the Closeable
interface.
A Scanner
is not safe for multithreaded use without
external synchronization.
Unless otherwise mentioned, passing a null
parameter into
any method of a Scanner
will cause a
NullPointerException
to be thrown.
A scanner will default to interpreting numbers as decimal unless a
different radix has been set by using the useRadix(int)
method. The
reset()
method will reset the value of the scanner's radix to
10
regardless of whether it was previously changed.
An instance of this class is capable of scanning numbers in the standard
formats as well as in the formats of the scanner's locale. A scanner's
initial locale is the value returned by the Locale.getDefault(Locale.Category.FORMAT)
method; it may be changed via the useLocale()
method. The reset()
method will reset the value of the
scanner's locale to the initial locale regardless of whether it was
previously changed.
The localized formats are defined in terms of the following parameters,
which for a particular locale are taken from that locale's DecimalFormat
object, df
, and its and
DecimalFormatSymbols
object,
dfs
.
- LocalGroupSeparator
- The character used to separate thousands groups, i.e.,
dfs.
getGroupingSeparator()
- LocalDecimalSeparator
- The character used for the decimal point, i.e.,
dfs.
getDecimalSeparator()
- LocalPositivePrefix
- The string that appears before a positive number (may be empty), i.e.,
df.
getPositivePrefix()
- LocalPositiveSuffix
- The string that appears after a positive number (may be empty), i.e.,
df.
getPositiveSuffix()
- LocalNegativePrefix
- The string that appears before a negative number (may be empty), i.e.,
df.
getNegativePrefix()
- LocalNegativeSuffix
- The string that appears after a negative number (may be empty), i.e.,
df.
getNegativeSuffix()
- LocalNaN
- The string that represents not-a-number for floating-point values, i.e.,
dfs.
getNaN()
- LocalInfinity
- The string that represents infinity for floating-point values, i.e.,
dfs.
getInfinity()
The strings that can be parsed as numbers by an instance of this class are specified in terms of the following regular-expression grammar, where Rmax is the highest digit in the radix being used (for example, Rmax is 9 in base 10).
Character.isDigit
(c)
returns true
[1-
Rmax] |
NonASCIIDigit
[0-
Rmax] |
NonASCIIDigit
(
Non0Digit
Digit?
Digit?
(
LocalGroupSeparator
Digit
Digit
Digit )+ )
( (
Digit+ )
|
GroupedNumeral )
( [-+]? (
Numeral
) )
|
LocalPositivePrefix Numeral
LocalPositiveSuffix
|
LocalNegativePrefix Numeral
LocalNegativeSuffix
|
Numeral
LocalDecimalSeparator
Digit*
|
LocalDecimalSeparator
Digit+
( [eE] [+-]?
Digit+ )
( [-+]?
DecimalNumeral
Exponent? )
|
LocalPositivePrefix
DecimalNumeral
LocalPositiveSuffix
Exponent?
|
LocalNegativePrefix
DecimalNumeral
LocalNegativeSuffix
Exponent?
[-+]? 0[xX][0-9a-fA-F]*\.[0-9a-fA-F]+
([pP][-+]?[0-9]+)?
NaN
|
LocalNan
| Infinity
|
LocalInfinity
( [-+]?
NonNumber )
|
LocalPositivePrefix
NonNumber
LocalPositiveSuffix
|
LocalNegativePrefix
NonNumber
LocalNegativeSuffix
|
HexFloat
|
SignedNonNumber
Whitespace is not significant in the above regular expressions.
InputStreamReader
, Console.charset()
should be used for the charset, or consider using
Console.reader()
.InputStreamReader
, Console.charset()
should be used for the charset, or consider using
Console.reader()
.Scanner
that produces values scanned
from the specified input stream. Bytes from the stream are converted
into characters using the
default charset.Scanner
that produces values scanned
from the specified input stream. Bytes from the stream are converted
into characters using the
default charset.source
- An input stream to be scannedA Scanner
breaks its input into tokens using a
delimiter pattern, which by default matches whitespace. The resulting
tokens may then be converted into values of different types using the
various next
methods.
For example, this code allows a user to read a number from the console.
var con = System.console();
if (con != null) {
Scanner sc = new Scanner(con.reader()
);
int i = sc.nextInt();
}
As another example, this code allows long
types to be
assigned from entries in a file myNumbers
:
Scanner sc = new Scanner(new File("myNumbers"));
while (sc.hasNextLong()) {
long aLong = sc.nextLong();
}
The scanner can also use delimiters other than whitespace. This example reads several items in from a string:
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();
prints the following output:
1 2 red blue
The same output can be generated with this code, which uses a regular expression to parse all four tokens at once:
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input);
s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)");
MatchResult result = s.match();
for (int i=1; i<=result.groupCount(); i++)
System.out.println(result.group(i));
s.close();
The default whitespace delimiter used
by a scanner is as recognized by Character.isWhitespace()
. The reset()
method will reset the value of the scanner's delimiter to the default
whitespace delimiter regardless of whether it was previously changed.
A scanning operation may block waiting for input.
The next()
and hasNext()
methods and their
companion methods (such as nextInt()
and
hasNextInt()
) first skip any input that matches the delimiter
pattern, and then attempt to return the next token. Both hasNext()
and next()
methods may block waiting for further input. Whether a
hasNext()
method blocks has no connection to whether or not its
associated next()
method will block. The tokens()
method
may also block waiting for input.
The findInLine()
,
findWithinHorizon()
,
skip()
, and findAll()
methods operate independently of the delimiter pattern. These methods will
attempt to match the specified pattern with no regard to delimiters in the
input and thus can be used in special circumstances where delimiters are
not relevant. These methods may block waiting for more input.
When a scanner throws an InputMismatchException
, the scanner
will not pass the token that caused the exception, so that it may be
retrieved or skipped via some other method.
Depending upon the type of delimiting pattern, empty tokens may be
returned. For example, the pattern "\\s+"
will return no empty
tokens since it matches multiple instances of the delimiter. The delimiting
pattern "\\s"
could return empty tokens since it only passes one
space at a time.
A scanner can read text from any object which implements the Readable
interface. If an invocation of the underlying
readable's read()
method throws an IOException
then the scanner assumes that the end of the input
has been reached. The most recent IOException
thrown by the
underlying readable can be retrieved via the ioException()
method.
When a Scanner
is closed, it will close its input source
if the source implements the Closeable
interface.
A Scanner
is not safe for multithreaded use without
external synchronization.
Unless otherwise mentioned, passing a null
parameter into
any method of a Scanner
will cause a
NullPointerException
to be thrown.
A scanner will default to interpreting numbers as decimal unless a
different radix has been set by using the useRadix(int)
method. The
reset()
method will reset the value of the scanner's radix to
10
regardless of whether it was previously changed.
An instance of this class is capable of scanning numbers in the standard
formats as well as in the formats of the scanner's locale. A scanner's
initial locale is the value returned by the Locale.getDefault(Locale.Category.FORMAT)
method; it may be changed via the useLocale()
method. The reset()
method will reset the value of the
scanner's locale to the initial locale regardless of whether it was
previously changed.
The localized formats are defined in terms of the following parameters,
which for a particular locale are taken from that locale's DecimalFormat
object, df
, and its and
DecimalFormatSymbols
object,
dfs
.
- LocalGroupSeparator
- The character used to separate thousands groups, i.e.,
dfs.
getGroupingSeparator()
- LocalDecimalSeparator
- The character used for the decimal point, i.e.,
dfs.
getDecimalSeparator()
- LocalPositivePrefix
- The string that appears before a positive number (may be empty), i.e.,
df.
getPositivePrefix()
- LocalPositiveSuffix
- The string that appears after a positive number (may be empty), i.e.,
df.
getPositiveSuffix()
- LocalNegativePrefix
- The string that appears before a negative number (may be empty), i.e.,
df.
getNegativePrefix()
- LocalNegativeSuffix
- The string that appears after a negative number (may be empty), i.e.,
df.
getNegativeSuffix()
- LocalNaN
- The string that represents not-a-number for floating-point values, i.e.,
dfs.
getNaN()
- LocalInfinity
- The string that represents infinity for floating-point values, i.e.,
dfs.
getInfinity()
The strings that can be parsed as numbers by an instance of this class are specified in terms of the following regular-expression grammar, where Rmax is the highest digit in the radix being used (for example, Rmax is 9 in base 10).
Character.isDigit
(c)
returns true
[1-
Rmax] |
NonASCIIDigit
[0-
Rmax] |
NonASCIIDigit
(
Non0Digit
Digit?
Digit?
(
LocalGroupSeparator
Digit
Digit
Digit )+ )
( (
Digit+ )
|
GroupedNumeral )
( [-+]? (
Numeral
) )
|
LocalPositivePrefix Numeral
LocalPositiveSuffix
|
LocalNegativePrefix Numeral
LocalNegativeSuffix
|
Numeral
LocalDecimalSeparator
Digit*
|
LocalDecimalSeparator
Digit+
( [eE] [+-]?
Digit+ )
( [-+]?
DecimalNumeral
Exponent? )
|
LocalPositivePrefix
DecimalNumeral
LocalPositiveSuffix
Exponent?
|
LocalNegativePrefix
DecimalNumeral
LocalNegativeSuffix
Exponent?
[-+]? 0[xX][0-9a-fA-F]*\.[0-9a-fA-F]+
([pP][-+]?[0-9]+)?
NaN
|
LocalNan
| Infinity
|
LocalInfinity
( [-+]?
NonNumber )
|
LocalPositivePrefix
NonNumber
LocalPositiveSuffix
|
LocalNegativePrefix
NonNumber
LocalNegativeSuffix
|
HexFloat
|
SignedNonNumber
Whitespace is not significant in the above regular expressions.