"For" loop issue at ArrayList method in Java - java

I have an issue at TestVolleyTeam.java. I cannot get the list arrays to work, I am honestly confused. I don't really know how to assign the lists with the "for" loop, I have probably made a mistake there.
The code is supposed to show the list of the players by using both the VolleyPlayer class and the VolleyTeam class through the TestVolleyTeam class. Can anyone spot the mistakes I've made?
class VolleyPlayer {
private String name;
private String surname;
private int flnum;
private int height;
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public int getFlnum() {
return flnum;
}
public int getHeight() {
return height;
}
public VolleyPlayer(String n, String sur, int fl, int h) {
name = n;
surname = sur;
flnum = fl;
height = h;
}
public VolleyPlayer(String n, String sur, int fl) {
this(n, sur, fl, 185);
}
public VolleyPlayer(String n, String sur) {
this(n, sur, 3);
}
public VolleyPlayer(String n) {
this(n, "Brown");
}
}
import java.util.ArrayList;
public class VolleyTeam {
private String teamname;
private String city;
private int year;
private ArrayList<VolleyPlayer> players;
public String getTeamname() {
return teamname;
}
public String getCity() {
return city;
}
public int getYear() {
return year;
}
public ArrayList<VolleyPlayer> getPlayers() {
return players;
}
public void setTeamname(String newTeamname) {
this.teamname = teamname;
}
public void setCity(String newCity) {
this.city = city;
}
public void setYear(int newYear) {
this.year = year;
}
public void setPlayers(ArrayList<VolleyPlayer> newPlayers) {
this.players = players;
}
}
import javax.swing.JOptionPane;
import java.util.Scanner;
import java.util.ArrayList;
public class TestVolleyTeam {
public static void main(String[] args) {
VolleyTeam myObj = new VolleyTeam();
String teamname = JOptionPane.showInputDialog(null, "What is the name of the team?", "Input");
myObj.setTeamname(teamname);
String city = JOptionPane.showInputDialog(null, "What is the city of the team?", "Input");
myObj.setCity(city);
String input = JOptionPane.showInputDialog(null, "What is the foundation year of the team?",
"Input");
int year = Integer.parseInt(input);
myObj.setYear(year);
myObj.getTeamname();
myObj.getCity();
myObj.getYear();
VolleyPlayer first = new VolleyPlayer("Michael", "Scott", 1, 175);
VolleyPlayer second = new VolleyPlayer("Jim", "Halpert", 2, 191);
VolleyPlayer third = new VolleyPlayer("Dwight", "Schrute", 3, 189);
VolleyPlayer fourth = new VolleyPlayer("Darryl", "Philbin", 4, 188);
VolleyPlayer fifth = new VolleyPlayer("Andy", "Bernard", 5, 182);
VolleyPlayer sixth = new VolleyPlayer("Oscar", "Martinez", 6, 173);
VolleyPlayer seventh = new VolleyPlayer("Stanley", "Hudson", 7, 180);
VolleyPlayer eighth = new VolleyPlayer("Kevin", "Malone", 8, 185);
VolleyPlayer ninth = new VolleyPlayer("Creed", "Bratton", 9, 183);
VolleyPlayer tenth = new VolleyPlayer("Toby", "Flederson", 10, 177);
ArrayList<VolleyPlayer> vplist = new ArrayList<VolleyPlayer>();
for (VolleyPlayer volleyPlayer : vplist) {
vplist.add(volleyPlayer);
}
myObj.getPlayers();
myObj.setPlayers(vplist);
ArrayList<VolleyPlayer> vplist2 = volleyTeam.getPlayers();
for (VolleyPlayer volleyPlayer : vplist2) {
vplist2.add(volleyPlayer);
}
volleyTeam.getPlayers();
volleyTeam.setPlayers(vplist2);
JOptionPane.showMessageDialog(null, vplist2, teamname + " " + city + ", " + year,
JOptionPane.INFORMATION_MESSAGE);
}
}

