Okay, so I have this code, it prompts a month and a year from the user and prints the calendar for that month. I'm having some problems though.
the HTML font editing only affects the month.
the days of the week are not aligned in columns correctly.
Thanks!
package calendar_program;
import javax.swing.JOptionPane;
public class Calendar {
public static void main(String[] args) {
StringBuilder result=new StringBuilder();
// read input from user
int year=getYear();
int month=getMonth();
String[] allMonths={
"", "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};
int[] numOfDays= {0,31,28,31,30,31,30,31,31,30,31,30,31};
if (month == 2 && isLeapYear(year)) numOfDays[month]=29;
result.append(" "+allMonths[month]+ " "+ year+"\n"+" S M Tu W Th F S"+"\n");
int d= getstartday(month, 1, year);
for (int i=0; i<d; i++){
result.append(" ");
// prints spaces until the start day
}
for (int i=1; i<=numOfDays[month];i++){
String daysSpace=String.format("%4d", i);
result.append(daysSpace);
if (((i+d) % 7==0) || (i==numOfDays[month])) result.append("\n");
}
//format the final result string
String finalresult= "<html><font face='Arial'>"+result;
JOptionPane.showMessageDialog(null, finalresult);
}
//prompts the user for a year
public static int getYear(){
int year=0;
int option=0;
while(option==JOptionPane.YES_OPTION){
//Read the next data String data
String aString = JOptionPane.showInputDialog("Enter the year (YYYY) :");
year=Integer.parseInt(aString);
option=JOptionPane.NO_OPTION;
}
return year;
}
//prompts the user for a month
public static int getMonth(){
int month=0;
int option=0;
while(option==JOptionPane.YES_OPTION){
//Read the next data String data
String aString = JOptionPane.showInputDialog("Enter the month (MM) :");
month=Integer.parseInt(aString);
option=JOptionPane.NO_OPTION;
}
return month;
}
//This is an equation I found that gives you the start day of each month
public static int getstartday(int m, int d, int y){
int year = y - (14 - m) / 12;
int x = year + year/4 - year/100 + year/400;
int month = m + 12 * ( (14 - m) / 12 ) - 2;
int num = ( d + x + (31*month)/12) % 7;
return num;
}
//sees if the year entered is a leap year, false if not, true if yes
public static boolean isLeapYear (int year){
if ((year % 4 == 0) && (year % 100 != 0)) return true;
if (year % 400 == 0) return true;
return false;
}
}
Here's a rather stupid idea.
Rather then formatting your results using spaces, which may be affected by variance in the individual font widths of a variable width font...use a HTML table instead, or a JTable, or JXMonthView from the SwingX project
HTML Table
String dayNames[] = {"S", "M", "Tu", "W", "Th", "F", "S"};
result.append("<html><font face='Arial'>");
result.append("<table>");
result.append("<tr>");
for (String dayName : dayNames) {
result.append("<td align='right'>").append(dayName).append("</td>");
}
result.append("</tr>");
result.append("<tr>");
for (int i = 0; i < d; i++) {
result.append("<td></td>");
}
for (int i = 0; i < numOfDays[month]; i++) {
if (((i + d) % 7 == 0)) {
result.append("</tr><tr>");
}
result.append("<td align='right'>").append(i + 1).append("</td>");
}
result.append("</tr>");
result.append("</table>");
result.append("</html>");
JTable Example
MyModel model = new MyModel();
List<String> lstRow = new ArrayList<String>(7);
for (int i = 0; i < d; i++) {
lstRow.add("");
}
for (int i = 0; i < numOfDays[month]; i++) {
if (((i + d) % 7 == 0)) {
model.addRow(lstRow);
lstRow = new ArrayList<String>(7);
}
lstRow.add(Integer.toString(i + 1));
}
if (lstRow.size() > 0) {
while (lstRow.size() < 7) {
lstRow.add("");
}
model.addRow(lstRow);
}
JTable table = new JTable(model);
// Kleopatra is so going to kill me for this :(
Dimension size = table.getPreferredScrollableViewportSize();
size.height = table.getRowCount() * table.getRowHeight();
table.setPreferredScrollableViewportSize(size);
JOptionPane.showMessageDialog(null, new JScrollPane(table));
public static class MyModel extends AbstractTableModel {
public static final String[] DAY_NAMES = {"S", "M", "Tu", "W", "Th", "F", "S"};
private List<List<String>> lstRowValues;
public MyModel() {
lstRowValues = new ArrayList<List<String>>(25);
}
#Override
public int getRowCount() {
return lstRowValues.size();
}
#Override
public String getColumnName(int column) {
return DAY_NAMES[column];
}
#Override
public int getColumnCount() {
return 7;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
List<String> rowData = lstRowValues.get(rowIndex);
return rowData.get(columnIndex);
}
public void addRow(List<String> lstValues) {
lstRowValues.add(lstValues);
fireTableRowsInserted(getRowCount(), getRowCount());
}
}
Or you can go have a look at JXMonthView
There are a couple issues I noticed. For one, instead of getting your own days in the month or leap year info, you could use the java.util.Calendar class, which will do that for you.
Also, \n newlines don't behave well when interspersed with HTML formatting, so try using < br/> instead. This is causing the font choice to work improperly.
It looks like extra spaces also get stripped, so surrounding everything with a < pre> tag will fix that.
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
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);
}
I am trying to create a table based on my trial class. When I try to run my table class the table prints with the proper heading, but it does not print anything in the body of the table. How should I fix my for loop so the data enters the table? Do I need to add a parameter to the constructor?
I understand there are more getters and setters than necessary. I was just trying to go about the for loop in different ways.
public class Trial extends JFrame{
static int counter = 0;
int laps = 0;
String lapTime;
double currentTime = 0;
String difference;
int lapsCount = 0;
String[] array1;
double[] array2;
double[] array3;
public int getLapsCount() {
return lapsCount;
}
public void setLapsCount(int lapsCount) {
this.lapsCount = lapsCount;
}
public static int getCounter() {
return counter;
}
public static void setCounter(int counter) {
Trial.counter = counter;
}
public int getLaps() {
return laps;
}
public void setLaps(int laps) {
this.laps = laps;
}
public String getLapTime() {
return lapTime;
}
public void setLapTime(String lapTime) {
this.lapTime = lapTime;
}
public double getCurrentTime() {
return currentTime;
}
public void setCurrentTime(double currentTime) {
this.currentTime = currentTime;
}
public String getDifference() {
return difference;
}
public void setDifference(String difference) {
this.difference = difference;
}
public String[] getArray1() {
return array1;
}
public void setArray1(String[] array1) {
this.array1 = array1;
}
public double[] getArray2() {
return array2;
}
public void setArray2(double[] array2) {
this.array2 = array2;
}
public double[] getArray3() {
return array3;
}
public void setArray3(double[] array3) {
this.array3 = array3;
}
public static void main(String[] args) {
//drop down for number of laps
String lapsString;
String[] selections = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
lapsString = (String) JOptionPane.showInputDialog(null,
"Choose a number of laps:",
"Lap Counter",
JOptionPane.INFORMATION_MESSAGE,
null, /* icon */
selections,
"0");
System.out.printf("Number of laps = \"%s\"\n", lapsString);
int lapsCount = Integer.parseInt(lapsString);
String[] array1 = new String[lapsCount+1];
double[] array2 = new double[lapsCount+1];
double[] array3 = new double[lapsCount+1];
// showInputDialog with for lap time
for (int i = 1; i <= lapsCount; i++){
String lapTime;
lapTime =
JOptionPane.showInputDialog("Enter lap " + i + " total time.");
System.out.printf("Lap " + i + " = \"%s\"\n", lapTime);
array1[i] = lapTime;
double currentTime = inputConvert(array1[i]);
array2[i] = currentTime;
array3[i] = (array2[i] - array2[i-1]);
counter++;
//confirm each time
int result;
String[] results = { "Yes", "No", "Cancel" };
result = JOptionPane.showConfirmDialog(null,
"Please confirm lap " + i + " is " + lapTime);
if (result == -1)
System.out.printf("user closed window\n");
else if (result == 0)
System.out.printf("result = %d, user pressed \"%s\"\n", result, results[result]);
else {
lapTime =
JOptionPane.showInputDialog("Please re-enter lap " + i);
System.out.printf("Lap " + i + " = \"%s\"\n", lapTime);
counter++;
}
}
}
public static double inputConvert(String s) {
double convert = 0.0;
int minutes = Integer.parseInt(s.substring(0, 1));
double seconds = Double.parseDouble(s.substring(2, s.length()));
minutes = minutes * 60;
convert = minutes + seconds;
return convert;
}
private static String getDifference(int j, double sign) {
String difference = "";
if(j == 0) {
difference = "---";
}
else if(sign > 0.0) {
difference = "+";
}
return difference;
}
public static String displayTime(double time) {
String result = null;
int minutes = (int) (time/60);
double seconds = (time % 60);
seconds = Math.round(seconds*100.0)/100.0;
if(seconds < 10){
result = minutes + ":0" + seconds;
}
else{
result = minutes + ":" + seconds;
}
return result;
}
}
This is my table class where the problem arises.
public class table {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new table();
}
});
}
public table() {
JFrame guiFrame = new JFrame();
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("Table to record lap times");
guiFrame.setSize(700,200);
guiFrame.setLocationRelativeTo(null);
JTable table = new JTable(new ExampleTableModel());
table.setAutoCreateRowSorter(true);
table.setGridColor(Color.YELLOW);
table.setBackground(Color.CYAN);
JScrollPane tableScrollPane = new JScrollPane(table);
guiFrame.add(tableScrollPane);
guiFrame.setVisible(true);
}
class ExampleTableModel extends AbstractTableModel{
int laps = 0;
String lapTime;
double currentTime = 0;
String difference;
Trial t = new Trial();
//Two arrays used for the table data
private String[] columnNames = {"Lap #", "Total Time", "Lap Time" , "Difference" };
private Object[][] data;
public ExampleTableModel(){
data = new Object[laps][4];
for(int i = 0; i < laps; i++){
data[i][0] = "Lap " + i;
data[i][1] = t.getArray1() [i];
data[i][2] = t.getArray2()[i];
data[i][3] = t.getArray3()[i];
}
}
#Override public int getRowCount() {
return data.length;
}
#Override public int getColumnCount() {
return columnNames.length;
}
#Override public Object getValueAt(int row, int column) {
return data[row][column];
}
#Override public String getColumnName(int column) {
return columnNames[column];
}
#Override public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
#Override public boolean isCellEditable(int row, int column) {
if (column == 0 || column == 1) {
return false;
}
else {
return true;
}
}
}
}
I made those changes but I need my output to look like this
Lap #: Total time Lap time Difference
Lap1: 2:10 2:10 ---
I fixed the lap number so it starts at 1. I made these changes in the hopes that it would fix the lap time and difference cells but it is giving me an error.
public ExampleTableModel(Trial trial){
int laps = trial.getLapsCount();
data = new Object[laps][4];
for(int i = 0; i < laps; i++){
if (i == 0){
data[i][0] = "Lap " + (i + 1);
data[i][1] = trial.getArray1() [i + 1];
data[i][2] = trial.getArray2() [i + 1];
data[i][3] = trial.getDifference(i, (trial.getArray3()[i + 1] - trial.getArray3()[i]));
}
else {
data[i][0] = "Lap " + (i + 1);
data[i][1] = trial.getArray1() [i + 1];
data[i][2] = trial.displayTime(trial.getArray2() [i + 1] - trial.getArray2() [i]);
data[i][3] = trial.getDifference(i, (trial.getArray3()[i + 1] - trial.getArray3()[i])) + (trial.getArray3()[i + 1] - trial.getArray3()[i]);
}
}
}
Edit: combining the code from the Trial.main and the Table.main methods
To make the code from your Trial class easier to use from the Table class, you can make the following changes. This way you can create a Trial object and call the getUserInput to let the user initialize it:
public static void main(String[] args) {
new Trial().getUserInput();
}
public void getUserInput() {
// [Code from the old main method...]
// Use the fields of the class instead of local variables:
lapsCount = Integer.parseInt(lapsString);
array1 = new String[lapsCount+1];
array2 = new double[lapsCount+1];
array3 = new double[lapsCount+1];
// [Code from the old main method...]
}
Now you can modify the Table model like this:
public Table() {
// [...]
Trial trial = new Trial();
trial.getUserInput();
JTable table = new JTable(new ExampleTableModel(trial));
// [...]
}
And let the ExampleTableModel constructor use a trail parameter (the laps and t fields are no longer used):
public ExampleTableModel(Trial trial){
int laps = trial.getLapsCount();
data = new Object[laps][4];
for(int i = 0; i < laps; i++){
data[i][0] = "Lap " + i;
data[i][1] = trial.getArray1()[i];
data[i][2] = trial.getArray2()[i];
data[i][3] = trial.getArray3()[i];
}
}
There was also an issue with the getColumnClass method:
#Override public Class getColumnClass(int column) {
//return getValueAt(0, column).getClass();
return (column <= 1) ? String.class : Double.class;
}
Now the table looks like this:
The output was:
Number of laps = "2"
Lap 1 = "2:10"
result = 0, user pressed "Yes"
Lap 2 = "2:20"
result = 0, user pressed "Yes"
Old answer
There seem to be a few issues that prevent the table from being filled:
In the ExampleTableModel class the laps field should be something higher than zero (for the constructor to fill the data array):
class ExampleTableModel extends AbstractTableModel {
//int laps = 0;
int laps = 6;
In the constructor of the ExampleTableModel class:
public ExampleTableModel(){
data = new Object[laps][4];
for(int i = 0; i < laps; i++){
data[i][0] = "Lap " + i;
data[i][1] = t.getArray1()[i];
data[i][2] = t.getArray2()[i];
data[i][3] = t.getArray3()[i];
}
}
the calls to the t.getArray1, t.getArray2, and t.getArray3 methods return null. The Trial object appears to have no data yet.
Do you want your program to execute both the code of the Trial.main method and the Table.main method?
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.
// I am creating customize jcalender in swing
//I am facing problem regarding dates set
//i.e actual month is start from tuesday and it is starting from wednesday
// I am finding problem regarding setting values in calender-model
//Above code is running fine but problem in showing actual dates
//please suggest me to make necessary changes
import java.awt.Color;
public class Calendar extends JFrame {
private JPanel contentPane;
String[] years = { "2008", "2009", "2010" ,"2011","2012","2013","2014"};
JComboBox comboBox = new JComboBox(years);
String[] months = { "January", "February", "March", "April", "May", "June", "July", "August",
"September", "October", "November", "December" };
JList list = new JList(months);
JScrollPane scrollPane = new JScrollPane(list);
CalendarModel model = new CalendarModel();
JTable table = new JTable(model);
public Calendar() {
super();
getContentPane().setLayout(null);
comboBox.setBounds(10, 10, 100, 30);
comboBox.setSelectedIndex(5);
comboBox.addItemListener(new ComboHandler());
scrollPane.setBounds(200, 10, 150, 100);
list.setSelectedIndex(10);
list.addListSelectionListener(new ListHandler());
table.setBounds(10, 150, 550, 200);
model.setMonth(comboBox.getSelectedIndex() + 1998, list.getSelectedIndex());
getContentPane().add(comboBox);
getContentPane().add(scrollPane);
table.setGridColor(Color.black);
table.setShowGrid(true);
getContentPane().add(table);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(530,300);
setVisible(true);
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Calendar frame = new Calendar();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public class ComboHandler implements ItemListener {
public void itemStateChanged(ItemEvent e) {
System.out.println("ItemState change Method called ");
model.setMonth(comboBox.getSelectedIndex() + 1998, list.getSelectedIndex());
table.repaint();
}
}
public class ListHandler implements ListSelectionListener {
public void valueChanged(ListSelectionEvent e) {
model.setMonth(comboBox.getSelectedIndex() + 1998, list.getSelectedIndex());
table.repaint();
}
}
}
class CalendarModel extends AbstractTableModel {
String[] days = { "Sun" , "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
int[] numDays = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
String[][] calendar = new String[7][7];
public CalendarModel() {
//setting name of days (mon,tues)
for (int i = 0; i < days.length; ++i)
{
System.out.println("day[i] *** "+days[i]);
calendar[0][i] = days[i];
}
for (int i = 1; i < 7; ++i){
for (int j = 0; j < 7; ++j)
{
System.out.println("calendar[i][j] value i ** "+i +" j value "+ j );
calendar[i][j] = " ";
}
}
}
public int getRowCount() {
return 7;
}
public int getColumnCount() {
return 7;
}
public Object getValueAt(int row, int column) {
System.out.println("get Value at ** "+calendar[row][column]);
return calendar[row][column];
}
/*
public void setValueAt(Object value, int row, int column) {
System.out.println("set Value at ** "+(String) value);
calendar[row][column] = (String) value;
}*/
public void setMonth(int year, int month) {
for (int i = 1; i < 7; ++i)
{
for (int j = 0; j < 7; ++j)
{
calendar[i][j] = " ";
}
}
java.util.GregorianCalendar cal = new java.util.GregorianCalendar();
cal.set(year, month, 1);
int offset = cal.get(java.util.GregorianCalendar.DAY_OF_WEEK) - 1;
offset += 7;
int num = daysInMonth(year, month);
for (int i = 0; i < num; ++i) {
System.out.println("offset *** "+Integer.toString(i+1));
calendar[offset / 7][offset % 7] = Integer.toString(i+1);
++offset;
}
}
public boolean isLeapYear(int year) {
System.out.println("Is Leap Year *** ");
if (year % 4 == 0)
return true;
return false;
}
public int daysInMonth(int year, int month) {
System.out.println("day In month*** ");
int days = numDays[month];
if (month == 1 && isLeapYear(year))
++days;
System.out.println("days *** "+days);
return days;
}
}
I don't know if these are related but...
public void itemStateChanged(ItemEvent e) {
int index = comboBox.getSelectedIndex();
System.out.println("index = " + index + "; " + (index + 1998));
model.setMonth(comboBox.getSelectedIndex() + 1998, list.getSelectedIndex());
table.repaint();
}
Doesn't produce results which match those that are listed within the combo box. For example, if you select the first value, it will equal 1998, not 2008
So, if I select 2013 from the combo box, I'm actually getting 2003.
When I changed it to
public void itemStateChanged(ItemEvent e) {
int index = comboBox.getSelectedIndex();
System.out.println("index = " + index + "; " + (index + 2008));
model.setMonth(comboBox.getSelectedIndex() + 2008, list.getSelectedIndex());
table.repaint();
}
It gave me better results.
I also changed
java.util.GregorianCalendar cal = new java.util.GregorianCalendar();
to
java.util.Calendar cal = java.util.Calendar.getInstance();
You should avoid making assumptions about the users calendar system if possible...
I'd also avoid null layouts as well ;)
You should also avoid calling table.repaint when you change the table model, instead try using fireTableDataChanged from within the setMonth method
I would, personally, add the listeners to the combobox and JList before setting there selected indexes, this will allow the listeners to update the model for you...
You'll also need to fix you ListHandler so that it uses 2008 instead 1998
Have a try with this in setMonth method
public void setMonth(int year, int month)
Change
calendar[offset / 7][offset % 7] = Integer.toString(i+1);
To
calendar[offset / 7][offset % 7] = Integer.toString(i+2);
try this.. use - 2 instead of - 1 in offset calculation.
java.util.GregorianCalendar cal = new java.util.GregorianCalendar();
cal.set(year, month, 1);
int offset = cal.get(java.util.GregorianCalendar.DAY_OF_WEEK)- 2 ;
offset += 7;
int num = daysInMonth(year, month);
for (int i = 0; i < num; ++i) {
System.out.println("offset *** "+Integer.toString(i+1));
calendar[offset / 7][offset % 7] = Integer.toString(i+1);
++offset;