I am a java beginner and I've tried to add the player in an array. I thought I successfully dealt with the problem, but it's not. I've done the following:
I have a split text send to create a player.
I have made a constructor in NimPlayer.
I set the array in Nimsys to save created player data.
And I have two questions:
It is for sure that the array will be all null at first. If I use the only array here, is that possible to add the player here?
I have set the counter for recording a created player, but I cannot do it in the else statement.
Here is my code:
int static counter;
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 void main(String[] args) {
NimPlayer[] playerList = new NimPlayer[10]; // set an array here
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
//Can use playerCheck to simplify the code
if (name != null && name.length==3 && counter < 10) {
if (playerList != null) {
for (int i = 0; i < playerList.length; i++) {
String userCheck = playerList[i].getUserName();
if (userCheck.contains(name[0])) {
System.out.println("The player already exist.");
} else {
System.out.println("The player has been created.");
playerList[counter++] = new NimPlayer(name[0],name[1],name[2], 0, 0);
}
}
} else {
// I have to add the player here
}
} else {
System.out.println("Invalid input! e.g. addplayer george,Washington,George");
}
}
And my NimPlayer is:
public class NimPlayer {
private String userName;
private String familyName;
private String givenName;
private int score;
private int gamePlayed;
public NimPlayer(String userName, String familyName, String givenName, int gamePlayed, int score) {
this.userName = userName;
this.familyName = familyName;
this.givenName = givenName;
this.gamePlayed = gamePlayed;
this.score = score;
}
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;
}
public int setScore(int score) {
return score;
}
public int getScore() {
return score;
}
public int setGamePlayed (int gamePlayed) {
return gamePlayed;
}
public int getGamePlayed() {
return gamePlayed;
}
}
Yes, you may alter the array elements as you wish. So "adding" players (setting the value of an array element within array bounds) is OK.
The else ("// I have to add the player here") will never be reached, since playerList is never null.
Since all elements in playerList is initialized to null, you should check if playerList[i] is null before calling
getUserName() (to avoid NullpointerException).
Related
I have a problem with changing variable value in contact object. I'm trying to make a contact list but I can't change value of variables trought methods. I have editContact method which calls changeName method, both methods are passed ArrayList object trought reference so it shouldn't have problems with changing values trought ArrayList in main method, but problem is when I want to change object's name it won't change it. Is there something I'm missing here?
package telefonski_imenik;
public class Contact {
protected String name;
protected String lastname;
protected String number;
public Contact(String name, String lastname, String number) {
setName(name);
setLastName(lastname);
setNumber(number);
}
public void setName(String name) {
this.name = name;
}
public void setLastName(String lastname) {
this.lastname = lastname;
}
public void setNumber(String number) {
this.number = number;
}
public String getName() {
return this.name;
}
public String getLastName() {
return this.lastname;
}
public String getNumber() {
return this.number;
}
}
package telefonski_imenik;
import java.util.ArrayList;
import java.util.Scanner;
public class TelefonskiImenik {
public static void createContact(String ime, String prezime, String broj, ArrayList<Contact>
ContactList) {
Contact noviKontakt = new Contact(ime, prezime, broj);
ContactList.add(noviKontakt);
}
public static void editContact(ArrayList<Contact> ContactList) {
System.out.println("Unesite nove podatke");
changeName(ContactList);
}
public static void changeName(ArrayList<Contact> ContactList) {
Scanner novinput = new Scanner(System.in);
System.out.println("Unesite staro ime");
String oldName = novinput.nextLine();
System.out.println("Unesite novo ime");
String newName = novinput.nextLine();
for (int i = 0; i < ContactList.size(); i++) {
if (ContactList.get(i).equals(oldName)) {
ContactList.get(i).setName(newName);
}
}
novinput.close();
}
public static void main(String[] args) {
ArrayList<Contact> ContactList = new ArrayList<Contact>();
Scanner input = new Scanner(System.in);
System.out.println("Unesite podatke");
String name = input.nextLine();
String lastname = input.nextLine();
String number= input.nextLine();
createContact(name, lastname, number, ContactList);
for (int i = 0; i < ContactList.size(); i++) {
System.out.println(ContactList.get(i).getName());
System.out.println(ContactList.get(i).getLastName());
System.out.println(ContactList.get(i).getNumber());
}
editContact(ContactList);
for (int i = 0; i < ContactList.size(); i++) {
System.out.println(ContactList.get(i).getName());
System.out.println(ContactList.get(i).getLastName());
System.out.println(ContactList.get(i).getNumber());
}
input.close();
}
}
You forgot to get the name of the object in your loop:
for (int i = 0; i < ContactList.size(); i++) {
if (ContactList.get(i).equals(oldName)) {
ContactList.get(i).setName(newName);
}
}
ContactList.get(i).getName().equals(oldName)
I am a JAVA beginner, and I've done some research. It turned out there is no such a way to deal with this problem. I'm assigned to design a prompt command with multiple data inputs, with only one scanner object.
Now, I've already achieved the following:
Set an array for saving the NimPlayer object.
Set the NimPlayer class for creating a unique NimPlayer object.
Set the counter, used as an index.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print('$');
String input = in.next();
// initialize an array
NimPlayer [] playerList = new NimPlayer[10];
// create a position in the array
int addUserCount = 0;
if (input.equals("addplayer")) {
String userName = in.next();
String familyName = in.next();
String givenName = in.next();
addUserCount +=1;
playerList[addUserCount] = new NimPlayer(userName, familyName, givenName);
}
public class NimPlayer {
String userName;
String familyName;
String givenName;
public NimPlayer(String userName,String surName, String givenName) {
this.userName = userName;
this.familyName = surName;
this.givenName = givenName;
}
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;
}
}
the goal is to design like this:
addplayer userName,familyName,givenName
So, that's why I use next() to identify the first word, and space is the default delimiter.
I am not sure how to do next. What should I do to add a feature that separates the inputs using ",".
Any help is appreciated.
You can read lines with Scanner.nextLine(). Here is an example how you can type "username, surname, givenname" in one line and get splitted by String.split(",").
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String line = s.nextLine();
String[] splittedLine = line.split(",");
for(int i = 0; i < splittedLine.length; i++) {
System.out.printf("splitted line: %d. %s \n", i, splittedLine[i].trim());
}
}
Input:
name, surename, username
Output:
splitted line: 1. name
splitted line: 2. surename
splitted line: 3. username
Ive been trying to use a for loop to add instances of a driver to a driver array. Each driver has 3 basic variables that are gathered through the for loop. When the loop runs though, the details of the last driver are stored in all of the indexes of the array! I want to get it so that i can add each individual driver to the array.
public static void addDriver(Driver[] d) { //method using for loop to add drivers
for(int i = 0; i < d.length; i++ ) {
String name, DOB, occupation;
System.out.println("Please Enter Driver Name");
name = kb.nextLine();
System.out.println("Please Select Driver Occupation");
System.out.println("1: Chauffeur" + "\n2: Accountant");
int choice = kb.nextInt();
kb.nextLine();
if (choice == 1) {
occupation = "Chauffeur";
} else {
occupation = "Accountant";
}
System.out.println("Please Enter Driver D.O.B");
DOB = kb.nextLine();
d[i] = new Driver(name, occupation, DOB);
}
}
any and all help greatly appreciated!
edit...
here is the code from the main method, i get the size of the array from a separate method called driverNum.
public static void main(String[] args) {
int drivers = driverNum(); //Setting size of the array
Driver[] d = new Driver[drivers]; //creating new array using number of drivers to be insured
addDriver(d); //calling method to add drivers to array
for(int x = 0; x < d.length; x++)
{
System.out.println(d[x].toString());
}
}
here is the Driver class that i have been using...
public class Driver {
static String name, occupation, DOB;
public Driver()
{
name = "";
occupation = "";
DOB = "";
}
public Driver(String name, String occupation, String DOB)
{
this.name = name;
this.occupation = occupation;
this.DOB = DOB;
}
public void setName(String name)
{
this.name = name;
}
public String getName(Driver d)
{
return name;
}
public void setOccupation(String occupation)
{
this.occupation = occupation;
}
public String getOccupation()
{
return occupation;
}
public void setDOB(String DOB)
{
this.DOB = DOB;
}
public String getDOB()
{
return DOB;
}
public String toString()
{
String s;
s = "Name: " + name;
s = s + "\nOccupation: " + occupation;
s = s + "\nDOB: " + DOB;
return s;
}
}
Ive been scratching my head over this for a while now, because i thought it was correct. Thanks for the help so far!
In your Driver class, you defined your three global variables, name, occupation, and D.O.B as static. This means that whenever you change the value of that variable, it will change everywhere in the program, even if you create multiple instances of that class. Just take out the static declaration and that should solve your problem.
I have 3 classes, Movie which is used to add Movie objects to an in MovieDatabase but it keeps printing null.
When I add 2 Movies its like the first Movie is erased and it prints null instead. Also is there a way to check if the position in the array is empty and not print if it is empty?
Here is my Movie class
public class Movie {
private String name;
private String director;
private double fileSize;
private int duration;
private int moviecount;
public Movie()
{
name = null;
director = "";
fileSize = 0;
duration = 0;
}
public void setName(String newName)
{
name = newName;
}
public String getName()
{
return name;
}
public void setDirector(String newDirector)
{
director = newDirector;
}
public String getDirector()
{
return director;
}
public void setfileSize(double newfileSize)
{
fileSize = newfileSize;
}
public double getfileSize()
{
return fileSize;
}
public void setDuration(int newDuration)
{
duration = newDuration;
}
public int getDuration()
{
return duration;
}
and here my MovieDatabase class:
public class MovieDatabase
{
private Movie[] mov;
private int i;
public int count=0;
public MovieDatabase()
{
mov = new Movie[4];
i=0;
}
public void addData(String name, String director, double fileSize, int duration)
{
for(int i=0; i<4; i++)
mov[i] = new Movie();
setData(mov[i],name,director,fileSize,duration);
i++;
count++;
}
private void setData(Movie m,String name, String director, double fileSize, int duration)
{
mov[i].setName(name);
mov[i].setDirector(director);
mov[i].setfileSize(fileSize);
mov[i].setDuration(duration);
}
public void printNames()
{
for (int i = 0; i < mov.length; i++)
{
System.out.println(mov[i].getName());
}
}
}
import java.util.*;
public class Interface {
Scanner console = new Scanner(System.in);
MovieDatabase m = new MovieDatabase();
private void run()
{
int option;
do{
System.out.print("Add Movie(0), Delete Movie(2),Show Movies(3),Movie Count(4) \n");
option = console.nextInt();
switch(option)
{
case 0: addMovie();
break;
case 3: printMovies();
break;
}
}
while(option!=9);
}
public static void main(String[] args){
Interface intFace = new Interface();
intFace.run();
}
public void addMovie()
{
String name, director;
double fileSize;
int duration;
System.out.println("Movie Name: ");
name = console.next();
System.out.println("Movie Director: ");
director = console.next();
System.out.println("Movie File Size: ");
fileSize = console.nextDouble();
System.out.println("Movie Duration: ");
duration = console.nextInt();
System.out.print("Movie Added!");
m.addData(name,director,fileSize,duration);
}
public void printMovies()
{
m.printNames();
}
}
I tried to include only the relevant parts but majority of what I have done so far is relevant.
The problem is in these lines
....
public void addData(String name, String director, double fileSize, int duration)
{
for(int i=0; i<4; i++)
mov[i] = new Movie();
...
Each and every time you're adding a new data, you're erasing all previous records by assigning new movie object to every element in array. This erases all previous data.
You should instead move these 2 lines in MovieDatabase constructor. Or a better option would be to initialize them when you're setting data.
...
public void addData(String name, String director, double fileSize, int duration)
{
setData(mov[i],name,director,fileSize,duration);
i++;
count++;
}
private void setData(Movie m,String name, String director, double fileSize, int duration)
{
mov[i] = new Movie(); //++ edit
mov[i].setName(name);
mov[i].setDirector(director);
mov[i].setfileSize(fileSize);
mov[i].setDuration(duration);
}
...
Also is there a way to check if the position in the array is empty and not print if it is empty?
You can create a method in Movie class which checks whether this movie object is empty or not and returns appropriate result.
public class Movie {
...
...
public boolean isEmpty() {
if(
this.name.isEmpty() &&
this.director &&
this.fileSize == 0 &&
this.duration == 0 &&
this.moviecount == 0
)
return true;
else
return false;
}
...
...
}
Now you can check whether this movie object is empty or not using:
if(mov[i].isEmpty()) {
//empty movie object
...
}
In setData you always set the value of mov[0]. The class member i will never change (loop variable hides it). You do not use the parameter m to set the data.
Change your setData to
m.setName(name);
m.setDirector(director);
m.setfileSize(fileSize);
m.setDuration(duration);
This is not supposed to be a client class. I'm just making a class for others to use. I'm using this for a Highschool. For example i have classes for the address, teacher, students, principal, roomnumber, etc..But its not compiling for some odd reason. I believe its because I'm not declaring a field but not sure.
import java.io.*;
public class HighSchool {
// Constructors
public HighSchool() { }
public HighSchool(String title, String teacher, int roomNumber, String period, String[] students, String address, String subjects ) {
this.title = title;
this.teacher = teacher;
this.roomNumber = roomNumber;
this.period = period;
this.String[] students = students;
this.String address =a ddress;
this.String subjects = subjects;
}
public class Classcourse (String title, String teacher, int roomNumber, String period, String[] students, String address, String subjects
private String period;) {
public String gettitle() {
return title;
}
public void settitle(String title) {
this.title = title;
}
public String getteacher() {
return teacher;
}
public void setteacher(String teacher) {
this.teacher = teacher;
}
public int getroomNumber() {
return roomNumber;
}
public void setroomNumber (int roomNumber) {
this.roomNumber = roomNumber;
}
public String getperiod() {
return getperiod();
}
public void setperiod (String period) {
this.period = period;
}
public String[] getstudents () {
return students[];
}
public void setstudents[] (String[] students
private String address;) {
this.students = students;
}
public String getaddress() {
return address;
}
public void setaddress (String address) {
this.address = address;
}
public String getsubjects() {
return subjects;
}
public void setsubjects (String subjects) {
this.subjects = subjects;
}
}
// modifier method
public void addstudents(String students) {
String[] newstudents = new String[students.length + 1];
for (int i = 0; i < students.length; i++) {
newstudents[i] = students[i];
}
newstudents[students.length] = student;
students = newstudents;
}
public boolean isInClass(String students) {
for (int i = 0; i < students.length; i++) {
if (students[i].equals(students)) {
return true;
}
}
return false;
}
// static creator method
public static HighSchool readFromInput() throws IOException {
BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a HighSchool title: ");
HighSchool newHighSchool = new HighSchool(kb.readLine());
String students = null;
do {
System.out.print("Enter a student, or press Enter to finish: ");
students = kb.readLine();
if (students != null){
newHighSchool.addstudents(students);
}
} while (students != null);
return newHighSchool;
}
// Variables (Fields)
private String title;
private String[] students;
}
In addition, you wrote something that doesn't make sense from the point of view of Java Compiler:
private String period;) {
- probably remove ")".
The second thing:
Take a look on the declaration of class Classcourse.
It rather sounds wrong, although it can be an issue of this site's editor or something...
An "overall" hint - java has a very "intelligent" compiler in the most of the cases it can say what's wrong exactly with your code, so, assuming you're a newbie in Java, try to understand what compiler says to you.
Good luck!
Some things I noticed about the code:
public String getperiod() {
return getperiod();
}
This code will cause a endless loop when you call this function.
private String address;) {
this.students = students;
}
The compiler will give an error about the ";)". Change it to "()" to fix this.
Furthermore, you should really tell us more about the errors it's giving you. We can't help you if you don't give us the compiler errors.