I'm new to Java, and i'm trying to create an automatic working shift schedule.
I want the code to mix four different employees to handle a morning shift and afternoon shift every work day.
I have made some code that just pick a random employee into a shift:
import java.util.Arrays;
import java.util.Random;
public class CreateNewShift {
public static void main(String[] args) {
int startWeek = 30; //Which week would start from?
int endWeek = 32; //which week will you end on?
generateShift(startWeek, endWeek);
}
private static void generateShift(int startWeek, int endWeek) {
String Employees[] = {"Employee1", "Employee2", "Employee3", "Employee4"};
String morningShift;
String afternoonShift;
for (int x = 0; x <= (endWeek - startWeek); x++) { //This is counting the number of weeks
System.out.println("\nWeek: " + (startWeek+x));
for (int i = 1; i <= 5; i++) { //this is finding the next working shift day
morningShift = p.chooseRandomEmployee(Employees);
afternoonShift = p.chooseRandomEmployee(Employees);
if (i == 1) {
System.out.println("Mon: " + morningShift + " + " + afternoonShift);
}
else if (i == 2) {
System.out.println("Tue: " + morningShift + " + " + afternoonShift);
}
else if (i == 3) {
System.out.println("Wed: " + morningShift + " + " + afternoonShift);
}
else if (i == 4) {
System.out.println("Thu: " + morningShift + " + " + afternoonShift);
}
else {
System.out.println("Fri: " + morningShift + " + " + afternoonShift);
}
}
}
}
public class Employee {
public String chooseRandomEmployee(String[] Employees) {
Random r = new Random();
int randomNumber = r.nextInt(Employees.length);
return Employees[randomNumber];
}
}
However, I now want the code to handle more restictions.
So i'm currently trying to add the option for the employees to choose some specific days that they dont want to have a shift. I have done this by adding this code to the Employee class:
public class Employee {
boolean monShift = true;
boolean tueShift = true;
boolean wedShift = true;
boolean thuShift = true;
boolean friShift = true;
public String chooseRandomEmployee(String[] Employees) {
Random r = new Random();
int randomNumber = r.nextInt(Employees.length);
return Employees[randomNumber];
}
}
And then i had tried to create new objects in my main class:
private static void generateShift(int startWeek, int endWeek) {
Employee Employee1 = new Employee("Employee1");
Employee Employee2 = new Employee("Employee2");
Employee Employee3 = new Employee("Employee3");
Employee Employee4 = new Employee("Employee4");
String Employees[] = {"Employee1", "Employee2", "Employee3", "Employee4"};
String morningShift;
String afternoonShift;
....
Quetions:
How can I improve my code in the Employee class to do a check if the random chosen employee have
monShift = true;
I have tried something like this, but i know it will not work, (and does not work either):
import java.util.Random;
public class Employee {
public String chooseRandomEmployee(String[] Employees) {
Random r = new Random();
int randomNumber = r.nextInt(Employees.length);
**if (("Employee" + randomNumber).monShift == false) {**
// Go back and try find a new random employee
}
else {
return Employees[randomNumber];
}
}
}
So i need a way to make my code dynamic to know which object (employee) it has to check if they are available that specific day or not.
Feel free to ask for a deepening if my question is not clear.
Since this i my first question on this forum, I also appriciate feedback if my question and thoughts are too long, or any other comments.
I dont think that putting the chooseRandomEmployee() function inside the Employee object is a good idea beacuse is not a part of the employee, is not an "action" of it. I think you shiudl put it outside but I want to respect your decision so shoudl check the do while loop.
import java.util.Random;
public class Employee {
public String chooseRandomEmployee(String[] Employees) {
int randomNumber;
do {
//Generate a new random number
Random r = new Random();
randomNumber = r.nextInt(Employees.length);
//The line under is the same that saying "If monSift == false return to
//the beginning and start again generating a new number"
} while ("Employee" + randomNumber).monShift == false);
return Employees[randomNumber];
}
}
This is a probable answer of my question in stack overflow.Integer to word conversion
At first I have started with dictionary. Then I came to know it is obsolete. So now I use Map instead of dictionary. My code is work well for number till Millions. But the approach I take here is a naive approach. The main problem of this code is
First: Huge numbers of variable use
2nd: Redundant code block as per program requirement
3rd: Multiple if else statement
I am thinking about this problems
Solution for 2nd problem: using user define function or macros to eliminate redundant code block
Solution for 3rd problem: Using switch case
My code:
public class IntegerEnglish {
public static void main(String args[]){
Scanner in=new Scanner(System.in);
System.out.println("Enter the integer");
int input_number=in.nextInt();
Map<Integer,String> numbers_converter = new HashMap<Integer,String>();
Map<Integer,String> number_place = new HashMap<Integer,String>();
Map<Integer,String> number_2nd = new HashMap<Integer,String>();
numbers_converter.put(0,"Zero");
numbers_converter.put(1,"One");
numbers_converter.put(2,"Two");
numbers_converter.put(3,"Three");
numbers_converter.put(4,"Four");
numbers_converter.put(5,"Five");
numbers_converter.put(6,"Six");
numbers_converter.put(7,"Seven");
numbers_converter.put(8,"Eight");
numbers_converter.put(9,"Nine");
numbers_converter.put(10,"Ten");
numbers_converter.put(11,"Eleven");
numbers_converter.put(12,"Twelve");
numbers_converter.put(13,"Thirteen");
numbers_converter.put(14,"Fourteen ");
numbers_converter.put(15,"Fifteen");
numbers_converter.put(16,"Sixteen");
numbers_converter.put(17,"Seventeen");
numbers_converter.put(18,"Eighteen");
numbers_converter.put(19,"Nineteen");
number_place.put(3,"Hundred");
number_place.put(4,"Thousand");
number_place.put(7,"Million");
number_place.put(11,"Billion");
number_2nd.put(2,"Twenty");
number_2nd.put(3,"Thirty");
number_2nd.put(4,"Forty");
number_2nd.put(5,"Fifty");
number_2nd.put(6,"Sixty");
number_2nd.put(7,"Seventy");
number_2nd.put(8,"Eighty");
number_2nd.put(9,"Ninty");
if(input_number== 0){
System.out.println("zero");
}
else if(input_number>0 && input_number<19){
System.out.println(numbers_converter.get(input_number));
}
else if(input_number>19 && input_number<100){
int rem=input_number%10;
input_number=input_number/10;
System.out.print(number_2nd.get(input_number));
System.out.print(numbers_converter.get(rem));
}
else if(input_number==100){
System.out.println(number_place.get(3));
}
else if(input_number>100 && input_number<1000){
int reminder=input_number%100;
int r1=reminder%10;
int q1=reminder/10;
int quot=input_number/100;
System.out.print(numbers_converter.get(quot) + "hundred");
if(reminder>0 && reminder<20){
System.out.print(numbers_converter.get(reminder));
}
else{
System.out.println(number_2nd.get(q1) + numbers_converter.get(r1));
}
}
else if(input_number==1000){
System.out.println(number_place.get(4));
}
else if(input_number>1000 && input_number<10000){
int rem=input_number%100;
int rem_two=rem%10;
int quotient =rem/10;
input_number=input_number/100;
int thousand=input_number/10;
int hundred = input_number%10;
System.out.print(numbers_converter.get(thousand) + "thousand" + numbers_converter.get(hundred)+ " hundred");
if(rem >0 && rem<20){
System.out.print(numbers_converter.get(rem));
}
else if(rem >19 && rem <100){
System.out.print(number_2nd.get(quotient) + numbers_converter.get(rem_two));
}
}
else if(input_number>10000 && input_number<1000000000){
//Say number 418,229,356
int third_part=input_number%1000;//hold 356
input_number=input_number/1000;//hold 418,229
int sec_part=input_number%1000;//hold 229
input_number=input_number/1000;// hold 418
int rem_m=third_part%100;//hold 56
int rem_m1=rem_m%10;//hold 6
int rem_q=rem_m/10;// hold 5
int q_m=third_part/100;// hold 3
int sec_part_rem=sec_part%100;// hold 29
int sec_part_rem1=sec_part_rem%10;//9
int sec_part_q=sec_part_rem/10;//hold 2
int sec_q=sec_part/100;// hold 2
int input_q=input_number/100;// hold 4
int input_rem=input_number%100;//hold 18
int input_q_q=input_rem/10;//hold 1
int input_rem1=input_rem%10;// hold 8
System.out.print(numbers_converter.get(input_q) + " hundred ");
if(input_rem>0 && input_rem<20){
System.out.print(numbers_converter.get(input_rem)+ " Million ");
}
else{
System.out.print(number_2nd.get(input_q_q) + " " + numbers_converter.get(input_rem1) + " Million ");
}
System.out.print(numbers_converter.get(sec_q) + " hundred ");
if(sec_part_rem >0 && sec_part_rem<20){
System.out.println(numbers_converter.get(sec_part_rem) + " thousand ");
}
else{
System.out.print(number_2nd.get(sec_part_q) + " " + numbers_converter.get(sec_part_rem1) + " thousand ");
}
System.out.print(numbers_converter.get(q_m) + " hundred ");
if(rem_m>0 && rem_m<20){
System.out.print(numbers_converter.get(rem_m));
}
else{
System.out.print(number_2nd.get(rem_q) + " " + numbers_converter.get(rem_m1));
}
}
}
}
Redundant Code Blocks
int rem=input_number%100;
int rem_two=rem%10;
int quotient =rem/10;
input_number=input_number/100;
int thousand=input_number/10;
int hundred = input_number%10;
This type of code block used almost every where. Taking a number divide it with 100 or 1000 to find out the hundred position then then divide it with 10 to find out the tenth position of the number. Finally using %(modular division) to find out the ones position.
How could I include user define function and switch case to minimize the code block.
Instead of storing the results in variables, use a method call:
int remainder100(int aNumber) {
return aNumber % 100;
}
int remainder10(int aNumber) {
return aNumber % 10;
}
...etc.
System.out.println(numbers_converter.get(remainder100(input_number)));
About 3rd problem: I wouldn't use switch ... case, too many cases.
Instead, take advantage that numbering repeats itself every 3 digits. That means the pattern for thousands and millions is the same (and billions, trillions, etc).
To do that, use a loop like this:
ArrayList<String> partialResult = new ArrayList<String>();
int powersOf1000 = 0;
for (int kiloCounter = input_number; kiloCounter > 0; kiloCounter /= 1000) {
partialResult.add(getThousandsMilionsBillionsEtc(powersOf1000++);
partialResult.add(convertThreeDigits(kiloCounter % 1000));
}
Then you can print out the contents of partialResult in reverse order to get the final number.
I'd suggest you break your single main method down into a couple of classes. And if you haven't already create a few unit tests to allow you to easily test / refactor things. You'll find it quicker than starting the app and reading from stdin.
You'll find it easier to deal with the number as a string. Rather than dividing by 10 all the time you just take the last character of the string. You could have a class that does that bit for you, and a separate one that does the convert.
Here's what I came up with, but I'm sure it can be improved. It has a PoppableNumber class which allows the last character of the initial number to be easily retrieved. And the NumberToString class which has a static convert method to perform the conversion.
An example of a test would be
#Test
public void Convert102356Test() {
assertEquals("one hundred and two thousand three hundred and fifty six", NumberToString.convert(102356));
}
And here's the NumberToString class :
import java.util.HashMap;
import java.util.Map;
public class NumberToString {
// billion is enough for an int, obviously need more for long
private static String[] power3 = new String[] {"", "thousand", "million", "billion"};
private static Map<String,String> numbers_below_twenty = new HashMap<String,String>();
private static Map<String,String> number_tens = new HashMap<String,String>();
static {
numbers_below_twenty.put("0","");
numbers_below_twenty.put("1","one");
numbers_below_twenty.put("2","two");
numbers_below_twenty.put("3","three");
numbers_below_twenty.put("4","four");
numbers_below_twenty.put("5","five");
numbers_below_twenty.put("6","six");
numbers_below_twenty.put("7","seven");
numbers_below_twenty.put("8","eight");
numbers_below_twenty.put("9","nine");
numbers_below_twenty.put("10","ten");
numbers_below_twenty.put("11","eleven");
numbers_below_twenty.put("12","twelve");
numbers_below_twenty.put("13","thirteen");
numbers_below_twenty.put("14","fourteen ");
numbers_below_twenty.put("15","fifteen");
numbers_below_twenty.put("16","sixteen");
numbers_below_twenty.put("17","seventeen");
numbers_below_twenty.put("18","eighteen");
numbers_below_twenty.put("19","nineteen");
number_tens.put(null,"");
number_tens.put("","");
number_tens.put("0","");
number_tens.put("2","twenty");
number_tens.put("3","thirty");
number_tens.put("4","forty");
number_tens.put("5","fifty");
number_tens.put("6","sixty");
number_tens.put("7","seventy");
number_tens.put("8","eighty");
number_tens.put("9","ninty");
}
public static String convert(int value) {
if (value == 0) {
return "zero";
}
PoppableNumber number = new PoppableNumber(value);
String result = "";
int power3Count = 0;
while (number.hasMore()) {
String nextPart = convertUnitTenHundred(number.pop(), number.pop(), number.pop());
nextPart = join(nextPart, " ", power3[power3Count++], true);
result = join(nextPart, " ", result);
}
if (number.isNegative()) {
result = join("minus", " ", result);
}
return result;
}
public static String convertUnitTenHundred(String units, String tens, String hundreds) {
String tens_and_units_part = "";
if (numbers_below_twenty.containsKey(tens+units)) {
tens_and_units_part = numbers_below_twenty.get(tens+units);
}
else {
tens_and_units_part = join(number_tens.get(tens), " ", numbers_below_twenty.get(units));
}
String hundred_part = join(numbers_below_twenty.get(hundreds), " ", "hundred", true);
return join(hundred_part, " and ", tens_and_units_part);
}
public static String join(String part1, String sep, String part2) {
return join(part1, sep, part2, false);
}
public static String join(String part1, String sep, String part2, boolean part1Required) {
if (part1 == null || part1.length() == 0) {
return (part1Required) ? "" : part2;
}
if (part2.length() == 0) {
return part1;
}
return part1 + sep + part2;
}
/**
*
* Convert an int to a string, and allow the last character to be taken off the string using pop() method.
*
* e.g.
* 1432
* Will give 2, then 3, then 4, and finally 1 on subsequent calls to pop().
*
* If there is nothing left, pop() will just return an empty string.
*
*/
static class PoppableNumber {
private int original;
private String number;
private int start;
private int next;
PoppableNumber(int value) {
this.original = value;
this.number = String.valueOf(value);
this.next = number.length();
this.start = (value < 0) ? 1 : 0; // allow for minus sign.
}
boolean isNegative() {
return (original < 0);
}
boolean hasMore() {
return (next > start);
}
String pop() {
return hasMore() ? number.substring(--next, next+1) : "";
}
}
}
Im working on a school project where I have to implement recursion with arrays and I have done everything but im getting a null error when I am running it. The error points to the Recursion class on Line:
result += packetList[n].idNumber + " " + packetList[n].weight + " " + packetList[n].Destination;
I tried tracing the recursion method to see if it would actually make sense and its looks solid but i'm still getting a null error.
Recursion Class:
import java.io.*;
public class Recursion
{
public String toString(Packet[] packetList, int n)
{
String result = "";
if (n < 0)
{
return result;
}
result += packetList[n].idNumber + " " + packetList[n].weight + " " + packetList[n].Destination; // Uncomment if you want the values from last-to-first (last index to 0 index)
result += toString(packetList, n-1);
//result += packetList[n].idNumber + " " + packetList[n].weight + " " + packetList[n].Destination; // Uncomment if you want the values from first-to-last (0 index to last index)
return result;
}
}
Packet Class
public class Packet
{
public int idNumber;
public double weight;
public String Destination;
public Packet(int id, double w, String D)
{
idNumber = id;
weight = w;
Destination = D;
}
public boolean isHeavy()
{
if (weight > 10)
return true;
else
return false;
}
public String toString()
{
return idNumber + " " + weight + " " + Destination;
}
public double getWeight()
{
return weight;
}
public String getDestination()
{
return Destination;
}
}
Test Class
import java.io.*;
import java.util.*;
import java.util.Scanner;
public class TestPackages
{
public static void main (String[] args) throws IOException
{
Packet[] packetList = new Packet[100];
int idNumber;
double weight;
String Destination;
Scanner fileInput;
fileInput = new Scanner (new File("packetData.txt"));
int counter = 0;
while (fileInput.hasNextLine())
{
idNumber = fileInput.nextInt();
weight = fileInput.nextDouble();
Destination = fileInput.nextLine();
Packet myPacket = new Packet (idNumber, weight, Destination);
packetList[counter++] = myPacket;
}
Recursion recursion = new Recursion();
System.out.println(recursion.toString(packetList, packetList.length - 1));
recursion.displayHeavyPackages(packetList, packetList.length - 1);
recursion.displayPacketsToDest(packetList, packetList.length - 1, "CT");
recursion.countPacketsToDest(packetList, packetList.length - 1, "CT");
}
}
It looks like you are sending the length of the array to your toString() function, but it might not have the 100 elements initialized, try sending your ´counter´ instead :
System.out.println(recursion.toString(packetList, counter-1))
Please verify that packetData.txt has exactly 100 lines otherwise the program will throw a null pointer Exception.
The displayHeavyPackage method should validate if n==0 to avoid Array Index Out Bound exception
displayHeavyPackage
public void displayHeavyPackages(Packet[] packetList, int n) {
if (packetList[n].isHeavy() == true && n>0) {
System.out.println(packetList[n]); displayHeavyPackages(packetList, n-1);
} else if (packetList[n].isHeavy() == true && n==0){
System.out.println(packetList[n]);
}
}
My final suggestion is try to debug your code, it will help a lot to clarify the root cause of the exceptions.
I spent several hours working on this and even had my professor look at this and it seems to be printing out just the last element in the for loop. It seems to allows me to add the data structure information and initialize the array queue but it only print out the last element. Here is the sufficient code to assist with the question.
static int MAX;
static final int amount = 6;
static boolean [] openflag;
static queue [] Clinic;
static String [] Doctor;
final static String HEADING = "The clinic moniter of Dylan Rychlik";
public static void Listpaitents( ) {
Paitent[] array;
int queuechoice;
JOptionPane.showMessageDialog(null, "Which doctor would you like to
print?");
String InputString = JOptionPane.showInputDialog(null,Doctor, HEADING,
JOptionPane.QUESTION_MESSAGE);
queuechoice = Integer.parseInt(InputString);
if (openflag[queuechoice -1 ] == false){
JOptionPane.showMessageDialog(null, "Sorry, that doctor is not aviable");
}
else {
//Paitent[] array = null;
int limit;
limit = Clinic[queuechoice -1 ].getSize();
array = Clinic[queuechoice -1 ].toArray();
System.out.println(array[0]);
System.out.println(array[1].Print());
System.out.println(array[2].Print());
//int size = Clinic[queuechoice -1].getSize();
//System.out.println(limit);
int x; String out = " Members of the list are: \n";
// boolean exit = false;
for(x = 0; x < limit; x++) {
out += array[x].Print() + "\n";
//System.out.println(out);
// System.out.println(Clinic[queuechoice].toString() + "\n");
}
System.out.println(limit);
JOptionPane.showMessageDialog(null,out);
}
}
Here this is the array() method in the queue clas
public Paitent[] toArray() {
int x;
Paitent[] Array = new Paitent[Length];
queuenode Current = rear;
for (x = 1; ((Current != null) && (x <= Length));x++) {
Array[x-1] = new Paitent();
Array[x-1].update(Current.info);
Current = Current.next;
// System.out.println( Array[x-1].Print());
}
//System.out.println( Array[x-1].Print());
return Array;
}
Any finally here this is the print method
public String Print() {
String outputString;
outputString = "Paitent: " + "-" + name + "\n" + " Telephone number
telephone + " ID " + ID;
return outputString;
}
Any help you can give is really appreciated. I really have spent hours analyzing the code to come up a solution. Its a bulky program.
Right now I'm working on a method for comparing the scores of athletes in the olympics. So far I've had little trouble, however now I've reached a point where i need to compare two objects (athletes) scores and I'm not sure how to do it. This is my code for the Olympic class:
// A program using the Athlete class
public class Olympics {
public static void main(String args[]) {
System.out.println("The leader is " + Athlete.leader() +
", with a score of " + Athlete.leadingScore());
Athlete meryl = new Athlete("Meryl Davis", "U.S.");
meryl.addScore(75);
System.out.println(meryl);
Athlete tessa = new Athlete("Tessa Virtue", "Canada");
System.out.println(tessa);
System.out.println(); // blank line
tessa.addScore(50);
System.out.println(tessa);
System.out.println(meryl);
System.out.println("The leader is " + Athlete.leader() +
", with a score of " + Athlete.leadingScore());
System.out.println(); // blank line
tessa.addScore(100);
meryl.addScore(65);
System.out.println(tessa);
System.out.println(meryl);
System.out.println("The leader is " + Athlete.leader() +
", with a score of " + Athlete.leadingScore());
System.out.println(); // blank line
tessa.addScore(20);
System.out.println("Tessa's final score is " + tessa.getScore());
meryl.move("France");
System.out.println(meryl);
} // end main
} // end class Olympics
And this is the constructor class "Athlete":
public class Athlete {
private String name;
private String country;
protected int score;
public static int leadScore;
public Athlete(String athName, String athCountry) {
this.name = athName;
this.country = athCountry;
score = 0;
if (score < 1) {
System.out.println("Score cannot be lower than 1");
}
}
public int addScore(int athScore) {
score += athScore;
return score;
}
public static String leader(){
//TODO
}
public static int leadingScore() {
//MUST COMPARE BOTH ATHLETES
}
public int getScore(){
return score;
}
public void move(String newCountry) {
country = newCountry;
}
public String toString() {
return name + ": " + "from " + country + ", current score " + score;
}
}
So what I'm trying to do is have the program check Meryl's score compared to Tessa's and return that Athlete's score in leadingScore() and, using that athlete, return a leader(). Any help is appreciated! Thanks.
The function must take the two Athletes you're comparing as the parameters for this to work
public static int leadingScore(Athlete a1, Athlete a2) {
if (a1.getScore() < a2.getScore()) {
// do stuff
}
}
The lead score should not be in the athlete class, but rather in main () because one instance of an Athlete class would not know of other instances unless you put a self-referential list inside the class. Similarly, leadingScore should be in main ().
It or main can call each athlete and compare:
int merylScore = meryl.getScore ();
int tessaScore = tessa.getScore ();
int leadingScore = 0;
String leaderName = "";
if (merylScore > tessaScore) {
leadingScore = merylScore;
leaderName = meryl.getName ();
} else if (tessaScore > merylScore) {
leadingScore = tessaScore;
leaderName = tessa.getName ();
} else {
leadingScore = merylScore;
leaderName = "a tie between Meryl and Tessa";
}
System.out.println ("The leader is " + leaderName + ", with a score of " + leadingScore);
You should consider using a "collection". Use an array, a list ... or even a sorted list.
Stored your individual objects in the collection, then traverse the collection to find the highest score.
For example:
// Create athlete objects; add each to list
ArrayList<Athlete> athletes = new ArrayList<Athlete>();
Athlete meryl = new Athlete("Meryl Davis", "U.S.");
meryl.addScore(75);
...
athletes.add(meryl);
Athlete tessa = new Athlete("Tessa Virtue", "Canada");
...
athletes.add(tessa );
// Go through the list and find the high scorer
Athlete highScorer = ...;
for (Athlete a : athletes) {
if (highScorer.getScore() < a.getScore())
highScorer = a;
...
}
System.out.println("High score=" + highScorer.getScore());
Here's a good tutorial:
http://www.vogella.com/tutorials/JavaCollections/article.html