Having some problems with this program. I am new to Java and am trying to make a league scheduler. I have got to the point where the user can enter a number of teams needed, expected league start date and end date. Once the user selects the end date, a number of rounds are suggested to the user as this would be the number of weeks the league would need to go on for. Currently though, when the league generates, the dates print altogether, my question is how can I can the dates to print like - "round 1 05/06/2018". Also, how can I change my program so an odd number can be accepted, similar to a 'bye'?
I apologise for my ill knowledge of the subject, I have included a snippet of my code and a picture of my GUI so it gives more context.
Many thanks,
Jack
void cyclicRoll(int cycle[], int teams) {
int tmp = cycle[1];
for(int i=1;i<teams-1;i++) {
int pr = cycle[i+1];
cycle[i+1] = tmp;
tmp = pr;
}
cycle[1] = tmp;
}
void scheduleTournament(int teams, int round) {
if (((teams%2 != 0) && (round != teams - 1))||(teams <= 0))
throw new IllegalArgumentException();
int[] cycle = new int[teams];
int n = teams /2;
for (int i = 0; i < n; i++) {
cycle[i] = i + 1;
cycle[teams - i - 1] = cycle[i] + n;
}
Date startDate = (jXDatePicker1.getDate());
Date endDate = (jXDatePicker2.getDate());
LocalDate dates = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate firstdate = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
DayOfWeek dayOfWeeek = dates.getDayOfWeek();
LocalDate datee = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
String listrep ="";
String firstDateToPrint = firstdate.toString();
while (!dates.equals(datee)) {
jTextArea1.removeAll();
if(dayOfWeeek == dayOfWeeek) {
dates = dates.plusDays(7);
}
String[] Itdates = {dates.toString()
};
for(String replacement : Itdates) {
if ("".equals(listrep)) {
listrep += replacement;
} else {
listrep += ", \n" + replacement ;
}
}
}
jTextArea1.append(firstDateToPrint + "\n");
jTextArea1.append(listrep);
for(int d = 1; d <= round; d++)
{
jTextArea1.append(String.format("Round %d\n", d ));
for (int i = 0; i < n; i++)
{
jTextArea1.append(String.format("team %d - team %d\n",cycle[i],cycle[teams - i - 1]));
}
//Roll the cycle keeping the first constant
cyclicRoll(cycle,teams);
}
}
String ref;
String teams;
String rounds;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextArea1.selectAll();
jTextArea1.replaceSelection("");
teams = jTextField1.getText();
int teamsToEnter = Integer.parseInt(teams);
rounds = jTextField2.getText();
int roundsToEnter = Integer.parseInt(rounds);
ref = jTextField3.getText();
jTextArea1.append("Ref "+ref + "\n");
scheduleTournament(jTextField2,roundsToEnter);
}
Related
I'm trying to get the code to search for a songs that were made in a specific year
I've tried implementing my own binary search code but it's not working and instead asks for an input when I never asked for an input
Class:
public class MusicV3
{
// instance variables
private int year;
private String title;
private String artist;
// Constructor for objects of class Music
public MusicV3(String t, int y, String a)
{
// initialize instance variables
title = t;
year = y;
artist = a;
}
public String getTitle()
{
return title;
}
public void setTitle(String t)
{
title = t;
}
public String getArtist()
{
return artist;
}
public void setArtist(String a)
{
artist = a;
}
public int getYear()
{
return year;
}
public void setTitle(int y)
{
year = y;
}
public String toString()
{
String str = String.format( "%-25s %4d %-20s ", title, year , artist);
return str;
}
}
Tester class:
public class MusicV3Tester
{
public static void main(String[]args)
{
int find = 0;
MusicV3[] songs = new MusicV3[10];
MusicV3[] sortedSongs = new MusicV3[songs.length];
songs[0] = new MusicV3("Sugar", 2014, "Maroon 5");
songs[1] = new MusicV3("Mercy", 2016, "Shawn Mendes");
songs[2] = new MusicV3("Shape of You", 2017, "Ed Sheeran");
songs[3] = new MusicV3("Photograph", 2014, "Ed Sheeran");
songs[4] = new MusicV3("Closer", 2016, "The Chainsmokers");
songs[5] = new MusicV3("Galway Girl", 2017, "Ed Sheeran");
songs[6] = new MusicV3("Counting Stars", 2013, "OneRepublic");
songs[7] = new MusicV3("7 Years", 2015, "Lukas Graham");
songs[8] = new MusicV3("Night Changes", 2014, "One Direction");
songs[9] = new MusicV3("What Makes You Beautiful", 2011, "One Direction");
printSongs(songs);
System.out.println();
sortedSongs = sortBySong(songs);
System.out.println("Song list sorted by songs:");
//printSongs(sortedSongs);
System.out.println();
System.out.println("Searching for the song: Paris");
find = findSong(songs, "Paris");
if(find != -1){
System.out.println("We found Paris in the song list: ");
System.out.println(sortedSongs[find]);
}
else
System.out.println("Paris is not in the song list");
System.out.println();
System.out.println("Searching for the song: Sugar");
find = findSong(songs, "Sugar");
if(find != -1){
System.out.println("We found Sugar in the song list: ");
System.out.println(sortedSongs[find]);
}
else
System.out.println("Sugar is not in the song list");
System.out.println();
sortedSongs = sortByYear(songs);
System.out.println("Song list sorted by year:");
//printSongs(sortedSongs);
System.out.println();
System.out.println("Searching for the year: 2000");
find = findYear(songs, 2000);
if(find != -1){
System.out.println("We found songs made in the year 2000 in the song list: ");
System.out.println(sortedSongs[find]);
}
else
System.out.println("Songs made in the year 2000 are not in the song list");
System.out.println();
System.out.println("Searching for the year: 2014");
findYear(songs, 2014);
if(find != -1){
System.out.println("We found songs made in the year 2014 in the song list: ");
System.out.println(sortedSongs[find]);
}
else
System.out.println("Songs made in the year 2014 are not in the song list");
System.out.println();
sortedSongs = sortByArtist(songs);
System.out.println("Song list sorted by artist:");
//printSongs(sortedSongs);
System.out.println();
System.out.println("Searching for the artist: Sia");
findArtist(songs, "Sia");
System.out.println();
System.out.println("Searching for the artist: Ed Sheeran");
findArtist(songs, "Ed Sheeran");
System.out.println();
}
public static void printSongs(MusicV3[] s)
{
System.out.println("Song Year Artist");
System.out.println("-------------------------------------------------------");
for(int i = 0; i < s.length; i++)
System.out.println(s[i]);
}
public static MusicV3[] sortBySong(MusicV3 [] songs){
MusicV3[] sortedList = songs;
int i;
int k;
int posmax;
MusicV3 temp;
for ( i = songs.length - 1 ; i >= 0 ; i-- )
{
posmax = 0;
for ( k = 0 ; k <= i ; k++ )
{
if (songs[k].getTitle().compareTo(songs[posmax].getTitle()) > 0)
posmax = k;
}
temp = songs[i];
songs[i] = songs[posmax];
songs[posmax] = temp;
}
return sortedList;
}
public static MusicV3[] sortByYear(MusicV3 [] movies){
MusicV3[] sortedList = movies;
int i;
int k;
int posmax;
MusicV3 temp;
for ( i = movies.length - 1 ; i >= 0 ; i-- )
{
posmax = 0;
for ( k = 0 ; k <= i ; k++ )
{
if (movies[k].getYear()> movies[posmax].getYear())
posmax = k;
}
temp = movies[i];
movies[i] = movies[posmax];
movies[posmax] = temp;
}
return sortedList;
}
public static MusicV3[] sortByArtist(MusicV3 [] songs){
MusicV3[] sortedList = songs;
int i;
int k;
int posmax;
MusicV3 temp;
for ( i = songs.length - 1 ; i >= 0 ; i-- )
{
posmax = 0;
for ( k = 0 ; k <= i ; k++ )
{
if (songs[k].getArtist().compareTo(songs[posmax].getArtist()) > 0)
posmax = k;
}
temp = songs[i];
songs[i] = songs[posmax];
songs[posmax] = temp;
}
return sortedList;
}
public static int findSong( MusicV3[] songs, String song){
int high = songs.length;
int low = -1;
int probe;
while ( high - low > 1 )
{
probe = ( high + low ) / 2;
if (songs[probe].getTitle().compareTo(song) > 0)
high = probe;
else
low = probe;
}
if ( low >= 0 && songs[low].getTitle().compareTo(song) == 0){
return low;
}
else{
return -1;
}
}
public static int findYear(MusicV3[] songs, int year){
int high = songs.length - 1;
int low = 0;
int probe;
while (low <= high)
{
probe = ( high + low ) / 2;
if (songs[probe].getYear() == year)
return probe;
if(songs[probe].getYear() > year)
low = probe;
else
low = probe + 1;
}
return -1;
}
public static void findArtist(MusicV3[] s, String artist)
{
int found = 0;
for(int i = 0; i < s.length; i++){
if (s[i].getArtist().compareTo(artist) == 0)
{
System.out.println(s[i]);
found++;
}
}
if (found == 0)
{ // we have not found the location
System.out.println("There are no songs on the songs list made in the year " + artist);
System.out.println();
}
else
{
System.out.print("There were " + found + " listings for " + artist);
System.out.println();
}
}
}
Ignore the song and artist search, those I can do and have no problems with but with the year search, it's not working correctly since it is supposed to correctly print all of the songs that are in the specific year giving (2000 and 2014) but it isn't and instead is not working at all and asking for an input for some reason. This is my first time doing a binary search so i'm pretty new to this.
How can you possibly show all of them when you are only returning the index of one of them (and not even the first one at that) ?
Try returning a list of results. or a Pair<int, int> of indexes begin and end
what I am trying to do is create an itinerary of flight paths using JGraphT. The problem I am facing is converting the string times I have set into actual times that I can then do calculations over multiple days i.e. if a flight leaves at 16.00 and arrives at 18.30 but then the connecting flight leaves at 14.00 and arrives at the final destination at 16.00 it will have been 24 hours (i.e. one day). I am lost in this as I have tried to parse the string to a date in the Flight class and also used The simple date format which is causing errors.
My code as follows;
Flight3.java
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
import org.jgrapht.alg.DijkstraShortestPath;
import org.jgrapht.graph.DefaultWeightedEdge;
import org.jgrapht.graph.SimpleDirectedWeightedGraph;
public class Flight3
{
private static ArrayList<String[]> myEdges;
private static ArrayList<Flight> flight;
public Flight3()
{
}
public static void main(String [] args)
{
myEdges = new ArrayList<String[]>();
flight = new ArrayList<Flight>();
SimpleDirectedWeightedGraph<String, DefaultWeightedEdge> Graph = createGraph();
System.out.println("Airlines!");
Scanner sc = new Scanner(System.in);
System.out.println("Enter the airport you wish to fly from");
String startVertex = sc.nextLine();
while(!Graph.containsVertex(startVertex))
{
System.out.println("Sorry, that airport does not exist. Please select another;");
startVertex = sc.nextLine();
}
System.out.println("Enter destination airport");
String endVertex = sc.nextLine();
while(!Graph.containsVertex(endVertex))
{
System.out.println("Sorry, that airport does not exist. Please select another;");
endVertex = sc.nextLine();
}
calculatePath(Graph, startVertex, endVertex);
}
private static SimpleDirectedWeightedGraph<String, DefaultWeightedEdge> createGraph()
{
SimpleDirectedWeightedGraph<String, DefaultWeightedEdge> g =
(SimpleDirectedWeightedGraph<String, DefaultWeightedEdge>) new SimpleDirectedWeightedGraph<String, DefaultWeightedEdge>(DefaultWeightedEdge.class);
{
g.addVertex("London");
g.addVertex("France");
g.addVertex("Spain");
createTwoWayWeightedEdge(g, "London", "France", 80);
generateFlight("1600", "1830", "EH445", "0000", 80);
generateFlight("0400", "0600", "HE452", "0000", 80);
createTwoWayWeightedEdge(g, "France", "Spain", 130);
generateFlight("1400", "1600", "HD123", "0400", 130);
generateFlight("0400", "0600", "DH712", "0000", 130);
}
return g;
}
private static void createTwoWayWeightedEdge(SimpleDirectedWeightedGraph<String, DefaultWeightedEdge> g, String vertex1, String vertex2, double weight)
{
g.addEdge(vertex1, vertex2);
g.addEdge(vertex2, vertex1);
g.setEdgeWeight(g.getEdge(vertex1, vertex2), weight);
g.setEdgeWeight(g.getEdge(vertex2, vertex1), weight);
String[] tmp1 = {vertex1, vertex2};
myEdges.add(tmp1);
String[] tmp2 = {vertex2, vertex1};
myEdges.add(tmp2);
}
private static void generateFlight(String depTime, String arrTime, String flightNo, String locTime, int duration)
{
Flight f = new Flight(depTime, arrTime, flightNo, locTime, duration);
flight.add(f);
}
private static String textToPrint(String[] format)
{
String text = " ";
for(int i = 0; i < format.length; i++)
{
switch(i)
{
case 0:
text = text + format[i];
for(int j = format[i].length(); j < 6 ; j++)
text = text + " ";
break;
case 1:
text = text + format[i];
for(int j = format[i].length(); j < 15 ; j++)
text = text + " ";
break;
case 2:
text = text + format[i];
for(int j = format[i].length(); j < 10 ; j++)
text = text + " ";
break;
case 3:
text = text + format[i];
for(int j = format[i].length(); j < 10 ; j++)
text = text + " ";
break;
case 4:
text = text + format[i];
for(int j = format[i].length(); j < 15 ; j++)
text = text + " ";
break;
case 5:
text = text + format[i];
for(int j = format[i].length(); j < 10 ; j++)
text = text + " ";
break;
case 6:
text = text + format[i];
for(int j = format[i].length(); j < 10 ; j++)
text = text + " ";
break;
}
}
return text;
}
private static void calculatePath(SimpleDirectedWeightedGraph<String, DefaultWeightedEdge> g, String startVertex, String endVertex)
{
DijkstraShortestPath path = new DijkstraShortestPath(g, startVertex, endVertex);
path.getPath();
List<Object> edges = path.getPathEdgeList();
String item;
int count = 1;
double totalDuration = 0;
if(edges!=null)
{
System.out.println("\n The lowest cost route is:");
String[] labels = {"Flight.", "Leave from", "At", "On", "Arrive", "At", "Local Time"};
System.out.println(textToPrint(labels));
for(Object edge : edges)
{
item = edge.toString();
StringTokenizer st = new StringTokenizer(item, ":");
String firstAirport = st.nextToken().trim().substring(1);
String secondAirport = st.nextToken().trim();
secondAirport = secondAirport.substring(0, secondAirport.length()-1);
String depTime = null;
String arrTime = null;
String flightNo = null, locTime = null;
double price, flightDuration;
for(int i=0;i<flight.size();i++)
{
if(firstAirport.equals(myEdges.get(i)[0]) && secondAirport.equals(myEdges.get(i)[1]))
{
Flight details = flight.get(i);
flightNo = details.flightNo;
depTime = details.depTime;
arrTime = details.arrTime;
price = details.price;
flightDuration = details.duration;
totalDuration = totalDuration + details.getDuration();
locTime = details.getLocTime();
String[] flightInfo = {count+".", firstAirport, depTime, flightNo, secondAirport, arrTime, locTime};
System.out.println(textToPrint(flightInfo));
}
}
count++;
}
System.out.println("Cost of route = £"+path.getPathLength());
System.out.println("Total time in the air = "+totalDuration +"hrs");
}
else
System.out.println("Sorry you can't fly there from " + startVertex);
}
Flight.java
import java.text.SimpleDateFormat;
public class Flight {
String depTime;
String arrTime;
String flightNo;
String locTime;
double duration;
int price;
public Flight(String depTime, String arrTime, String flightNo, String locTime, int duration){
this.depTime = depTime;
this.arrTime = arrTime;
this.flightNo = flightNo;
this.locTime = locTime;
this.duration = duration;
}
public double getDuration(){
double duration = Integer.parseInt(arrTime) - Integer.parseInt(depTime);
return duration / 100;
}
public String getLocTime(){
int value = Integer.parseInt(locTime) + Integer.parseInt(arrTime);
locTime = ""+value;
return locTime;
}
public String getFlightNo(){
return flightNo;
}
public double getPrice(){
return price;
}
}
Your Question is not exactly clear. But here are some general tips.
Departure + Duration = Arrival
Do not focus on arrival. The arrival time is a result of [arrival + duration]. In other words, output not input. This solves your problem with rotating around the clock crossing midnight.
Use objects, not strings
Use objects, not strings. Java has an excellent industry-leading date-time framework in the java.time classes. Use them. But do not use the notoriously troublesome old legacy date-time classes, the ones outside the java.time package. Use strings only as needed in the user-interface and for serializing data.
In particular, you should be looking at the LocalTime and Duration classes. See Oracle Tutorial.
ISO 8601
And for serializing, stick to the standard ISO 8601 formats such as HH:MM for a time-only value with the colon being optional for the “basic” version though I recommend keeping the colon for the “extended” version. The java.time classes use the extended version of ISO 8601 by default when parsing and generating strings that represent date-time values.
Make Flight ignorant of charting, and vice-versa
Separate out your data model from the chart drawing. Define Flight as just the flight info and functions, without thinking about the charting.
class Flight {
LocalTime departure;
Duration duration;
LocalTime getArrival() {
LocalTime arrival = departure.plus( duration );
// If called *many* times, and you account for changing-data and thread-safety, you could cache this result for performance.
return arrival;
}
Flight( LocalTime departureArg , Duration durationArg ) {
this.departure = departureArg;
this.duration = durationArg;
}
}
To produce the exact data needed by chart, either use getter methods on Flight or a mediating class between Flight and chart. Keep the classes as cleanly separated as possible. Your car’s radio-stereo does not need to know anything about the air-conditioner which in turn does not need to know about the engine’s fuel-oxygen mixture ratio.
Time Zone
The big elephant in the room is time zone. You have not made clear your intentions here.
Generally best to work in UTC. Translate to a local time zone only as needed for presentation to the user.
Not much more to say on this until you clarify the intention of your business context.
Search Stack Overflow for the Java classes LocalDateTime, OffsetDateTime, ZonedDateTime, ZoneOffset, and ZoneId to learn much more.
We might have to append/prefix some format of today's date (examples here : https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html) before doing the duration computation.
so when we have the start time of "0430" we will prefix some format of today's date as well . For example:
startDate = "0430"
becomes
startDateModified = new SimpleDateFormat("yyyy/MM/dd").format(new Date()) + startDate;
startDateObject = new SimpleDateFormat("yyyy/MM/dd HH:mm").parse(statDateModified)
similarly we do so for the end date (we might have to use some other value of new Date() because the arrival time be for the next day etc)
And then we do the computation.
Now regarding your question, we will have to some how figure out the connecting flight departure date value is not
new Date(); //today
but
new Date(System.currentTimeMillis() + 24*3600); //tomorrow
We might, in fact, have to have another shorthand notation to denote that the flight leaves today and reaches tomorrow (like "+1 0430" to denote +1 day etc)
I need to implement a "round-robin" scheduler with a job class that I cannot modify. Round-robin scheduler should process the job that has been waiting the longest first, then reset timer to zero. If two jobs have same wait time, lower id is processed first. The job class only gives three values (job id, remaining duration, and priority(which is not needed for this). each job has a start time, so only a couple of jobs may be available during first cycle, few more next cycle, etc. Since the "job array" I am calling is different every time I call it, I'm not sure how to store the wait times.
This is the job class:
public class Jobs{
private int[] stas = new int[0];
private int[] durs = new int[0];
private int[] lefs = new int[0];
private int[] pris = new int[0];
private int[] fins = new int[0];
private int clock;
public Jobs()
{
this("joblist.csv");
}
public Jobs(String filename)
{
BufferedReader fp = null;
String line = "";
String[] b = null;
int[] tmp;
try
{
fp = new BufferedReader(new FileReader(filename));
while((line = fp.readLine()) != null)
{
b = line.split(",");
if(b.length == 3)
{
try
{
int sta = Integer.parseInt(b[0]);
//System.out.println("sta: " + b[0]);
int dur = Integer.parseInt(b[1]);
//System.out.println("dur: " + b[1]);
int pri = Integer.parseInt(b[2]);
//System.out.println("pri: " + b[2]);
stas = app(stas, sta);
//System.out.println("stas: " + Arrays.toString(stas));
durs = app(durs, dur);
//System.out.println("durs: " + Arrays.toString(durs));
lefs = app(lefs, dur);
//System.out.println("lefs: " + Arrays.toString(lefs));
pris = app(pris, pri);
//System.out.println("pris: " + Arrays.toString(pris));
fins = app(fins, -1);
//System.out.println("fins: " + Arrays.toString(fins));
}
catch(NumberFormatException e) {}
}
}
fp.close();
}
catch(FileNotFoundException e) { e.printStackTrace(); }
catch(IOException e) { e.printStackTrace(); }
clock = 0;
}
public boolean done()
{
boolean done = true;
for(int i=0; done && i<lefs.length; i++)
if(lefs[i]>0) done=false;
return done;
}
public int getClock() { return clock; }
public int[][] getJobs()
{
int count = 0;
for(int i=0; i<stas.length; i++)
if(stas[i]<=clock && lefs[i]>0)
count++;
int[][] jobs = new int[count][3];
count = 0;
for(int i=0; i<stas.length; i++)
if(stas[i]<=clock && lefs[i]>0)
{
jobs[count] = new int[]{i, lefs[i], pris[i]};
count++;
}
return jobs;
}
public int cycle() { return cycle(-1); }
public int cycle(int j)
{
if(j>=0 && j<lefs.length && clock>=stas[j] && lefs[j]>0)
{
lefs[j]--;
if(lefs[j] == 0) fins[j] = clock+1;
}
clock++;
return clock;
}
private int[] app(int[] a, int b)
{
int[] tmp = new int[a.length+1];
for(int i=0; i<a.length; i++) tmp[i] = a[i];
tmp[a.length] = b;
return tmp;
}
public String report()
{
String r = "JOB,PRIORITY,START,DURATION,FINISH,DELAY,PRI*DELAY\n";
float dn=0;
float pdn=0;
for(int i=0; i<stas.length; i++)
{
if(fins[i]>=0)
{
int delay = ((fins[i]-stas[i])-durs[i]);
r+= ""+i+","+pris[i]+","+stas[i]+","+durs[i]+","+fins[i]+","+delay+","+(pris[i]*delay)+"\n";
dn+= delay;
pdn+= pris[i]*delay;
}
else
{
int delay = ((clock*10-stas[i])-durs[i]);
r+= ""+i+","+pris[i]+","+stas[i]+","+durs[i]+","+fins[i]+","+delay+","+(pris[i]*delay)+"\n";
dn+= delay;
pdn+= pris[i]*delay;
}
}
if(stas.length>0)
{
r+= "Avg,,,,,"+(dn/stas.length)+","+pdn/stas.length+"\n";
}
return r;
}
public String toString()
{
String r = "There are "+stas.length+" jobs:\n";
for(int i=0; i<stas.length; i++)
{
r+= " JOB "+i+": START="+stas[i]+" DURATION="+durs[i]+" DURATION_LEFT="+lefs[i]+" PRIORITY="+pris[i]+"\n";
}
return r;
}
I don't need full code, just an idea of how to store wait times and cycle the correct job.
While a array based solution 'may' work, I would advocate a more object oriented approach. Create 'Job' class with the desire attributes (id, start_time, wait etc). Using the csv file, create Job objects and hold them in a list. Write a comparator to sort this jobs-list (in this case based on job wait/age would be the factor).
The job executor then has to do the following:
while(jobs exist) {
iterate on the list {
if job is executable // start_time > current sys_time
consume cycles/job for executable jobs
mark completed jobs (optional)
}
remove the completed jobs
}
//\ This loop will add +1 to each job
for(int i = 0; i < jobs.length; i++)
{
waitTime[jobs[i][0]] += 1;
}
int longestWait = 0;//\ This holds value for greatest wait time
int nextJob = 0; //\ This holds value for index of job with greatest wait time
//\ this loop will check for the greatest wait time and and set variables accordingly
for(int i = 0; i < waitTime.length; i++)
{
if(waitTime[i] > longestWait)
{
longestWait = waitTime[i];
nextJob = i;
}
}
//\ this cycles the job with the highest wait time
jobsource.cycle(nextJob);
//\ this resets the wait time for processed job
waitTime[nextJob] = 0;
I am writing a program for class and the loop seems to not execute correctly. It always returns the value for i as 0. The rest of the code seems to work as advertised, i is just not increasing in index value.
public class Day {
String strDay;
private int d = 0;
private String[] Days = {"SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY"};
String day;
public Day() {
return;
}
public Day(String strDay) {// this is my issue. I think I am going about this constructor all wrong
for (int i = 0; i < Days.length; i++) {
if (strDay.equalsIgnoreCase(Days[i]))
d = i;
return;
}
}
public int getDay() {
return d;
}
public void nexDay() {
int next;
if (d < 6) {
next = (this.d) + 1;
System.out.println("Next Day is :" + Days[next]);
} else {
next = 0;
System.out.println("Next Day is :" + Days[next]);
}
}
public void prevDay() {
int prev = 0;
if ((d > 0) && (d < 6)) {
prev = (this.d) - 1;
System.out.println("previous day is " + Days[prev]);
} else
System.out.println("previous day id " + Days[6]);
}
public int calcDay(int num) {
int newDay;
this.d = d + num;
newDay = this.d % 7;
System.out.println("calc day is" + Days[d]);
return newDay;
}
public void print() {
System.out.println("day is " + Days[d]);
}
public static void main(String[] args) {
String day;
Day Callmethod = new Day();
Scanner console = new Scanner(System.in);
System.out.println("enter a day of the week");
day = console.nextLine();
Callmethod.print();
Callmethod.nexDay();
Callmethod.prevDay();
Callmethod.getDay();
}
}
Well, this
Day Callmethod = new Day();
is calling your empty constructor. Not your constructor with a loop (which takes a String). Also, Java variables start with a lower case letter (Callmethod looks like a class). I think you were looking for something like
Day day = new Day("SUNDAY");
Also, your if needs braces or the return will be invoked without doing anything (unless it matches on the first entry) like
for(int i=0;i<Days.length;i++){
if (strDay.equalsIgnoreCase(Days[i])) {
d = i;
return;
}
}
try change this:
public Day(String strDay)/// this is my issue. I think I am going about this constructor all wrong
{
for(int i=0;i<Days.length;i++){
if (strDay.equalsIgnoreCase(Days[i]))
d = i;
return;
}
}
for this:
public Day(String strDay)/// this is my issue. I think I am going about this constructor all wrong
{
for(int i=0;i<Days.length;i++){
if (strDay.equalsIgnoreCase(Days[i]))
{
d = i;
return;
}
}
}
Without the curly braces your conditional block will be only the next line of code. So your loop was only running once
public Day(String strDay) {
for (int i = 0; i < Days.length; i++) {
if (strDay == Days[i])
d = i;
return;
}
}
If I understood it clearly this will work. If not, just explain me what the goal is on that for loop. And place the return statement outisde of the next bracket.
Hey guys I need some help with my homework. I understand the way the Fork and Join Framework works, but my code does not join the results. Our exercise is to write a program, that counts the true values in an array. Sorry for any mistakes (bad grammar or something else) in this post, it is my first one.
Edit:
Thanks for all the requests here is my solution of this problem:
TrueFinder Class:
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
class TrueFinder extends RecursiveTask<TrueResult>
{
private static final int SEQUENTIAL_THRESHOLD = 5;
private boolean[] trueData;
private final int start;
private final int end;
public TrueFinder(boolean[] data, int start, int end)
{
this.trueData = data;
this.start = start;
this.end = end;
}
public TrueFinder(boolean[] data)
{
this(data, 0, data.length);
}
protected TrueResult compute()
{
final int length = end - start;
int counter = 0;
if (length < SEQUENTIAL_THRESHOLD)
{
for (int i = start; i < end; i++)
{
if (trueData[i])
{
counter++;
}
}
return new TrueResult(counter);
}
else
{
final int split = length / 2;
TrueFinder left = new TrueFinder(trueData, start, start + split);
left.fork();
TrueFinder right = new TrueFinder(trueData, start + split, end);
TrueResult subResultRight = right.compute();
TrueResult subResultLeft = left.join();
return new TrueResult(subResultRight.getTrueCounter() +
subResultLeft.getTrueCounter());
}
}
public static void main(String[] args)
{
int trues = 0;
boolean[] trueArray = new boolean[500];
for (int i = 0; i < 500; i++)
{
if (Math.random() < 0.3)
{
trueArray[i] = true;
trues++;
}
else
{
trueArray[i] = false;
}
}
TrueFinder finder = new TrueFinder(trueArray);
ForkJoinPool pool = new ForkJoinPool(4);
long startTime = System.currentTimeMillis();
TrueResult result = pool.invoke(finder);
long endTime = System.currentTimeMillis();
long actualTime = endTime - startTime;
System.out.println("Array mit der Länge " + trueArray.length + " in"
actualTime + " msec dursucht und " + result.getTrueCounter() +
" von " + trues + " True Werten gefunden.");
}
}
And the result class:
public class TrueResult
{
private int trueCounter;
public TrueResult(int counter)
{
this.trueCounter = counter;
}
public int getTrueCounter()
{
return trueCounter;
}
}
The splitting task of your souce code is wrong as :
(1) your splitting isn't started from 0:
your start is 1
(2) fraction point is ignored for your splitting;
(granted that SEQUENTIAL_THRESHOLD=5 and trueArray.length = 13, your splitting is ignoring of the numbers from 11 to 12)
(3) if you modify for (1) and (2), the length of subtasks must be split not SQCUQNTIALTHRESHOLD.
So, the modifying source code is below:
else
{
int split = (length - 1 ) / SEQUENTIAL_THRESHOLD + 1;
TrueFinder[] subtasks = new TrueFinder[split];
int start = 0;
for(int i = 0; i < split - 1; i++)
{
subtasks[i] = new TrueFinder(trueData, start, start + SEQUENTIAL_THRESHOLD);
subtasks[i].fork();
start += SEQUENTIAL_THRESHOLD;
}
subtasks[split - 1] = new TrueFinder(trueData, start, length);
counter = subtasks[split - 1].compute();// better invoking compute than join
for (int i = 0; i < SEQUENTIAL_THRESHOLD; i++)
{
counter += subtasks[i].join();
}
return new TrueResult(counter);
}