Creating an array of arrays in Java - java

Say I have a Player class such as:
public class Player {
String name;
int chips;
int betVal;
}
Is the following code correct for creating the array of the players?
public static void main(String[] args) {
int playerCount;
int startingChip;
out.print("How many players? ");
playerCount = myScanner.nextInt();
Player[] aPlayer = new Player[playerCount + 1];
for (int i = 0; i < playerCount + 1; i++){
aPlayer[i] = new Player();
}
out.print("Enter starting chip amount: ");
startingChip = myScanner.nextInt();
}
If so, how would I assign the name, chip amount and the betVal to each player? How would I access and alter them later on in the code?
EDIT: Will it be easier leaving the Player as an object or an array (name,chips,betVal) for accessing it later on?

First off, your variables need to be private (there's a section of programmers who prefer public variables but most prefer private).
You could set the values of the Player object either through an overloaded constructor or through the setters.
public class Player {
private String name;
private int chips;
private int betVal;
public Player(){
//default constructor to initialize without any parameters
}
public Player(String name, int chips, int betVal){
this.name=name;
this.chips=chips;
this.betVal=betVal;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getChips() {
return chips;
}
public void setChips(int chips) {
this.chips = chips;
}
public int getBetVal() {
return betVal;
}
public void setBetVal(int betVal) {
this.betVal = betVal;
}
}
In which case, your initialization could be either
aPlayer[i] = new Player("Jason", 5,1000);
or using the setters as in
for (int i = 0; i < playerCount + 1; i++){
aPlayer[i] = new Player();
}
aPlayer[i].setName("Jason");
aPlayer[i].setChips(5);
aPlayer[i].setBetVal(1000);
Considering your sample program, I guess option 2 plays well.

You can access each player by telling the array which one you want to access.
`aPlayer[0].name = "JAG";`
would work for example.

Why not ask all the user's inputs before creating anything ? For exemple :
public static void main(String[] args) {
int playerCount;
int startingChip;
out.print("How many players? ");
playerCount = myScanner.nextInt();
out.print("Enter starting chip amount: ");
startingChip = myScanner.nextInt();
Player[] aPlayer = new Player[playerCount];
for (int i = 0; i < playerCount; i++){
aPlayer[i] = new Player();
aPlayer[i].setChips(startingChip);
}
}
You should also use a List. And finally, if you want to ask for the name of each player, do it directly in the loop :
for (int i = 0; i < playerCount; i++){
aPlayer[i] = new Player();
aPlayer[i].setChips(startingChip);
out.print("What's the player " + i + " name? ");
aPlayer[i].setName(myScanner.next());
}

try something like this...
ask for individual players info in the loop itself.
System.out.println("How many players? ");
Scanner myScanner = new Scanner(System.in);;
playerCount = myScanner.nextInt();
Player[] aPlayer = new Player[playerCount];
for (int i = 0; i < playerCount; i++){
aPlayer[i] = new Player();
System.out.println("Enter Name for Player " + i+1);
String name = myScanner.next();
System.out.println("Enter chips for Player " + i+1);
int chips = myScanner.nextInt();
System.out.println("Enter betVal for Player " + i+1);
int betVal = myScanner.nextInt();
aPlayer[i].name = name;
aPlayer[i].chips = chips;
aPlayer[i].betVal = betVal;
}
Also make the instance variables of Player class private, and access them using getters and setters.

Related

Java - Iterating around for-loop to create players for game and setting their name

I haven't been programming for long and I have spent hours trying to get this method to do what I need so help would be very much appreciated at this point. I am creating a board game which prompts players for the number of players playing, after which they are prompted for their names in turn, and those new players will be created and their names set/stored. I also want to make sure that two players cannot have the same name.
Here is part of my player class:
public class Player {
private String name;
private int currentPosition;
private int distance;
private boolean quit;
public Player() {
}
public Player(String name, int currentPosition, int distance, boolean quit) {
this.name = name;
this.currentPosition = currentPosition;
this.distance = distance;
this.quit = quit;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I have a setNumberOfPlayers method which is working fine and getting the correct number of players when getNumberOfPlayers() is called.
public class SetUpGame {
Scanner sc = new Scanner(System.in);
public void addPlayers() {
String playerName;
ArrayList<Player> players = new ArrayList<Player>();
System.out.println("What are the names of the " + this.numberOfPlayers + " players?\n");
for (int loop = 1; loop <= getNumberOfPlayers(); loop++) {
System.out.println("Player " + loop + " please enter your name");
boolean valid = false;
do {
playerName = sc.nextLine();
Player player = new Player();
for (Player play : players) {
if (players.isEmpty() || !play.getName().equalsIgnoreCase(playerName)) {
player.setName(playerName);
players.add(player);
System.out.println("success, your name is: " +playerName);
valid = true;
} else {
System.out.println("please enter another name");
valid = false;
}
}
} while (valid == false);
}
sc.close();
}
When the add players method is called from main, it gives this output:
What are the names of the 2 players?
Player 1 please enter your name
...and the user can input their name but the scanner never closes or loops around to ask the next player their name. I have messed around with the code so much that I've confused myself at this point. Can anyone help with this, and also how to validate/check that the players have been created and their names set? Thank you
Your inner for loop is iterating on players array, but it is empty.
Maybe try this instead:
do {
System.out.println("Please enter name:");
playerName = sc.nextLine();
if(playerName.length()!=0){
valid = true;
for(Player play : players)
if(play.getName().equalsIgnoreCase(playerName))
valid = false;
if(valid){
Player player = new Player();
player.setName(playerName);
players.add(player);
}
}
} while (!valid);
I think you might be having a hard time debugging because of how similar all your variable names are. ('players','player','play')
EDIT: updated to check if a duplicate
First, list of players is defined as a local variable in the method addPlayers, so when this method is done, all the players data are lost. So it is necessary to modify this method either to add the players to a field of SetupGame class or to return the list of players to the calling method. The latter way is a cleaner functional way of populating the player list.
Next, in order to efficiently detect duplicate names, it is recommended to create and use Set<String> playerNames.
And the last, if Scanner is open on System.in it must not be closed, because after that no user input can be entered.
That being said, the code of addPlayers may look as follows:
public List<Player> addPlayers() {
List<Player> players = new ArrayList<>();
Set<String> playerNames = new HashSet<>();
Scanner sc = new Scanner(System.in);
System.out.println("What are the names of the " + this.numberOfPlayers + " players?\n");
for (int loop = 1; loop <= this.numberOfPlayers; loop++) {
while (true) {
System.out.println("Player " + loop + " please enter your name");
String playerName = sc.nextLine();
if (playerNames.add(playerName)) {// Set.add returns true if name was added to it
Player p = new Player();
p.setName(playerName);
players.add(p);
break; // input new player
}
}
}
return players;
}
You missed some getters and setters in your Player class.
Player.java
public class Player {
private String name;
private int currentPosition;
private double distance;
private boolean quit;
public Player() {
// no-args constructor
}
public Player(String name, int currentPosition, double distance, boolean quit) {
this.name = name;
this.currentPosition = currentPosition;
this.distance = distance;
this.quit = quit;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCurrentPosition() {
return currentPosition;
}
public void setCurrentPosition(int currentPosition) {
this.currentPosition = currentPosition;
}
public double getDistance() {
return distance;
}
public void setDistance(double distance) {
this.distance = distance;
}
public boolean isQuit() {
return quit;
}
public void setQuit(boolean quit) {
this.quit = quit;
}
}
You can implement the SetUpGame class as follows.
No need to create the do-while loop.
SetUpGame.java
import java.util.ArrayList;
import java.util.Scanner;
public class SetUpGame {
Scanner sc = new Scanner(System.in);
ArrayList<Player> players = new ArrayList<Player>();
int numberOfPlayers;
public int getNumberOfPlayers() {
return numberOfPlayers;
}
public void setNumberOfPlayers(int numberOfPlayers) {
this.numberOfPlayers = numberOfPlayers;
}
public void addPlayers() {
System.out.print("Enter number of players: ");
numberOfPlayers = sc.nextInt();
System.out.println("What are the names of the " + numberOfPlayers + " players?");
for(int loop = 1; loop <= numberOfPlayers; loop++) {
Player player = new Player();
System.out.print("Enter name for player " + loop + ": ");
player.setName(sc.next());
System.out.print("Enter current position for player " + loop + ": ");
player.setCurrentPosition(sc.nextInt());
System.out.print("Enter distance for player " + loop + ": ");
player.setDistance(sc.nextDouble());
System.out.print("Enter validity for player " + loop + ": ");
player.setQuit(sc.nextBoolean());
players.add(player);
}
sc.close();
}
public void displayAllPlayers() {
System.out.println("Displaying all players...");
for(Player p : players) {
System.out.printf("%s %d %f %b", p.getName(), p.getCurrentPosition(), p.getDistance(), p.isQuit());
}
}
}
Finally you can test your SetUpGame class.
TestSetUpGame.java
public class TestSetUpGame {
public static void main(String[] args) {
SetUpGame game = new SetUpGame();
game.addPlayers();
game.displayAllPlayers();
}
}

Using a for loop to print out students and their grades from highest to lowest , using an object

So in this program I am asking the size of a class of students, taking in each student and the grade associated with them. myStudents[i] then holds each students name and their grade. The problem I am having now is with both of my selectionSort. I was supposed to arrange each students by grades (from highest to lowest. Which I think I did correctly in public static void selectionSort(student[] myStudents), but I am not sure how I a supposed to print that out using a for loop when I call selectionSort. Any advice to point me in the right direction would be greatly appreciated. Thank you!
import java.util.Scanner;
public class Final4{
public static void main(String[] args) {
Scanner myInput=new Scanner(System.in);
System.out.print("Enter the size of the class: ");
int num = myInput.nextInt();
int array[] = new int[num];
double score;
student[] myStudents = new student[num];
for (int i = 0 ; i < array.length; i++ ) {
System.out.print("Please enter a student name: ");
myInput.useDelimiter(System.getProperty("line.separator"));
String s;
s = myInput.next();
System.out.print("Please enter " + s +"'s score: ");
score = myInput.nextDouble();
myStudents[i] = new student(s, score);
}
}
selectionSort()
public static void selectionSort(student[] myStudents) {
for (int i = myStudents.length-1; i>0; i--){
int maxIndex = 0;
student max = myStudents[0];
for (int j=1; j<=i; j++)
if (myStudents[j].getScore() > (max.getScore())) {
maxIndex = i;
}
student temp = myStudents[i];
myStudents[i] = myStudents[maxIndex];
myStudents[maxIndex] = temp;
}
}
}
class student {
String name;
double score;
student(String name, double score) {
this.name = name;
this.score = score;
}
public double getScore() {
return score;
}
public String getName() {
return name;
}
}
I tend to get a little confused once I start incorporating gets and objects. Again, any advice is greatly appreciated.
so your problem was how to print your array of Student which is sorted by Selection Sort, right?
On your main method, after looping condition (on creating Student array) add this code.
selectionSort(myStudents);
for(Student s: myStudents) {
System.out.println(s.getName() + " " + s.getScore());
}
That code will print your array of students.

Java: How to change Class1 variables with Class2 variables

So my project is to make a small poker game that will ask users their name, how many players, and your bets.
However before all this, we need to ask the player if they would like to play a NEW game or a SAVED game. The saved game can be hard-coded.
I created a class1 game, and for the saved game file, I created class2. I want class2 to replace the values of class1 but I am not sure how to do this.
The issue is the values of CLASS1 are NOT being replaced by the values of CLASS2 when we call CLASS2. How can I get the variables from CLASS1 to update to CLASS2?
My First Class:
public class NoC2_Musick extends savedGame
{
public static void main(String[] args)
{
savedGame obj = new savedGame();
Scanner input = new Scanner(System.in);
Scanner inputString = new Scanner(System.in);
System.out.println("Is this a NEW Game or a PREVIOUS game?");
System.out.println("How many players will join this game?");
int totalPlayers = input.nextInt();
String[] players = new String[totalPlayers];
obj.oldsavedgame();
System.out.println("What is your name and club?");
for (int i = 0; i < totalPlayers; i++) {
players[i] = inputString.nextLine();
}
System.out.println("These are the Players: ");
for (int i = 0; i < totalPlayers; i++) {
System.out.println(players[i]);
}
System.out.println("Place your Bet.");
int bet = input.nextInt();
}
}
My Second Class:
public class savedGame
{
public int oldsavedgame()
{
int totalPlayers = 3;
String[] players;
players = new String[3];
players[0] = "Sofia";
players[1] = "Shawn";
players[2] = "Tomi";
int bet = 100;
System.out.println("Test");
return totalPlayers;
}
public static void main(String[] args)
{
}
}
I think you are missing some key things here. I do not think you should create a new class for storing the old info.
Just write a method that loads the data into instance variables.
Also, you are not reading the answer to the question: is this a new game / previous.
I would do something along these lines (note: It is not complete, but it should get you headed in the right direction, as far as loading a previous game):
public class NoC2_Musick {
int totalPlayers = 0;
ArrayList<String> players = new ArrayList<String>();
int bet = 0;
private void LoadSavedGame() {
totalPlayers = 3;
players.add("Sofia");
players.add("Shawn");
players.add("Tomi");
bet = 100;
}
public NoC2_Musick() {
Scanner input = new Scanner(System.in);
Scanner inputString = new Scanner(System.in);
System.out.println("Is this a NEW Game? (y/n)");
char newGame = input.next().charAt(0);
if(newGame == 'y')
{
System.out.println("How many players will join this game?");
totalPlayers = input.nextInt();
for (int i = 0; i < totalPlayers; i++) {
System.out.println("What is your name and club?");
players.add(inputString.nextLine());
}
}
else {
LoadSavedGame();
}
System.out.println("These are the Players: ");
for (int i = 0; i < totalPlayers; i++) {
System.out.println(players.get(i));
}
System.out.println("The current bet is: " + bet);
System.out.println("Place your Bet.");
int bet = input.nextInt();
}
public static void main(String[] args) {
new NoC2_Musick();
}
}

How to fix my Array class

I am trying to figure out how to get my array to run correctly, I know I have to change the array value to an input but I cannot get the program to compile if any one can help that be great.
I am trying to have the program take input for grades and names of students and in the end output their name and grade.
Edit sorry this is my first it posting i have an error
Student.java:60: error: class, interface, or enum expected I am in java 101 so this is why it is such low level java, we only know the basics
import java.util.Scanner;
public class students
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("How many students?: ");
int numofstudents = keyboard.nextInt();
Student s = new Student();
s.setMultipleStudents();
s.toString();
System.out.println("Enter the Grade for the student: ");
int gradeofstudnets = keyboard.nextInt();
}
}
and my second class is
import java.util.Scanner;
public class Student
{
Scanner scan = new Scanner(System.in);
private String name;
private int grade;
private int[] multiplegradeinputs = new int[10];
private String[] multipleStudent = new String[10];
public Student()
{
}
public Student(String n, int g)
{
name = n;
grade = g;
}
public String setMultipleStudents()
{
String n = "";
for(int i = 1; i < multipleStudent.length; i++)
{
System.out.println("Enter student #" + i +" name: " );
n = scan.nextLine();
multipleStudent[i] = n;
}
return null;
}
public String multiplegradeinputs()
{
for(int i = 1; i <multiplegradeinputs.length; i++)
{
System.out.println("Enter the Grade of the student#" + i +" : ");
grade = scan.nextInt();
multiplegradeinputs[i] = grade;
}
} <--- error here
public String toString()
{
String temp = "";
for(int i = 1; i < multipleStudent.length; i++)
{
temp += multipleStudent[i] + " ";
}
return temp;
}
}
Add return statement in your multiplegradeinputs() method:
public String multiplegradeinputs()
{
for(int i = 1; i <multiplegradeinputs.length; i++)
{
System.out.println("Enter the Grade of the student#" + i +" : ");
grade = scan.nextInt();
multiplegradeinputs[i] = grade;
}
return null; //Add this line
}
Or change your methods to void return type if they dont return anything.
Class names have to be capitalized in java, so instead of
public class students
you should write
public class Students
Also instead of writing
keyboard.nextInt();
You should write
Integer.parseInt(keyboard.nextLine());
This is mainly because java is full of bugs and technical specifications that you won't find easily. Let me know if this fixes it for you, since you didn't post the exact error message you got.
As for the error that you pointed out, it's because your function expects a String as a return value no matter what, so either change that to void if you can or return a null string. To do that just add the following line at the very end of the method.
return null;
You should create a Student object which holds the properties of the student, e.g. Name and Grades. You should then store all the student objects in some kind of data structure such as an array list in the students class.
Adding to the answer provided by #hitz
You have a bug in the for loops:
for(int i = 1; i <multiplegradeinputs.length; i++)
for(int i = 1; i < multipleStudent.length; i++)
You will never populated multiplegradeinputs[0] and multipleStudent[0] because you start the loop at index == 1 and thus you will have only 9 student names stored instead of 10.
Change to:
for(int i = 0; i <multiplegradeinputs.length; i++)
for(int i = 0; i < multipleStudent.length; i++)
Remember even though the length in 10, the indices always start with 0 in Java and in your case will end with 9.
import java.util.Scanner;
public class Student
{
Scanner scan = new Scanner(System.in);
private String name;
private int grade;
private int[] multiplegradeinputs = new int[10];
private String[] multipleStudent = new String[10];
public Student()
{
}
public Student(String n, int g)
{
name = n;
grade = g;
}
public String setMultipleStudents()
{
String n = "";
for(int i = 1; i < multipleStudent.length; i++)
{
System.out.println("Enter student #" + i +" name: " );
n = scan.nextLine();
multipleStudent[i] = n;
}
return null;
}
public void multiplegradeinputs()
{
for(int i = 1; i <multiplegradeinputs.length; i++)
{
System.out.println("Enter the Grade of the student#" + i +" : ");
grade = scan.nextInt();
multiplegradeinputs[i] = grade;
}
}
public String toString()
{
String temp = "";
for(int i = 1; i < multipleStudent.length; i++)
{
temp += multipleStudent[i] + " ";
}
return temp;
}
}
this is the 2nd class
import java.util.Scanner;
public class students
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("How many students?: ");
int numofstudents = keyboard.nextInt();
Student s = new Student();
s.setMultipleStudents();
s.toString();
System.out.println("Enter the Grade for the student: ");
int gradeofstudnets = keyboard.nextInt();
}
}
You are missing a return value in the multiplegradeinputs() method.

Java: The constructor gerbil(int) is undefined

So I've read over all of the constructor undefined posts on stackoverflow and tried the solutions and they haven't worked for me. Maybe I'm trying it wrong. I keep getting "the constructor Gerbil(int) is undefined."
The code that's the problem:
GerbilArray[i] = new Gerbil(i);
My full code:
import java.util.Scanner;
public class Gerbil {
public String name;
public String id;
public String bite;
public String escape;
public Gerbil() {
this.name = "";
this.id = "";
this.bite = "";
this.escape = "";
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("How many foods?");
int totalFood = keyboard.nextInt();
System.out.println("How many gerbils in the lab?");
int numberOfGerbils = keyboard.nextInt();
Gerbil[] GerbilArray = new Gerbil[numberOfGerbils];
for(int i = 0; i <= numberOfGerbils; i++){
GerbilArray[i] = new Gerbil(i);
System.out.print("Lab ID:");
String id = keyboard.next();
System.out.print("Gerbil Nickname:");
String name = keyboard.next();
System.out.print("Bite?");
String bite = keyboard.next();
System.out.print("Escapes?");
String city = keyboard.nextLine();
for (int j = 0; j < totalFood; j++) {
System.out.println("How many of food " + (j+1) + "do you eat?:");
}
}
}
}
Also you've probably seen that my nested for-loop isn't finished as well. I'm trying to make an array inside of an object that will store "x" amount of integers inside of my object listed from the user (int totalFood) but I have no idea how.
You don't have a constructor Gerbil(int a) in the class Gerbil and you try to call it!
Just call it this way:
GerbilArray[i] = new Gerbil();

Categories

Resources