The List is empty when you start, this code
for (VolleyPlayer volleyPlayer : vplist) {
is attempted to loop over an empty List. I think I see what you want, and it can be achieved with something like
List<VolleyPlayer> vplist = new ArrayList<>(Arrays.asList(
first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth));
Then you don't need a loop to add first - tenth to your vplist. Note I changed it the diamond operator <> on construction. And used Arrays.asList to add the elements.
Since you must use a for loop, create an inline array. Like,
for (VolleyPlayer volleyPlayer : new VolleyPlayer[] {
first, second, third, fourth, fifth, sixth, seventh,
eighth, ninth, tenth }) {

Related

How to sort a continuously updated (dynamic) object in an array

I am building a classical Nim game. So far, I've done the player part and the game part. Now, I am trying to sort(rank) the object in an array. I've built the following for sorting:
playerList
winRatio, which is set in the NimPlayer class with its getter.
The aim :
to sort the winRatio descendingly, which means from the highest score to the lowest one. The ratio is calculated by score/gamePlayed.
If there's a tie, sort using userName alphabetically.
I've referred to this issue: How to sort an array of objects in Java?
I know what I should do is use the Comparable or Comparator for sorting but from the article, they sort using the attributes in the object (All the information I've found so far). What I am dealing with is the continuously updated data outside the constructor.
What I've tried was directly printed out the data without sorting.
Here is my related code (NimPlayer):
public class NimPlayer {
private String userName;
private String familyName;
private String givenName;
static int counter;
private int score;
private int gamePlayed;
static NimPlayer[] playerList = new NimPlayer[2]; // set an array here
//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 (counter<10) {
playerList[counter++] = new NimPlayer(userName, familyName, givenName);
} else {
System.out.println("Cannot add more players.");
}
// all the getter and setter related to the constructor; the getter of the player list.
}
public void setScore(int score) {
this.score=score;
}
public int getScore() {
return score;
}
public void setGamePlayed (int gamePlayed) {
this.gamePlayed = gamePlayed;
}
public int getGamePlayed() {
return gamePlayed;
}
public int getWinRatio () {
return Math.round(Float.valueOf(getScore())/ (getGamePlayed()+1)*100) ;
}
}
This is my main class (Nimsys)
public static void searchAndPrintRankingData() {
for (int i = 0; i < NimPlayer.getCounter(); i++) {
String familyName = NimPlayer.getPlayer()[i].getFamilyName();
String givenName = NimPlayer.getPlayer()[i].getGivenName();
int score = NimPlayer.getPlayer()[i].getScore();
int gamePlayed = NimPlayer.getPlayer()[i].getGamePlayed();
double winRatio = score/(gamePlayed+1);//wrong calculation for testing
System.out.println(winRatio+"% | "+gamePlayed+" games | "+givenName+" "+familyName);
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) {
System.out.print('$');
String commandin = in.next();
if (commandin.equals("rankings")) {
String commandOrder = in.nextLine().trim();
if (commandOrder.equals("asc")) {
//sort the data
searchAndPrintRankingData();
}
if (commandOrder.equals("") || commandOrder.equals("desc")) {
//sort the data
searchAndPrintRankingData();
}
}
}
Any help is highly appreciated.
Use Interface Comparator
Do it as follows:
import java.util.Arrays;
import java.util.Comparator;
class NimPlayer {
private String userName;
private String familyName;
private String givenName;
private static int counter;
private static final int SIZE = 4;
private int score;
private int gamePlayed;
static NimPlayer[] playerList = new NimPlayer[SIZE];
public NimPlayer(String userName, String surName, String givenName) {
this.userName = userName;
this.familyName = surName;
this.givenName = givenName;
}
public static void createPlayer(String userName, String familyName, String givenName) {
if (counter < SIZE) {
playerList[counter++] = new NimPlayer(userName, familyName, givenName);
} else {
System.out.println("Cannot add more players.");
}
}
public static int getCounter() {
return counter;
}
public static NimPlayer[] getPlayerList() {
return playerList;
}
public String getUserName() {
return userName;
}
public String getFamilyName() {
return familyName;
}
public String getGivenName() {
return givenName;
}
public void setScore(int score) {
this.score = score;
}
public int getScore() {
return score;
}
public void setGamePlayed(int gamePlayed) {
this.gamePlayed = gamePlayed;
}
public int getGamePlayed() {
return gamePlayed;
}
public int getWinRatio() {
return Math.round((Float.valueOf(score) / gamePlayed) * 100);
}
#Override
public String toString() {
return "User Name: " + userName + ", Name: " + givenName + " " + familyName + ", Score: " + score
+ ", Games Played: " + gamePlayed + ", Win ratio: " + getWinRatio();
}
}
public class Main {
static void searchAndPrintRankingData() {
NimPlayer[] players = NimPlayer.getPlayerList();
Arrays.sort(players,
Comparator.comparing((NimPlayer::getWinRatio)).reversed().thenComparing(NimPlayer::getUserName));
Arrays.stream(players).forEach(System.out::println);
}
public static void main(String[] args) {
NimPlayer.createPlayer("Avi", "Avinash", "Arvind");
NimPlayer.createPlayer("Harry", "Potter", "Harry");
NimPlayer.createPlayer("Vishy", "Anand", "Vishwanathan");
NimPlayer.createPlayer("Bond", "Bond", "James");
NimPlayer[] players = NimPlayer.getPlayerList();
players[0].setGamePlayed(2);
players[0].setScore(40);
players[1].setGamePlayed(3);
players[1].setScore(75);
players[2].setGamePlayed(2);
players[2].setScore(120);
players[3].setGamePlayed(4);
players[3].setScore(100);
System.out.println("Unsorted: ");
Arrays.stream(NimPlayer.getPlayerList()).forEach(System.out::println);
System.out.println();
System.out.println("Sorted on win ratio (then name, in case of tie): ");
searchAndPrintRankingData();
}
}
Output:
Unsorted:
User Name: Avi, Name: Arvind Avinash, Score: 40, Games Played: 2, Win ratio: 2000
User Name: Harry, Name: Harry Potter, Score: 75, Games Played: 3, Win ratio: 2500
User Name: Vishy, Name: Vishwanathan Anand, Score: 120, Games Played: 2, Win ratio: 6000
User Name: Bond, Name: James Bond, Score: 100, Games Played: 4, Win ratio: 2500
Sorted on win ratio (then name, in case of tie):
User Name: Vishy, Name: Vishwanathan Anand, Score: 120, Games Played: 2, Win ratio: 6000
User Name: Bond, Name: James Bond, Score: 100, Games Played: 4, Win ratio: 2500
User Name: Harry, Name: Harry Potter, Score: 75, Games Played: 3, Win ratio: 2500
User Name: Avi, Name: Arvind Avinash, Score: 40, Games Played: 2, Win ratio: 2000
Note: In case you wish to use ArrayList<NimPlayer> in searchAndPrintRankingData, given below is the code for the same:
static void searchAndPrintRankingData() {
List<NimPlayer> players = new ArrayList<NimPlayer>(Arrays.asList(NimPlayer.getPlayerList()));
Collections.sort(players,
Comparator.comparing((NimPlayer::getWinRatio)).reversed().thenComparing(NimPlayer::getUserName));
players.stream().forEach(System.out::println);
}
For sort ascending use the code link you mentioned. As long as the players have been added to the array, you can sort them. The code below is the key (you will need to adapt variable names etc)
You will need to add winRation etc to NimPlayer constructor and as element of the array, then it can sort it.
#Test
public void sortBooks() {
Book[] books = {
new Book("foo", "1", "author1", "pub1"),
new Book("bar", "2", "author2", "pub2")
};
// 1. sort using Comparable
Arrays.sort(books);
System.out.println(Arrays.asList(books));
// 2. sort using comparator: sort by id
Arrays.sort(books, new Comparator<Book>() {
#Override
public int compare(Book o1, Book o2) {
return o1.id.compareTo(o2.id);
}
});
System.out.println(Arrays.asList(books));
}
Change this :
return o1.id.compareTo(o2.id);
To:
return o1.winRatio.compareTo(o2.winRatio);
It should work by implementing the Comparable interface, as the compareTo method will be called each time you want to sort and will have the updated data.
To sort first by winRatio, and if equal, by name, it can work with the following code:
public class NimPlayer implements Comparable<NimPlayer> {
...
#Override
public int compareTo(NimPlayer o) {
// get the comparison of the win ratios
int ratioCompare = this.getWinRatio().compareTo(o.getWinRatio());
// if the winRatio is equal, return the reverse comparison of the usernames
return (ratioCompare != 0) ? ratioCompare : o.userName.compareTo(this.userName);
}
}
Then, to sort the array, you just need to use the Arrays class:
Arrays.sort(NimPlayer.playerList);
Arrays.sort(NimPlayer.playerList, Collections.reverseOrder()); // for desc order
The problem you may face with that is if you always want to have the username ordered ASC.
In that case, your only option is to implement two different comparators, one for ascending and another for descending orders:
Comparator<NimPlayer> ascComparator = (p1, p2) -> {
int ratioCompare = p1.getWinRatio().compareTo(p2.getWinRatio());
return (ratioCompare != 0) ? ratioCompare : p1.getUserName().compareTo(p2.getUserName());
};
Comparator<NimPlayer> descComparator = (p1, p2) -> {
int ratioCompare = p2.getWinRatio().compareTo(p1.getWinRatio());
return (ratioCompare != 0) ? ratioCompare : p1.getUserName().compareTo(p2.getUserName());
};
To sort using those comparators, just pass the comparators into the Arrays.sort method:
Arrays.sort(NimPlayer.playerList, ascComparator);
Arrays.sort(NimPlayer.playerList, descComparator);
Your NimPlayer needs to implement Comparable interface:
public class NimPlayer implements Comparable<NimPlayer> {
#Override
public int compareTo(NimPlayer other) {
if (other.getWinRatio() == this.getWinRatio()) {
return this.getUserName().compareTo(other.getUserName());
} else if (other.getWinRatio() > this.getWinRatio()) {
return 1;
}
return -1;
}
public static NimPlayer[] getPlayer() {
Arrays.sort(playerList);
return playerList;
}
}
Also, you need to fix the size of your playerList, which is set to 2 static NimPlayer[] playerList = new NimPlayer[2];, and then you try to add up to 10 players :)
And when adding players to the list you'd better compared counter to actual playerList.length;

Generating sequence numbers in Java from the ArrayList

How to generate sequence numbers and assign them to each object in java?
for example i have the following,
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class MyMaxUDOComparable
{
public static Integer findMaxScore(List<testVO> emps)
{
Integer maxScoreTotal = 0;
for (Iterator<JobFitSurveyConfigVO> iterator = emps.iterator(); iterator.hasNext();)
{
testVOempl = (testVO) iterator.next();
if (empl != null)
{
maxScoreTotal += empl.getSalary();
}
}
return maxScoreTotal;
}
public static void main(String a[])
{
List<testVO> emps = new ArrayList<testVO>();
emps.add(new testVO(10, "Raghu", 10,1));
emps.add(new testVO(120, "Krish", 10,2));
emps.add(new testVO(210, "John", 10,3));
emps.add(new testVO(150, "Kishore", 10,4));
testVOmaxSal = Collections.max(emps);
System.out.println("Employee with max Id: " + maxSal);
System.out.println("maxScoreTotal: " + findMaxScore(emps));
}
}
class testVOimplements Comparable<testVO>
{
private Integer id;
private String name;
private Integer salary;
private Integer sequenceNumber;
public testVO(Integer id, String name, Integer sal,Integer sequenceNumber) {
this.id = id;
this.name = name;
this.salary = sal;
}
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Integer getSalary()
{
return salary;
}
public void setSalary(Integer salary)
{
this.salary = salary;
}
public Integer getSequenceNumber()
{
return sequenceNumber;
}
public void setSequenceNumber(Integer sequenceNumber)
{
this.sequenceNumber = sequenceNumber;
}
#Override
public int compareTo(JobFitSurveyConfigVO emp)
{
return this.id.compareTo(emp.getId());
}
public String toString()
{
return id + " " + name + " " + salary;
}
}
in the above class, i have assigned values to all the objects for Sequence Number and if I remove any object from the list then the Sequence Number has to be re generated.
how to do this in java, would some one help me on this please?.
public void deleteObjFormList(JobFitSurveyConfigVO emp,List<JobFitSurveyConfigVO> emps)
{
int i = emps.indexOf(emp);
emps.remove(i);
for(int j=i;j<emps.size();j++)
{
JobFitSurveyConfigVO emp1 = emps.get(j);
emp1.setSequenceNumber(emp1.getSequenceNumber()-1);
}
return;
}
I this this should be a function to remove the object from the list.
You iterate the list and set the sequence number.
Be aware that your constructor is not assigning the sequence number, so although you provided values, they are all null. If you changed type to the more sensible int, they would be 0.
// Renumber (aka resequence) the emp records
for (int i = 0; i < emps.size(); i++)
emps.get(i).setSequenceNumber(i + 1);
try this way
public static void main(String a[]) {
List<JobFitSurveyConfigVO> emps = new ArrayList<JobFitSurveyConfigVO>();
ArrayList<Integer> seq = new ArrayList<Integer>();
addElement(seq, emps, 10, "Raghu", 10);
addElement(seq, emps, 120, "Krish", 10);
addElement(seq, emps, 210, "John", 10);
addElement(seq, emps, 150, "Kishore", 10);
System.out.println("Display : "+emps);
removeElement(2, seq, emps);
System.out.println("Removed : "+emps);
addElement(seq, emps, 210, "John2", 10);
System.out.println("Added : "+emps);
}
Add Element and Remove Element methods
public static void addElement(ArrayList<Integer> seq,
List<JobFitSurveyConfigVO> emps, int id, String name, Integer salary) {
int size = seq.size();
Collections.sort(seq); // Make sure they are in Sequence.
if (size > 1) {
for (int i = 1; i < size; i++) {
int check = seq.get(i-1);
if ( (check + 1) != (seq.get(i))) {
seq.add(check + 1);
emps.add(new JobFitSurveyConfigVO(id, name, salary, (check + 1)));
break;
}
if (i+1 == size) {
seq.add(seq.get(i) + 1);
emps.add(new JobFitSurveyConfigVO(id, name, salary, (seq.get(i) + 1)));
}
}
}else if (size == 1 && seq.get(0) == 1) {
int check = seq.get(0);
seq.add(check + 1);
emps.add(new JobFitSurveyConfigVO(id, name, salary, (check + 1)));
}else{
seq.add(1);
emps.add(new JobFitSurveyConfigVO(id, name, salary, 1));
}
}
public static void removeElement(int index, ArrayList<Integer> seq, List<JobFitSurveyConfigVO> emps){
if (index < seq.size()) {
emps.remove(index);
seq.remove(index);
}else {
throw new ArrayIndexOutOfBoundsException();
}
}
constructor
public JobFitSurveyConfigVO(Integer id, String name, Integer sal,Integer sequenceNumber) {
this.id = id;
this.name = name;
this.salary = sal;
this.sequenceNumber = sequenceNumber;
}

"new Parameters" on Java

I want the out put is like this:
Conan is NOT the same age as Natsu
this output program create the latest parameters.
Natsu is the same age as Natsu.
below is java program that I have made.
Syntax code that I have made
package rawrandomtest;
public class GetSet002 {
private static String name;
private static int age;
public GetSet002(String s, int i){
GetSet002.name = s;
GetSet002.age = i;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
public void setAge(int x){
GetSet002.age =x;
}
}
Driver Code
package rawrandomtest;
import java.util.Scanner;
public class GetSet002Driver {
public static Scanner input = new Scanner (System.in);
public static void main (String[] args){
GetSet002 p1 = new GetSet002("Conan", 14);
GetSet002 p2 = new GetSet002("Natsu", 18);
if(p1.getAge()==p2.getAge()){
System.out.println(p1.getName()+" is the same age as "+p2.getName());
}else{
System.out.println(p1.getName()+" is NOT the same age as "+p2.getName());
}
}
}
The age is a static variable. You change the value for all instances, every time you set the variable.
GetSet002 p1 = new GetSet002("Conan", 14);
//result: GetSet002 = ("Conan" , 14)
GetSet002 p2 = new GetSet002("Natsu", 18);
//result: GetSet = ("Natsu" , 18);
if(p1.getAge() == p2.getAge())
//is semantically equal to:
if(GetSet002.age == GetSet002.age)
//public accessiblity is only implied for demonstration

java.util.Scanner; vs JOptionPane; [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Please I would like know How would I implement JOptionPane instead of import java.util.Scanner;
I also have 4 separate classes
If i implement JOptionPane will it clean up the code I would also like to know any changes anyone would make.
Employee.Class
import java.text.NumberFormat;
import java.util.Scanner;
public class Employee {
public static int numEmployees = 0;
protected String firstName;
protected String lastName;
protected char gender;
protected int dependents;
protected double annualSalary;
private NumberFormat nf = NumberFormat.getCurrencyInstance();
public Benefit benefit;
private static Scanner scan;
public Employee() {
firstName = "";
lastName = "";
gender = 'U';
dependents = 0;
annualSalary = 40000;
benefit = new Benefit();
numEmployees++;
}
public Employee(String first, String last, char gen, int dep, Benefit benefit1) {
this.firstName = first;
this.lastName = last;
this.gender = gen;
this.annualSalary = 40000;
this.dependents = dep;
this.benefit = benefit1;
numEmployees++;
}
public double calculatePay1() {
return annualSalary / 52;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("First Name: ").append(firstName).append("\n");
sb.append("Last Name: ").append(lastName).append("\n");
sb.append("Gender: ").append(gender).append("\n");
sb.append("Dependents: ").append(dependents).append("\n");
sb.append("Annual Salary: ").append(nf.format(getAnnualSalary())).append("\n");
sb.append("Weekly Pay: ").append(nf.format(calculatePay1())).append("\n");
sb.append(benefit.toString());
return sb.toString();
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public <Gender> void setGender(char gender) {
this.gender = gender;
}
public <Gender> char getGender() {
return gender;
}
public void setDependents(int dependents) {
this.dependents = dependents;
}
public void setDependents(String dependents) {
this.dependents = Integer.parseInt(dependents);
}
public int getDependents() {
return dependents;
}
public void setAnnualSalary(double annualSalary) {
this.annualSalary = annualSalary;
}
public void setAnnualSalary(String annualSalary) {
this.annualSalary = Double.parseDouble(annualSalary);
}
public double getAnnualSalary() {
return annualSalary;
}
public double calculatePay() {
return annualSalary / 52;
}
public double getAnnualSalary1() {
return annualSalary;
}
public static void displayDivider(String outputTitle) {
System.out.println(">>>>>>>>>>>>>>> " + outputTitle + " <<<<<<<<<<<<<<<");
}
public static String getInput(String inputType) {
System.out.println("Enter the " + inputType + ": ");
scan = new Scanner(System.in);
String input = scan.next();
return input;
}
public static int getNumEmployees() {
return numEmployees;
}
public static void main(String[] args) {
displayDivider("New Employee Information");
Benefit benefit = new Benefit();
Employee employee = new Employee("George", "Anderson", 'M', 5, benefit);
System.out.println(employee.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Hourly Temp Employee Information");
Hourly hourly = new Hourly("Mary", "Nola", 'F', 5, 14, 45, "temp");
System.out.println(hourly.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Hourly Full Time Employee Information");
Hourly hourly1 = new Hourly("Mary", "Nola", 'F', 5, 18, 42, "full time");
System.out.println(hourly1.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Hourly Part Time Employee Information");
Hourly hourly11 = new Hourly("Mary", "Nola", 'F', 5, 18, 20, "part time");
System.out.println(hourly11.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Salaried Revised Employee Information");
Benefit benefit1 = new Benefit("None", 500, 3);
Salaried salaried = new Salaried("Frank", "Lucus", 'M', 5, 150000, benefit1, 3);
System.out.println(salaried.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Salaried Employee Information");
Benefit benefit11 = new Benefit("None", 500, 3);
Salaried salaried1 = new Salaried("Frank", "Lucus", 'M', 5, 100000, benefit11, 2);
System.out.println(salaried1.toString());
System.out.println("Total employees: " + getNumEmployees());
}
}
SALARIED.CLASS
import java.util.Random;
import java.util.Scanner;
public class Salaried extends Employee {
private static final int MIN_MANAGEMENT_LEVEL = 0;
private static final int MAX_MANAGEMENT_LEVEL = 3;
private static final int BONUS_PERCENT = 10;
private int managementLevel;
private Scanner in;
public Salaried() {
super();
Random rand = new Random();
managementLevel = rand.nextInt(4) + 1;
if (managementLevel == 0) {
System.out.println("Not Valid");
}
//numEmployees++;
}
private boolean validManagementLevel(int level) {
return (MIN_MANAGEMENT_LEVEL <= level && level <= MAX_MANAGEMENT_LEVEL);
}
public Salaried(String fname, String lname, char gen, int dep,
double sal, Benefit ben, int manLevel)
{
super.firstName = fname;
super.lastName = lname;
super.gender = gen;
super.dependents = dep;
super.annualSalary = sal;
super.benefit = ben;
while (true) {
if (!validManagementLevel(manLevel)) {
System.out.print("Invalid management level, please enter
another management level value in range [0,3]: ");
manLevel = new Scanner(System.in).nextInt();
} else {
managementLevel = manLevel;
break;
}
}
//numEmployees++;
}
public Salaried(double sal, int manLevel) {
super.annualSalary = sal;
while (true) {
if (!validManagementLevel(manLevel)) {
System.out.print("Invalid management level, please enter another
management level value in range [0,3]: ");
in = new Scanner(System.in);
manLevel = in.nextInt();
} else {
managementLevel = manLevel;
break;
}
}
// numEmployees++;
}
#Override
public double calculatePay() {
double percentage = managementLevel * BONUS_PERCENT;
return (1 + percentage/100.0) * annualSalary / 52;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(super.toString());
sb.append("Management Level: ").append(managementLevel).append("\n");
return sb.toString();
}
}
Hourly.Class
import java.util.Scanner;
public class Hourly extends Employee {
private static final double MIN_WAGE = 10;
private static final double MAX_WAGE = 75;
private static final double MIN_HOURS = 0;
private static final double MAX_HOURS = 50;
private double wage;
private double hours;
private String category;
private Scanner in;
private Scanner in2;
private Scanner in3;
private Scanner in4;
public Hourly() {
super();
this.wage = 20;
this.hours= 30;
this.category = "full time";
annualSalary = wage * hours * 52;
}
public Hourly(double wage_, double hours_, String category_) {
while (true) {
if (!validWage(wage_)) {
System.out.print("Invalid wage: ");
in2 = new Scanner(System.in);
wage_ = in2.nextDouble();
} else {
this.wage = wage_;
break;
}
}
while (true) {
if (!validHour(hours_)) {
System.out.print("Invalid hours: ");
in = new Scanner(System.in);
hours_ = in.nextDouble();
} else {
this.hours = hours_;
break;
}
}
while (true) {
if (!validCategory(category_)) {
System.out.print("Invalid category, please enter another category value: ");
category_ = new Scanner(System.in).next();
} else {
this.category = category_;
break;
}
}
annualSalary = wage * hours * 52;
//numEmployees++;
}
public Hourly(String fname, String lname, char gen, int dep, double wage_,double hours_, String category_) {
super.firstName = fname;
super.lastName = lname;
super.gender = gen;
super.dependents = dep;
super.annualSalary = annualSalary;
super.benefit = benefit;
while (true) {
if (!validWage(wage_)) {
System.out.print("Invalid wage : ");
in3 = new Scanner(System.in);
wage_ = in3.nextDouble();
} else {
this.wage = wage_;
break;
}
}
while (true) {
if (!validHour(hours_)) {
System.out.print("Invalid hours : ");
hours_ = new Scanner(System.in).nextDouble();
} else {
this.hours = hours_;
break;
}
}
while (true) {
if (!validCategory(category_)) {
System.out.print("Invalid category, please enter another category value: ");
in4 = new Scanner(System.in);
category_ = in4.next();
} else {
this.category = category_;
break;
}
}
annualSalary = wage * hours * 52;
//numEmployees++;
}
private boolean validHour(double hour) {
return (MIN_HOURS <= hour && hour <= MAX_HOURS);
}
private boolean validWage(double wage) {
return (MIN_WAGE <= wage && wage <= MAX_WAGE);
}
private boolean validCategory(String category) {
String[] categories = {"temp", "part time", "full time"};
for (int i = 0; i < categories.length; i++)
if (category.equalsIgnoreCase(categories[i]))
return true;
return false;
}
public double calculatePay() {
return annualSalary / 52;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(super.toString());
sb.append("Wage: ").append(wage).append("\n");
sb.append("Hours: ").append(hours).append("\n");
sb.append("Category: ").append(category).append("\n");
return sb.toString();
}
}
Benefit.Class
public class Benefit {
private String healthInsurance;
private double lifeInsurance;
private int vacationDays;
public Benefit() {
healthInsurance = "Full";
lifeInsurance = 100;
vacationDays = 5;
}
public Benefit(String health, double life, int vacation) {
setHealthInsurance(health);
setLifeInsurance(life);
setVacation(vacation);
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Health Insurance: ").append(healthInsurance).append("\n");
sb.append("Life Insurance: ").append(lifeInsurance).append("\n");
sb.append("Vacation Days: ").append(vacationDays).append("\n");
return sb.toString();
}
public void setHealthInsurance(String healthInsurance) {
this.healthInsurance = healthInsurance;
}
public String getHealthInsurance() {
return healthInsurance;
}
public void setLifeInsurance(double lifeInsurance) {
this.lifeInsurance = lifeInsurance;
}
public double getLifeInsurance() {
return lifeInsurance;
}
public void setVacation(int vacation) {
this.vacationDays = vacation;
}
public int getVacation() {
return vacationDays;
}
public void displayBenefit() {
this.toString();
}
}
Start by taking a look at How to Make Dialogs...
What you basically want is to use JOptionPane.showInputDialog, which can be used to prompt the use for input...
Yes, there are a few flavours, but lets keep it simply and look at JOptionPane.showInputDialog(Object)
The JavaDocs tells us that...
message - the Object to display
Returns:user's input, or null meaning the user canceled the input
So, from that we could use something like...
String value = JOptionPane.showInputDialog("What is your name?");
if (value != null) {
System.out.println("Hello " + value);
} else {
System.out.println("Hello no name");
}
Which displays...
Now, if we take a look at your code, you could replace the use of scan with...
public static String getInput(String inputType) {
String input = JOptionPane.showInputDialog("Enter the " + inputType + ": ");
return input;
}
As an example...
Now, what I might recommend is creating a simple helper method which can be used to prompt the user in a single line of code, for example...
public class InputHelper {
public static String promptUser(String prompt) {
String input = JOptionPane.showInputDialog(prompt);
return input;
}
}
which might be used something like...
String value = InputHelper.promptUser("Please enter the hours worked");
hours_ = Double.parse(value);
And this is where it get's messy, as you will now need to valid the input of the user.
You could extend the idea of the InputHelper to do automatic conversions and re-prompt the user if the value was invalid...as an idea
It is much easier than you think, if you try. Get used to reading the Java API.
http://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html
Even has examples.
String input;
JOptionPane jop=new JOptionPane();
input=jop.showInputDialog("Question i want to ask");
System.out.println(input);

Getting error: non-static method getTotalPlayers() cannot be referenced from a static context

I don't see what I'm doing wrong here or how anything here is static without it being declared that way. I just need to be pointed in the right direction here.
Test code:
public class PaintballPlayerTest
{
//Test program for PaintballPlayer assignment
public static void main (String [] args)
{
//Part 1 check constructor & toString --(make sure ID is working too)
PaintballPlayer sheldon = new PaintballPlayer ("Sheldon", "Lee", "Cooper");
PaintballPlayer leonard = new PaintballPlayer ("Leonard", "Hofstadter");
PaintballPlayer amy = new PaintballPlayer ("Amy", "Farrah", "Fowler");
System.out.println(sheldon);
System.out.println(leonard);
//Part 2 test getTotalPlayer --should be 3
System.out.println("The team has this many players " + PaintballPlayer.getTotalPlayers());
My code:
import java.util.*;
public class PaintballPlayer
{
private String firstName, middleName, lastName;
private String secFirst, secLast;
private int id;
private int count;
private static int totalPlayers;
private int playerID;
private int players;
public PaintballPlayer(String first, String middle, String last)
{
count = 0;
id = totalPlayers++;
players = count++;
firstName = first;
middleName = middle;
lastName = last;
}
public PaintballPlayer(String f, String l)
{
this (f,"",l);
id = count++;
}
public PaintballPlayer()
{
totalPlayers++;
}
public static int getTotalPlayers()
{
return totalPlayers;
}
public String toString()
{
String name;
String n;
name = firstName + " " + middleName + " " + lastName;
return name;
}
public int getPlayerID()
{
playerID = count;
return playerID;
}
}
Again, my problem is with the getTotalPlayers() method.
EDIT: This is my edited code applying the fixes provided. Thank you!
getTotalPlayers() is not a static method, so you need an instance of PaintballPlayer to call this method.
If you want to store the total players inside PaintballPlayer, you need an static attribute (same reference for all instances):
class PaintballPlayer {
private static int totalPlayers;
public PaintballPlayer() {
totalPlayers++;
}
public static int getTotalPlayers() {
return totalPlayers;
}
}
On your code there are a few problems, on the constructor #1
public PaintballPlayer(String first, String middle, String last)
{
count = 0;
players = 0;
id = count++;
players = count++;
firstName = first;
middleName = middle;
lastName = last;
}
The variables players and count are being reseted while the variable count is increased two times.
And in the constructor #2 the problem is worst:
public PaintballPlayer(String f, String l)
{
this (f,"",l);
id = count++;
players = count++;
}
because you are increasing the value of count two times besides the 2 times in the original constructor, so four times in total.
Once u have done what Devon Freese says u will have to modify the constructor of PaintballPlayer
public PaintballPlayer(String first, String middle, String last)
{
id = totalPlayers++;
firstName = first;
middleName = middle;
lastName = last;
}
Try this.
import java.util.*;
public class PaintballPlayer {
private String firstName, middleName, lastName;
private String secFirst, secLast;
private int id;
private static int count;
private static int totalPlayers;
private int playerID;
private static int players;
public PaintballPlayer(String first, String middle, String last) {
count++;
id = count;
players = count;
firstName = first;
middleName = middle;
lastName = last;
}
public PaintballPlayer(String f, String l) {
this(f, "", l);
id = count;
players = count;
}
public String toString() {
String name = firstName + " " + middleName + " " + lastName;
return name;
}
public static int getTotalPlayers() {
totalPlayers = players;
return totalPlayers;
}
public int getPlayerID() {
playerID = count;
return playerID;
}
}
class PaintballPlayerTest {
//Test program for PaintballPlayer assignment
public static void main(String[] args) {
//Part 1 check constructor & toString --(make sure ID is working too)
PaintballPlayer sheldon = new PaintballPlayer("Sheldon", "Lee", "Cooper");
PaintballPlayer leonard = new PaintballPlayer("Leonard", "Hofstadter");
PaintballPlayer amy = new PaintballPlayer("Amy", "Farrah", "Fowler");
System.out.println(sheldon);
System.out.println(leonard);
//Part 2 test getTotalPlayer --should be 3
System.out.println("The team has this many players " + PaintballPlayer.getTotalPlayers());
}
}

Categories