There are two things I need help with but I'm having a hard time figuring out. They are listed below - any assistance is greatly appreciated.
1) I need to add a method that prompts the user to enter an int (1-3) to change the volume (default set to 2). I'm really having trouble figuring out how to make this work.
2) I need to add a similar method that prompts the user to enter an int (1 or 2) to plug the head phones in.
Here's my code; one is the test class:
//Open Package
package headphone_wk6;
//Import scanner since this will require user input
import java.util.Scanner;
// Creat class for headphones
public class HeadPhone_WK6 {
//Call scanner
Scanner stdin = new Scanner(System.in);
//Initialize input variable
int Input;
//Declare constant Variables
public static final int LOW = 1;
public static final int MEDIUM = 2;
public static final int HIGH = 3;
//Declare Private variables
private int volume;
private boolean pluggedIn;
private String manufacturer;
private String headPhoneColor;
//Declare Strings
String pluggedInStat;
String volumeNow;
// Constructor for class
public HeadPhone_WK6(int volume, boolean pluggedIn, String manufacturer, String headPhoneColor) {
this.volume = volume;
this.pluggedIn = pluggedIn;
this.manufacturer = manufacturer;
this.headPhoneColor = headPhoneColor;
}
// Default Constructor for default settings
public HeadPhone_WK6() {
volume = MEDIUM;
pluggedIn = false;
manufacturer = "";
headPhoneColor = "";
}
// setVolume
public void setVolume(int volume) {
this.volume = volume;
}
// getVolume
public int getVolume() {
if (volume == 1) {
volumeNow = "LOW";
}
else if (volume == 2) {
volumeNow = "MEDIUM";
}
else {
volumeNow = "HIGH";
}
return volume;
}
// setPluggedIn
public void setPluggedIn(boolean pluggedIn) {
this.pluggedIn = pluggedIn;
}
// getPluggedIn
public boolean getPluggedIn() {
if(pluggedIn == true) {
pluggedInStat = "Plugged In";
}
else {
pluggedInStat = "Not Plugged In";
}
return pluggedIn;
}
// setManufacturer
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
// getManufacturer
public String getManufacturer() {
return manufacturer;
}
// setHeadPhoneColor
public void setHeadPhoneColor(String headPhoneColor) {
this.headPhoneColor = headPhoneColor;
}
// getHeadPhoneColor
public String getHeadPhoneColor() {
return headPhoneColor;
}
// method to create string
public String toString() {
boolean phonesPluggedIn = this.getPluggedIn();
String phoneManufacturer = this.getManufacturer();
String phoneColor = this.getHeadPhoneColor();
String currentVolume = this.volumeNow;
//Build String for characteristics of phones
StringBuilder characteristics = new StringBuilder();
characteristics.append(String.format("\nThe Head Phone Manufacturer "
+ "is: %s", phoneManufacturer));
characteristics.append(String.format("\nThe Color of the Head Phone Set "
+ "is: %s", phoneColor));
characteristics.append(String.format("\nThe Head Phones are Currently: "
+ " %s", phonesPluggedIn));
characteristics.append(String.format("\nThe Head Phone Volume is "
+ "Currently Set on: %s", currentVolume));
//return string for characteristics
return characteristics.toString();
}
}
package headphone_wk6;
//Import scanner since this will require user input
import java.util.Scanner;
//Test class for head phone
public class HeadPhone_WK6_Test {
//Command line arguments
public static void main(String[] args) {
//Initialize input variable
int Input;
//Call scanner
Scanner stdin = new Scanner(System.in);
HeadPhone_WK6 bestPair = new HeadPhone_WK6(2, false, "SONY", "BLUE");
HeadPhone_WK6 worstPair = new HeadPhone_WK6(2, false, "BOSE", "BLACK");
HeadPhone_WK6 decentPair = new HeadPhone_WK6(2, false, "RCA", "ORANGE");
int bestPairVolume = bestPair.getVolume();
boolean bestPairPluggedIn = bestPair.getPluggedIn();
String bestPairManufacturer = bestPair.getManufacturer();
String bestPairHeadPhoneColor = bestPair.getHeadPhoneColor();
String bestPairVolumeNow = bestPair.volumeNow;
String bestPairPluggedInStat = bestPair.pluggedInStat;
int worstPairVolume = worstPair.getVolume();
boolean worstPairPluggedIn = worstPair.getPluggedIn();
String worstPairManufacturer = worstPair.getManufacturer();
String worstPairHeadPhoneColor = worstPair.getHeadPhoneColor();
String worstPairVolumeNow = worstPair.volumeNow;
String worstPairPluggedInStat = worstPair.pluggedInStat;
int decentPairVolume = decentPair.getVolume();
boolean decentPairPluggedIn = decentPair.getPluggedIn();
String decentPairManufacturer = decentPair.getManufacturer();
String decentPairHeadPhoneColor = decentPair.getHeadPhoneColor();
String decentPairVolumeNow = decentPair.volumeNow;
String decentPairPluggedInStat = decentPair.pluggedInStat;
//Introduce HeadPhone helper
System.out.print("Hi there! Let's have you try a pair of head phones "
+ "on and we'll see what you think of them! \nStart by choosing a "
+ "random pair of head phones. To do this, enter 1, 2, or 3: ");
//Get user input for random pair of headphones
Input = stdin.nextInt();
//Loop for random headphone selection
if (Input == 1){
//echo user input
System.out.println("You have chosen the best pair of "
+ "headphones! Here is a list of the characteristics: ");
System.out.println(bestPair.toString());
//End if
}
else if (Input == 2){
System.out.println("You have chosen the worst pair of "
+ "headphones. Here is a list of the characteristics: ");
System.out.println(worstPair.toString());
//End If
}
else if(Input == 3){
System.out.println("You have chosen a decent pair of "
+ "headphones. Here is a list of the characteristics:");
System.out.println(decentPair.toString());
//End If
}
else{
System.out.println("You have expressed that you want to see "
+ "the default pair of headphones. They are the "
+ "decent pair! Here's a list of the characteristics:");
System.out.println(decentPair.toString());
}
}
}
Maybe try something like this, first get input via scanner, then create HeadPhone objects:
//Initialize input variable
int Input;
//Call scanner
Scanner stdin = new Scanner(System.in);
//Introduce HeadPhone helper
System.out.print("Hi there! Let's have you try a pair of head phones "
+ "on and we'll see what you think of them! \nStart by choosing a "
+ "random pair of head phones. To do this, enter 1, 2, or 3: ");
//Get user input for random pair of headphones
Input = stdin.nextInt();
System.out.println("Now give me value of plug in 1 or 2");
int plugInState = stdin.nextInt();
boolean pluggedIn=true;
if(plugInState==1) pluggedIn = false;
if(plugInState==2) pluggedIn = true;
System.out.println("Now give me value volume (1/2/3");
int volumeState = stdin.nextInt();
HeadPhone_WK6 bestPair = new HeadPhone_WK6(volumeState, pluggedIn, "SONY", "BLUE");
HeadPhone_WK6 worstPair = new HeadPhone_WK6(volumeState, pluggedIn, "BOSE", "BLACK");
HeadPhone_WK6 decentPair = new HeadPhone_WK6(volumeState, pluggedIn, "RCA", "ORANGE");
You can put if clause in the end, based on your input, you can create one object that you need. If you need separate methods, do this in main():
HeadPhone_WK6 hp = new HeadPhone_WK6();
//Initialize input variable
int Input;
//Call scanner
Scanner stdin = new Scanner(System.in);
//Introduce HeadPhone helper
System.out.print("Hi there! Let's have you try a pair of head phones "
+ "on and we'll see what you think of them! \nStart by choosing a "
+ "random pair of head phones. To do this, enter 1, 2, or 3: ");
//Get user input for random pair of headphones
Input = stdin.nextInt();
System.out.println("Now give me value of plug in 1 or 2");
int plugInState = stdin.nextInt();
hp.setPluggedIn(plugInState);
System.out.println("Now give me value volume (1/2/3");
int volumeState = stdin.nextInt();
hp.setVolume(volumeState);
HeadPhone_WK6 bestPair = new HeadPhone_WK6(hp.getVolume(), hp.getPluggedIn(), "SONY", "BLUE");
HeadPhone_WK6 worstPair = new HeadPhone_WK6(hp.getVolume(), hp.getPluggedIn(), "BOSE", "BLACK");
HeadPhone_WK6 decentPair = new HeadPhone_WK6(hp.getVolume(), hp.getPluggedIn(), "RCA", "ORANGE");
Where
setPluggedIn(int pluggedInState) {
if(plugInState==1) pluggedIn = false;
else if(plugInState==2) pluggedIn = true;
else {
pluggedIn = false;
}
}
Related
I am a beginner in Java, and I've been creating a practicing project for a game. For this purpose, I've already put some features in this project, and I separate the entire project into three files: Nimsys, NimPlayer, NimGame.
I've created these features.
addplayer into playerList in the NimPlayer.
removeplayer
editplayer
Now, I want two of the players to join the game, and do the following:
Score record
The times the player has played.
What I did was trying to store the user data (addplayer) from the prompt input, and brought the game to be played (last part of the incomplete code).
import java.util.Scanner;
public class Nimsys {
public static String[] splitName(String inName) {
String[] splittedLine = inName.split(",");
String[] name = null;
if (splittedLine.length==3) {
String userName = splittedLine[0].trim();
String familyName = splittedLine[1].trim();
String givenName = splittedLine[2].trim();
name = new String[3];
name[0] = userName;
name[1] = familyName;
name[2] = givenName;
}
return name;
}
public static String [] splitData(String dataIn) {
String[] splittedLine = dataIn.split(",");
String[] data = null;
if (splittedLine.length==4) {
String initialStone = splittedLine[0];
String stoneRemoval = splittedLine[1];
String player1 = splittedLine[2].trim();
String player2 = splittedLine[3].trim();
data = new String[4];
data[0] = initialStone;
data[1] = stoneRemoval;
data[2] = player1;
data[3] = player2;
}
return data;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) {
System.out.print('$');
String commandin = in.next();
if (commandin.equals("addplayer")) {
String inName = in.nextLine();
String[] name = splitName(inName);
//Make sure the vadality of in name
if (name!=null && name.length==3) {
for (int i = 0; i < NimPlayer.getId(); i ++) {
String userCheck = NimPlayer.getPlayer()[i].getUserName();
if (userCheck.contains(name[0])) {
System.out.println("The player already exist");//Test if player has been created
}
}
NimPlayer.createPlayer(name[0], name[1], name[2]);
System.out.println("The player has been created.");
} else {
System.out.println("Not Valid! Please enter again!");
}
}
if (commandin.equals("removeplayer")) {
//cannot loop through the entire null array, would be NullPointerException
String removeUserName = in.nextLine().trim();
/*System.out.println("Are you sure you want to remove all players? (y/n) \n");
//System.out.print('$');
commandin = in.next();
if (commandin.equals("y")) {
for (int i = 0; i < NimPlayer.getId(); i++) {
NimPlayer.getPlayer()[i] = null;
System.out.println("Remove all the players");
}
} else {
System.out.print('$');
}*/
//commandin = in.next();
for (int i = 0; i < NimPlayer.getId(); i++) {
String userName = NimPlayer.getPlayer()[i].getUserName().trim();
if (removeUserName != null && userName.equals(removeUserName)) {
NimPlayer.getPlayer()[i] = null;
System.out.println("Remove successfully!");// A test to see if the code runs
} else {
System.out.println("The player does not exist");
}
}
}
if (commandin.equals("editplayer")) {
String inName = in.nextLine();
String[] splittedLine = inName.split(",");
if (splittedLine!=null && splittedLine.length==3) {
String userName = splittedLine[0].trim();
String familyName = splittedLine[1].trim();
String givenName = splittedLine[2].trim();
//System.out.println(userName+","+familyName+","+givenName);//Test if in name in the if loop
for (int i = 0; i < NimPlayer.getId(); i++) {
String userCheck = NimPlayer.getPlayer()[i].getUserName().trim();
if (userName != null && userCheck.equals(userName)) {
NimPlayer.getPlayer()[i].setFamilyName(familyName);
NimPlayer.getPlayer()[i].setGivenName(givenName);
System.out.println("Edit successfully");
} else {
System.out.println("The player does not exist.");
}
}
} else {
System.out.println("Invalid in! Please enter again.");
}
}
if (commandin.equals("displayplayer")) {
for (int i = 0; i < NimPlayer.getId(); i++) {
String userName = NimPlayer.getPlayer()[i].getUserName();
String familyName = NimPlayer.getPlayer()[i].getfamilyName();
String givenName = NimPlayer.getPlayer()[i].getGivenName();
System.out.println(userName+","+familyName+""+givenName);
}
}
if (commandin.equals("startgame")) {
String dataIn = in.nextLine();
String [] data = splitData(dataIn);
//Check if player in the array
if (data.length==4 && data !=null) {
for (int i = 0; i < NimPlayer.getId(); i++) {
for (int j = i + 1; j < NimPlayer.getId(); j++) {
String player1 = NimPlayer.getPlayer()[i].getUserName();
String player2 = NimPlayer.getPlayer()[j].getUserName();
if (player1==null || player2==null) {
System.out.println("One of the players does not exist. Please enter again");
} else {
System.out.println("Data built successfully.Game starts!");
break;
}
}
}
dataIn = in.nextLine();
}
int dataStone = Integer.parseInt(data[0]);
int dataRemoval = Integer.parseInt(data[1]);
}
}}
//username, given name, family name, number of game played, number of games won
public class NimPlayer {
private String userName;
private String familyName;
private String givenName;
static NimPlayer[] playerList = new NimPlayer[10]; // set an array here
static int id;
//define NimPlayer data type
public NimPlayer(String userName,String surName, String givenName) {
this.userName = userName;
this.familyName = surName;
this.givenName = givenName;
}
// create new data using NimPlayer data type
public static void createPlayer(String userName, String familyName, String givenName) {
if (id<10) {
playerList[id++] = new NimPlayer(userName, familyName, givenName);
} else {
System.out.println("Cannot add more players.");
}
}
public static int getId() {
return id;
}
public static NimPlayer [] getPlayer() {
return playerList;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getUserName() {
return userName;
}
public String getfamilyName() {
return familyName;
}
public String getGivenName() {
return givenName;
}
}
Above are my Nimsys and NimPlayers class. So far, I have a question:
Is it wrong to manipulate the players in the Nimplayer?
Or it is better to create an object in Nimsys if I want to store the record and the times game played?
public class NimGame {
int stoneBalance;
int stars;
public int initializeStone(int startStones) {
stoneBalance = startStones;
return stoneBalance;
}
public void removeStones(int stonesTaken) {
int updatedBalance = stoneBalance - stonesTaken;
stoneBalance = updatedBalance;
}
public void printStar(int star) {
stars = star;
stars = stoneBalance;
for (int stars = 1; stars <= star; stars++) {
System.out.print(" *");
}
System.out.println();
}
Scanner in = new Scanner(System.in);
String playOrNot;
do {
System.out.println("Initial stone count: "+datastone);
System.out.println("Maximum stone removal: "+dataRemoval);
System.out.println("Player 1: "+player1.getUserName());
System.out.println("Player 2: "+player2.getUserName());
// while stoneBalance > 0, two players keep playing the game
while (stoneBalance > 0) {
System.out.print(initialStone + " stones left:");
printStar(initialStone);
// player1's turn and remove the stones; decision of winning
System.out.println(player1 + "'s turn - remove how many?\n");
int takeStone = in.nextInt();
while (takeStone > dataRemoval || takeStone <= 0) {
System.out.println(
"Invalid, you need to remove stones under upper "+
"bound limit or above 0. \n Please enter again.");
takeStone = in.nextInt();
}
removeStones(takeStone); //remove the stone
if (stoneBalance > 0) {
//show the remaining stones
System.out.print(stoneBalance + " stones left:");
printStar(stoneBalance);
} else if (stoneBalance <= 0) {
System.out.println("Game Over\n" + player2 + " wins!\n");
break;
}
// player2's turn and remove the stones; decision of winning
System.out.println(player2 + "'s turn - remove how many?\n");
takeStone = in.nextInt();
while (takeStone > dataRemoval || takeStone <= 0) {
System.out.println(
"Invalid, you need to remove stones under upper " +
"bound limit or above 0. \n Please enter again.");
takeStone = in.nextInt();
}
removeStones(takeStone);
if (stoneBalance > 0) {
System.out.print(stoneBalance + " stones left:");
printStar(stoneBalance);
} else if (stoneBalance <= 0) {
System.out.println("Game Over\n" + player1 + " wins!\n");
break;
}
}
// ask players to play again
in.nextLine();
System.out.println("Do you want to play again (Y/N):");
playOrNot = in.nextLine();
} while (playOrNot.equals("Y"));
}
And this above is my NimGame class. It's the process of the classical Nim game. What should I do to introduce the player? What I did in Nimsys is only to check if players are inside the playerList.
Thanks for taking the time to review my code. Any help is highly appreciated!
On a side note (because it won't affect the execution of the program), the name of an identifier should be self-explanatory e.g. your getPlayer method should be named as getPlayerList as it is returning the playerList, not a single player.
Your logic for startgame should be as follows:
if (commandin.equals("startgame")) {
String dataIn = null, player1 = null, player2 = null;
do {
dataIn = in.nextLine();
String [] data = splitData(dataIn);
//Check if player in the array
if (data !=null && data.length==4) {
NimPlayer[] players = NimPlayer.getPlayerList();
for (int i = 0; i < players.length; i++) {
if(players[i].getUserName().equals(data[2])) {// Checking player1
player1 = players[i].getUserName();
break;
}
}
for (int i = 0; i < players.length; i++) {
if(players[i].getUserName().equals(data[3])) {// Checking player2
player2 = players[i].getUserName();
break;
}
}
}
} while(player1 == null || player2 == null)
//...
}
You can put the repeated code in a function to make your program modular e.g.
String findPlayerByName(String name){
String player = null;
NimPlayer[] players = NimPlayer.getPlayerList();
for (int i = 0; i < players.length; i++) {
if(players[i].getUserName().equals(name)) {
player = players[i].getUserName();
break;
}
}
return player;
}
Then, the logic for startgame will reduce to:
if (commandin.equals("startgame")) {
String dataIn = null, player1 = null, player2 = null;
do {
dataIn = in.nextLine();
String [] data = splitData(dataIn);
//Check if player in the array
if (data !=null && data.length==4) {
player1 = findPlayerByName(data[2]);
player2 = findPlayerByName(data[3]);
}
} while(player1 == null || player2 == null)
//...
}
Another thing I would like you to understand is the problem with the following line:
if (data.length==4 && data !=null)
It should be
if (data !=null && data.length==4)
This way, if data is null, the condition, data.length==4 will not be checked because && operator allows to proceed further only if the condition on its left side evaluates to true.
The problem with your line is that if data is null, you will get the NullPointerException because you will be checking .length on a null reference.
Now, I want two of the players to join the game, and do the following:
Score record
The times the player has played.
Currently, you have userName, familyName, and givenName attributes in NimPlayer class. You need to create two more attributes, private int score and private int numbersOfGamesPlayed with their public getters and setters. You need to use these attributes to store the value of score and the numbers of time a player has played the game.
So I have seen alot of similar questions to this one but can't seem to find the answer so sorry if this is a duplicate. So I am creating a java program for black jack that I would like to have a system in place to save the chips the user has. I can get it to work but whenever I try to get it to save it just seems to overwrite what was already previously there.
Example
User enters there name: Bob
The system automatically knows there chips so when they press the button to save game it writes there name and chips like so...
Bob
200 (or however many chips they have)
The problem comes up when a new user enters there name and saves so say sally was saving instead of going
Bob
200
Sally
300
It does
Sally
300
And completly deletes bob
public void newSave(String user){
this.user = user;
user = user;
String Chip = Integer.toString(chips);
try{
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(user);
fileWriter.write("\n");
fileWriter.write(Chip);
fileWriter.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
Here is my code that I have that is where my issue lies.
Here is the whole code of the program method.
import java.util.*;
import java.io.*;
class BlackJackPlayer{
//Keep the data secure by using private
private String hand;
private String user;
private int betNum;
private int sum;
private int numAces;
private int chips = 100;
private String bet;
private static Random gen = new Random();
private String result = "";
public String Win = "Win", Lose = "Lose", Split = "Split";
private final int ACE = 1;
private final int JACK = 11;
private final int QUEEN = 12;
private final int KING = 13;
//Scanner for fileIn
Scanner fileIn;
//File For Saves!
File file = new File("Saves.txt");
//Array For Saves!
private ArrayList<String> User = new ArrayList<>();
private ArrayList<Integer> Chips = new ArrayList<>();
//constructor
public BlackJackPlayer(){
hand = "";
sum = 0;
numAces = 0;
//Create a file if save file does not exist//
try{
if (file.createNewFile()){
System.out.println("Save File Created!");
}
else{
//Say Nothing//
}
}//End Try
catch(Exception e){
System.out.println(e.getMessage());
}
//End File Create//
//Read File //
try{
fileIn = new Scanner(new FileReader(file, true));
while(fileIn.hasNext()){
User.add( fileIn.nextLine().trim() );
Chips.add( fileIn.nextInt() );
}//End While
fileIn.close();
}//End Try
catch(Exception e){
System.out.println(e.getMessage());
}//End Catch
//End Read File//
}//End public
//checkSaveStatus//
//See if save exists already in text than send to proper scenario//
public boolean checkSaveStatus(String user){
for(String u: User){
if (user == u){
return true;
}//end if
}//end for
return false;
}//end checkSaveStatus
//End checkSaveStatus//
//overWriteSave if save already exists//
public void overWriteSave(String user){
}//end overWriteSave
//End overWriteSave//
//newSave scnenario if save dosent exist//
public void newSave(String user){
this.user = user;
user = user;
String Chip = Integer.toString(chips);
try{
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(user);
fileWriter.write("\n");
fileWriter.write(Chip);
fileWriter.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
public boolean checkBet(String bet, int chips){
this.bet = bet;
int betNum = Integer.parseInt(bet);
if(betNum <= chips){
return true;
}
return false;
}
public String setBet(String bet){
this.bet = bet;
betNum = Integer.parseInt(bet);
return "You Bet: " + betNum;
}
public String updateChips(){
chips -= betNum;
return "You have: " + chips + " chips";
}
//Getter for hand variable
public String getHand(){
return hand;
}
public String setHand(){
hand = " ";
return hand;
}
//Getter for sum variable
public int getSum(){
return sum;
}
public void hit(){
//local variable
int currentCard = gen.nextInt(13) + 1;
if(currentCard > ACE && currentCard < JACK){
sum += currentCard;
hand += currentCard + " ";
}
else if(currentCard == ACE){
sum += 11;
numAces++;
hand += "A ";
}
else if(currentCard == QUEEN){
sum += 10;
hand += "Q ";
}
else if(currentCard == QUEEN){
sum += 10;
hand += "Q ";
}
else if(currentCard == KING){
sum += 10;
hand += "K ";
}//Ends Else If
//Is Ace 1 or 11
if(sum > 21 && numAces > 0){
numAces--;
sum -= 10;
}
}//ENDS HIT
public void stand(){
sum = sum;
return;
}//ends stand
public String getWin(BlackJackPlayer other) {
if(sum > 21){
result = Win;
}
else if(sum < other.getSum()){
result = Lose;
}
else if(sum == other.getSum()){
result = Split;
}
return result;
}
}//end class
Use following code.
FileWriter fileWriter = new FileWriter(file, true);
Here true signifies that you want to append data to existing file.
For more details : https://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter(java.io.File,%20boolean)
It seems that 20 regiments were in a continuous process of formation. The first had 1000 men, the second had 950, the third 900, and so on down to the twentieth regiment, which garrisoned only 50. During each week, 100 men were added to each regiment, and at week's end, the largest regiment was sent off to the front.This lasted for a total of 20 weeks.
For this program I have already managed to print out the original number of men for each regiment. But I am having difficult adding 100 men to each regiment.The adding men must be a method in the army class. I am getting the regiment objects using a .txt file. All this files contains is the names of regiments numbered 1-20.
I currently have no errors my only problem is that I do not know how to add men to my regiment. I have to use the addMen method in the army class which I currently have blank.
public class Regiment {
private String name; //name of regiment
private int regNumber; //regiment number
private int men; // regiment men
public Regiment(int regNumber, String name, int men) {
this.name = name;
this.regNumber = regNumber;
this.men = men;
}
public String getName() {
return name;
}
public int getregNumber() {
return regNumber;
}
public int getMen() {
return men;
}
public int addMen2(int RegNumber) {
int men = 1050 - (regNumber * 50);
return men;
}
}
ArmyDataList:
class ArmyDataList {
public ArrayList<Regiment> list;
public ArmyDataList() {
list = new ArrayList<Regiment>();
}
public void AddToList(Regiment current) {
list.add(current);
}
public void RemoveFromList(Regiment current) {
list.remove(current);
}
public Regiment getLargest() {
if (list.isEmpty()) {
return null;
}
Regiment Reg1 = list.get(0);
for (int i = 1; i < list.size(); i++) {
Regiment current = list.get(i); // get next regiment
// is current regiment > largest
if (current.getMen() > Reg1.getMen()) {
Reg1 = current;
}
}
return Reg1;
}
public void addMen() {
}
public String toString() {
String out
= String.format("%28s%12s%n", "Regiments", " Men")
+ String.format("%12s%n", "Number")
+ String.format("%12s%16s%14s%n", "=======", "===============",
"=========");
for (int i = 0; i < list.size(); i++) {
Regiment regim = list.get(i);
int regNumber = regim.getregNumber();
String name = regim.getName();
int men = regim.addMen2(regNumber);
out = out + String.format("%12s", regNumber)
+ String.format("%16s", name)
+ String.format("%10s", men)
+ "\n";
}
return out + "\n";
}
}
RegimentTest:
public class RegimentTest {
public static void main(String[] args) throws IOException
{
ArmyDataList army = new ArmyDataList();
Scanner fileScan = new Scanner(new File("regiments.txt"));
System.out.println("Report Summary:\n");
while (fileScan.hasNext()) {
String line = fileScan.nextLine();
System.out.println(line);
Scanner in = new Scanner(line) ;
int regNumber = in.nextInt();
String name = in.next();
int men = 0 ; //men is set to 0 only because I havent add the men yet
Regiment adder = new Regiment(regNumber, name, men );
army.AddToList(adder) ;
}
System.out.println(army.toString());
}
Add a setMen(int numberOfMen) method to your Regiment class. Then in your addMen() method, you can do something like this:
public void addMen(){
for(Regiment r : list){ //iterate through the list of regiments
r.setMen(r.getMen() + 100); //add 100 men to each regiment
}
}
The setMen method would look like this:
public void setMen(int numberOfMen){
men = numberOfMen;
}
There is another issue with your toString method, where the regiment's addMen2 method is called - right now you're just printing the number, not initializing the number of men. In the constructor for your Regiment class, replace the line
this.men = men;
with
this.men = addMen2(regNumber);
Then in your toString method, replace
int men = regim.addMen2(regNumber);
with
int men = regim.getMen();
Here is what your main should look like:
public static void main(String[] args) throws IOException{
ArmyDataList army = new ArmyDataList();
Scanner fileScan = new Scanner(new File("regiments.txt"));
System.out.println("Report Summary:\n");
while (fileScan.hasNext()) {
String line = fileScan.nextLine();
System.out.println(line);
Scanner in = new Scanner(line);
int regNumber = in.nextInt();
String name = in.next();
int men = 0 ; //men is set to 0 only because I havent add the men yet
Regiment adder = new Regiment(regNumber, name, men );
army.AddToList(adder);
}
System.out.println(army.toString()); //print out the initial # of men
for(int i = 0; i < 20; i++)
army.addMen();
System.out.println(army.toString()); //print the final # of men
}
in Regiment get rid of method addMen2, and replace it with
public void addMen(int men) {
this.men +=men;
}
then in your army you could have method
public void addMen(int men) {
for(Regiment regiment : list){
regiment.addMen(men);
}
}
that will be simplest solution to add 100 men to each regiment,
other thing is, your toString is bit nasty, regiment should know how meny soldiers it ghas, you shouldnt need additional method to calculate it (reason why i recommend you to trash addMen2 method)
to initiate your Regiment, use constructor. You want to have regiments in sizes 1000, 1950, 1900 etc, do it when you are creating them
while (fileScan.hasNext()) {
String line = fileScan.nextLine();
System.out.println(line);
Scanner in = new Scanner(line) ;
int regNumber = in.nextInt();
String name = in.next();
int men = 1050 - (regNumber * 50);
Regiment adder = new Regiment(regNumber, name, men );
army.AddToList(adder) ;
}
I'm trying to making a program that simulates the card game War.
class Project2
package proj2;
import java.util.Scanner;
public class Project2 {
public static void main( String[ ] args)
{
Scanner keybd = new Scanner( System.in );
// Get player names
System.out.println("Welcome to WAR!!");
System.out.print("Please enter player 1's name: ");
String p1Name = keybd.nextLine();
System.out.print("Please enter player 2's name: ");
String p2Name = keybd.nextLine();
// Get random number generator (RNG) seed and initialize the game
System.out.print ("Please enter the RNG seed for shuffling: ");
long rngSeed = keybd.nextLong();
Game war = new Game(p1Name, p2Name, rngSeed);
int turn = 1;
// While game is being played, print details and results of each turn
while (!war.gameComplete())
{
System.out.printf( "Turn %2d\n", turn);
System.out.println( "-----");
System.out.println( war.nextTurn());
++turn;
}
// All turns complete; print the game results
System.out.println("Game Over!!");
System.out.println(war.gameResult());
}
}
Class Game:
package proj2;
public class Game {
private Deck deck;
private Player player1;
private CardPile p1Deck;
private Player player2;
private CardPile p2Deck;
private int warCount;
private int turns;
public Game(String p1, String p2, long rngSeed)
{
this.deck = new Deck();
deck.Shuffle((int) rngSeed);
this.player1 = new Player(p1, 0, 0);
this.p1Deck = new CardPile(deck.Deal());
this.player2 = new Player(p2, 0, 0);
this.p2Deck = new CardPile(deck.Deal());
this.turns = 1;
this.warCount = 0;
}
public String nextTurn()
{
p1Card = p1Deck.drawCard();
(ERROR)---> String p1Turn = player1.getName() + " shows " + p1Card.cardString();
Card p2Card = p2Deck.drawCard();
String p2Turn = player2.getName() + " shows " + p2Card.cardString();
String winner = "";
if(p1Card.getValue() > p2Card.getValue())
{
Card[] wonCards = new Card[2];
wonCards[0] = p1Card;
wonCards[1] = p2Card;
p1Deck.addCard(wonCards, 2);
player1.setCardsWon(wonCards.length);
winner = player1.getName() + " wins 2 cards" ;
}
if(p2Card.getValue() > p1Card.getValue())
{
Card[] wonCards = new Card[2];
wonCards[0] = p2Card;
wonCards[1] = p1Card;
p1Deck.addCard(wonCards, 2);
player2.setCardsWon(wonCards.length);
winner = "/n" + player2.getName() + " wins 2 cards";
}
String warTurn = "";
if(p1Card.getValue() == p2Card.getValue())
{
this.warCount = warCount + 1;
warTurn = "WAR!!";
Card[] wonCards = new Card[8];
while(p1Card.getValue() != p2Card.getValue())
{
wonCards[0] = p1Deck.drawCard();
wonCards[2] = p1Deck.drawCard();
wonCards[4] = p1Deck.drawCard();
Card p1WarCard = p1Deck.drawCard();
wonCards[6] = p1WarCard;
wonCards[1] = p2Deck.drawCard();
wonCards[3] = p2Deck.drawCard();
wonCards[5] = p2Deck.drawCard();
Card p2WarCard = p2Deck.drawCard();
wonCards[7] = p2WarCard;
if(p1WarCard.getValue() > p2WarCard.getValue())
{
p1Deck.addCard(wonCards, wonCards.length);
player1.setCardsWon(wonCards.length);
}
if(p2WarCard.getValue() > p2WarCard.getValue())
{
p2Deck.addCard(wonCards, wonCards.length);
player2.setCardsWon(wonCards.length);
}
}
}
String turnResults = p1Turn + "/n" + p2Turn + "/n" + warTurn + winner;
return turnResults;
}
public boolean gameComplete()
{
boolean result = false;
if(turns == 20) {
result = true;
}
return result;
}
public String gameResult()
{
String p1Result = (player1.getName() + " won " + player1.getCardsWon() + "and"
+ player1.getWarsWon() + "war(s)" + "/n");
String p2Result = (player2.getName() + " won " + player2.getCardsWon() + "and"
+ player1.getWarsWon() + "war(s)" + "/n");
String winner = "";
if(player1.getCardsWon() > player2.getCardsWon())
{
winner = "Winner: " + player1.getName();
}
if(player2.getCardsWon() < player2.getCardsWon())
{
winner = "Winner: " + player2.getName();
}
if(player1.getCardsWon() == player2.getCardsWon())
{
winner = "Game is a draw";
}
String finalResult = ("Game Over!!" + "There were " + warCount
+ "war(s)" + p1Result + "/n" + p2Result + "/n" + winner);
return finalResult;
}
}
When I try to access the class Card, I get a null pointer exception error. I'm not sure what is producing the error.
public class Card {
private char rank;
private String suit;
private int value;
public Card(char rank, String suit, int value)
{
this.rank = rank;
this.suit = suit;
this.value = value;
}
public char getRank()
{
return rank;
}
public String getSuit()
{
return suit;
}
public int getValue()
{
return value;
}
public String cardString()
{
String card = (rank + " of " + suit);
return card;
}
}
I tried googling for solutions, and it tells me to initialize the object before referencing the object. I tried initializing, but it still produces the null pointer exception error.
The error I'm getting is this.
Exception in thread "main" java.lang.NullPointerException
at proj2.Game.nextTurn(Game.java:29)
at proj2.Project2.main(Project2.java:37)
The drawCard() method is from this class.
package proj2;
public class CardPile {
private Card[] playerDeck;
public CardPile(Card[] deck)
{
this.playerDeck = deck;
}
public Card drawCard()
{
Card topCard = playerDeck[0];
Card[] newPlayerDeck = new Card[playerDeck.length - 1];
int counter = 0;
for(int i = 1; i < playerDeck.length; i++)
{
newPlayerDeck[counter] = playerDeck[i];
counter++;
}
this.playerDeck = newPlayerDeck;
return topCard;
}
}
It returns a NULL Point Exception because you are not passing any parameters. Try passing parameters to your constructor.
e.g
Card p1Card = new Card(rank,suit,value);
Card p2Card = new Card(rank,suit,value);
Since p1Card null, then p1Deck.drawCard() returns null - which means playerDeck[0] is null, which means new CardPile(deck.Deal()); creates and empty deck, which means something is wrong in deck.Deal(). By "something is wrong" I mean that it probably creates and returns an array with null values, like: [null, null, null, null, null] (or it might be that the first value is the only one that's null).
I've had this problem throughout multiple programs, but I can't remember how I fixed it last time. In the second while loop in my body, the second sentinel value is never read in for some reason. I've been trying to fix it for a while now, thought I might see if anyone had any clue.
import java.text.DecimalFormat; // imports the decimal format
public class Car {
// Makes three instance variables.
private String make;
private int year;
private double price;
// Makes the an object that formats doubles.
public static DecimalFormat twoDecPl = new DecimalFormat("$0.00");
// Constructor that assigns the instance variables
// to the values that the user made.
public Car(String carMake,int carYear, double carPrice)
{
make = carMake;
year = carYear;
price = carPrice;
}
// Retrieves variable make.
public String getMake()
{
return make;
}
// Retrieves variable year.
public int getYear()
{
return year;
}
// Retrieves variable price.
public double getPrice()
{
return price;
}
// Checks if two objects are equal.
public boolean equals(Car c1, Car c2)
{
boolean b = false;
if(c1.getMake().equals(c2.getMake()) && c1.getPrice() == c2.getPrice() &&
c1.getYear() == c2.getYear())
{
b = true;
return b;
}
else
{
return b;
}
}
// Turns the object into a readable string.
public String toString()
{
return "Description of car:" +
"\n Make : " + make +
"\n Year : " + year +
"\n Price: " + twoDecPl.format(price);
}
}
import java.util.Scanner; // imports a scanner
public class CarSearch {
public static void main(String[] args)
{
// initializes all variables
Scanner scan = new Scanner(System.in);
final int SIZE_ARR = 30;
Car[] carArr = new Car[SIZE_ARR];
final String SENT = "EndDatabase";
String carMake = "";
int carYear = 0;
double carPrice = 0;
int count = 0;
int pos = 0;
final String SECSENT = "EndSearchKeys";
final boolean DEBUG_SW = true;
// Loop that goes through the first list of values.
// It then stores the values in an array, then uses the
// values to make an object.
while(scan.hasNext())
{
if(scan.hasNext())
{
carMake = scan.next();
}
else
{
System.out.println("ERROR - not a String");
System.exit(0);
}
if(carMake.equals(SENT))
{
break;
}
if(scan.hasNextInt())
{
carYear = scan.nextInt();
}
else
{
System.out.println("ERROR - not an int" + count);
System.exit(0);
}
if(scan.hasNextDouble())
{
carPrice = scan.nextDouble();
}
else
{
System.out.println("ERROR - not a double");
System.exit(0);
}
Car car1 = new Car(carMake, carYear, carPrice);
carArr[count] = car1;
count++;
}
// Calls the method debugSwitch to show the debug information.
debugSwitch(carArr, DEBUG_SW, count);
// Calls the method printData to print the database.
printData(carArr, count);
// Loops through the second group of values and stores them in key.
// Then, it searches for a match in the database.
**while(scan.hasNext())**
{
if(scan.hasNext())
{
carMake = scan.next();
}
else
{
System.out.println("ERROR - not a String");
System.exit(0);
}
if(carMake.equals(SECSENT))
{
break;
}
if(scan.hasNextInt())
{
carYear = scan.nextInt();
}
else
{
System.out.println("ERROR - not an int" + count);
System.exit(0);
}
if(scan.hasNextDouble())
{
carPrice = scan.nextDouble();
}
else
{
System.out.println("ERROR - not a double");
System.exit(0);
}
Car key = new Car(carMake, carYear, carPrice);
// Stores the output of seqSearch in pos.
// If the debug switch is on, then it prints these statements.
if(DEBUG_SW == true)
{
System.out.println("Search, make = " + key.getMake());
System.out.println("Search, year = " + key.getYear());
System.out.println("Search, price = " + key.getPrice());
}
System.out.println("key =");
System.out.println(key);
pos = seqSearch(carArr, count, key);
if(pos != -1)
{
System.out.println("This vehicle was found at index = " + pos);
}
else
{
System.out.println("This vehicle was not found in the database.");
}
}
}
// This method prints the database of cars.
private static void printData(Car[] carArr, int count)
{
for(int i = 0; i < count; i++)
{
System.out.println("Description of car:");
System.out.println(carArr[i]);
}
}
// Searches for a match in the database.
private static int seqSearch(Car[] carArr, int count, Car key)
{
for(int i = 0; i < count; i++)
{
boolean b = key.equals(key, carArr[i]);
if(b == true)
{
return i;
}
}
return -1;
}
// Prints debug statements if DEBUG_SW is set to true.
public static void debugSwitch(Car[] carArr, boolean DEBUG_SW, int count)
{
if(DEBUG_SW == true)
{
for(int i = 0; i < count; i++)
{
System.out.println("DB make = " + carArr[i].getMake());
System.out.println("DB year = " + carArr[i].getYear());
System.out.println("DB price = " + carArr[i].getPrice());
}
}
}
}
I think this is your problem, but I might be wrong:
Inside your while loop, you have these calls:
next()
nextInt()
nextDouble()
The problem is that the last call (nextDouble), will not eat the newline. So to fix this issue, you should add an extra nextLine() call at the end of the two loops.
What happens is that the next time you call next(), it will return the newline, instead of the CarMake-thing.