Page 2 of 3 FirstFirst 123 LastLast
Results 21 to 40 of 46
  1. #21
    SMHouston is offline Member
    Join Date
    Sep 2009
    Posts
    80
    Rep Power
    0

    Default

    Ok, i'll keep cracking at it and see what I come up with and have something up in the morning.

    What I found with the day class is you could use

    weekday() - to the the weekday and then later I could use
    advance(int n) - to advance a certain amount of days.

    Problem with this though, is I have yet to see an example or be able to find any information other than that on the day class.

  2. #22
    SMHouston is offline Member
    Join Date
    Sep 2009
    Posts
    80
    Rep Power
    0

    Default

    Ok, here we go I think I'm getting closer but stuck again. Not exactly sure how to get them to return the current day, previous day, next day strings. Think my problem is trying to increment and decrement a string, but not sure where to even start with that. I'm beyond confused at this point to be completely honest and the more I stare at it and try different things seems to be making it worse on myself.

    Java Code:
    public class Day
    {
    	private String[] weekday = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
    	private String currentday; //stores day
    	private String nextday; //stores next day
    	private String previousday; //stores previous day
    
            //Default constructor to set the current day to "Sunday"
    	//Postcondition: sets Default Day to "Sunday"
       public Day()
       {
    	   String weekday = "Sunday";
       }
      
        	//Default constructor
        	//Postcondition; ????
       public void setDay(String Day)
       {
    	   String weekday = Day;
       }
    
            //Method to return the day
            //Postcondition: the value of currentday is returned
        public String getCurrentday()
        {
        	return currentday;
        }
    
        	//Method to return previous day
        	//Postcondition: the value of previousday is returned
        public String getPreviousday()
        {
        	return previousday;
        }
    
        	//Method to return next day
        	//Postcondition: the value of nextday is returned
        public String getNextday()
        {
        	return nextday;
        }
    
            //Method to print the day
        	//Postcondition: the current day is printed
        public void printDay()
        {
        	System.out.println("Today is " + currentday);
        }
    
            //Method to decrement the day by one and print
        	//Postconditions: previousday = currentday - 1 and printed
        public void decrementDay()
        {
        	previousday = currentday--;
        		System.out.println("Yesterday was " + previousday);
        }
    
            //Method to increment the day by one and print
        	//Postconditions: nextday = currentday - 1 and printed;
        public void incrementDay()
        {
        	nextday = currentday++;
        		System.out.println("Tomorrow is " + nextday);
        }
    }
    Last edited by SMHouston; 09-03-2009 at 05:05 PM.

  3. #23
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    There are probably many ways to create the program that you're working on, but your implementation currently won't work. I'm not saying that my suggestions are the one best way to do this, but I think that they will at least work. Please have a look at this example to see what I'm getting at:

    Java Code:
    public class Foo {
      public static final String[] NUMBER_STRINGS = {"Zero", "One", "Two", "Three"};
      private int myNumber;
      
      public Foo(int number) {
        this.myNumber = number;
      }
      
      public Foo(String numberString) {
    	for (int i = 0; i < NUMBER_STRINGS.length; i++) {
    	  if (NUMBER_STRINGS[i].equals(numberString)) {
    	    myNumber = i;
    	  }
    	}
      }
    
    	
      public String getNumberString() {
    	return NUMBER_STRINGS[myNumber];
      }
      
      public String nextNumberString() {
    	int nextNumber = myNumber + 1;
    	
    	// if nextNumber was the largest number possible, then adding one
    	// will be too big and we'll need to have our program loop back around.
    	if (nextNumber == NUMBER_STRINGS.length) {
    	  nextNumber = 0;
    	}
    	return NUMBER_STRINGS[nextNumber];
      }
    
      public String prevNumberString() {
    	int prevNumber = myNumber - 1;
    	
    	// if prevNumber was the smallest number possible, then subtracting one
    	// will return a number < 0  and we'll need to have our program loop back around.
    	if (nextNumber < 0) {
    	  prevNumber = NUMBER_STRINGS[NUMBER_STRINGS.length - 1];
    	}
    	return NUMBER_STRINGS[prevNumber];
      }
      
    
    }

  4. #24
    SMHouston is offline Member
    Join Date
    Sep 2009
    Posts
    80
    Rep Power
    0

    Default

    Ok, I understand your first two things. Setting the currentday to 0 then to a paramater.

    What I'm lost on is creating a method for incrementing and coming out with the previous day and next day no matter what I try without declaring those values I get errors.

    Java Code:
    public class Day
    {
    	private int currentDay;
    	private String[] daysOfTheWeek = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturda"};
    
    	//Default Constuctor 
    	//Postcondition; Sets current day to the value of 0
    	public Day()
    	{
    	 currentDay = 0;
    	}
    	
    	//Constructor to set the value of currentday
    	//Postcondition; currentDay is set to the int value of a
    	public void setcurrentDay(int a)
    	{
    		currentDay = a;
    	}
    }

  5. #25
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by SMHouston View Post
    What I'm lost on is creating a method for incrementing and coming out with the previous day and next day no matter what I try without declaring those values I get errors.
    Could you post the code that gives you errors and also the error messages?

  6. #26
    SMHouston is offline Member
    Join Date
    Sep 2009
    Posts
    80
    Rep Power
    0

    Default

    Thats basically as far as i've gotten with the new code. The first two constructors were like posted above and the rest was like it was. The errors were within the methods, which I've completely wiped and I'm starting from scratch. I think I started to have too many things and it confused me way to much and I lost track where I was.

    Now I've been reading and trying different things all day. I tried your code and get some errors with the if loops:

    Foo.java:38: cannot find symbol
    symbol : variable nextNumber
    location: class Foo
    if (nextNumber < 0) {
    ^
    Foo.java:39: incompatible types
    found : java.lang.String
    required: int
    prevNumber = NUMBER_STRINGS[NUMBER_STRINGS.length - 1];
    ^
    2 errors

    So I started back at scratch and this is where I'm at now using string's. The problem I'm running into is how I'm supposed to get values from the arrays without using numbers. I've read and read and read and searched and searched trust me, and I'm still confused.

    Java Code:
    private class Day
    {
    	private String currentDay;
    	private String nextDay;
    	private String previousDay;
    	private String[] daysOfTheWeek = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
    	
    		//Default constructor;
    		//Initialize currentDay, nextDay, previousDay to empty strings
    		//Postcondition: currentDay =  ""; nextDay = ""; previousDay = "";
    	public Day()
    	{
    		currentDay = "";
    		nextDay = "";
    		previousDay = "";
    	}
    		
    		//Constructor with parameters
    		//Set currentDay according to parameters
    	public Day(String current)
    	{
    		currentDay = current;
    	}
    	
    		//Method to set the current day
    		//Postcondition: currentDay = current;
    		//		AFter setting the current day, a reference
    		// 		to the object is return.
    	public Day setcurrentDay(String current)
    	{
    		currentDay = current;
    		return this;
    	}
    	
    }
    And thats where I'm stuck. Again.
    Last edited by SMHouston; 09-03-2009 at 07:49 PM.

  7. #27
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    I don't think you should use Strings as the internal representation of the current day since you can't add to it or subtract from it. I think that you're better off using an int as I showed above, but you are free do what you want as it's your program. Best of luck.

  8. #28
    SMHouston is offline Member
    Join Date
    Sep 2009
    Posts
    80
    Rep Power
    0

    Default

    Yeah, I'm having a huge problem with the strings will go back. I'm trying to just get this figured out and move onto the next problem in the book but I'm having a hell of a time. I'll go back to what you showed and see if i can get it from there.

    I went to strings because I was so confused I decided to wipe it out and start fresh, got to that point and got myself confused again. So back to square one.

  9. #29
    senorbum is offline Member
    Join Date
    Aug 2009
    Posts
    76
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    I don't think you should use Strings as the internal representation of the current day since you can't add to it or subtract from it. I think that you're better off using an int as I showed above, but you are free do what you want as it's your program. Best of luck.
    Well you could add or subtract, just not gain anything useful out of it. Quite fun though!

    Java Code:
    public static void main (String[] args){
    		String tue = "tuesday";
    		String mon = "monday";
    		String newDay = "";
    		for(int i = 0; i < tue.length(); i++){
    			char s = tue.charAt(i);
    			if(mon.length() < tue.length()){
    				mon = mon + "a";
    			}
    			char m = mon.charAt(i);
    			int difference = s-m;
    			char result = (char) (difference+97);
    			newDay = newDay + result;
    		}
    		System.out.println(newDay);
    	}

  10. #30
    Implode is offline Member
    Join Date
    Aug 2009
    Posts
    50
    Rep Power
    0

    Default

    Hello

    I am new to java aswell, I have read your problem, and would like to ask a question at the same time as possibly answering your question.

    Could one not just prompt the user for the number value of the day, e.g - 1 sun or 1 mon (not sure which day you want to start the week with)

    Then take the digit and just write a simple swith statement to assign the current day.

    is it not possible to assign previousDay to currentDay-- and send it back into the switch statement? and nextDay = currentDay++ ; and send that back into the switch statement?

    Is there no way to put multiple conditions for the switch statements? e.g

    currentDay , nextDay, previousDay

    Im just not sure if some exercises in java books are to learn fundementals, rather than just a solution for the specific problem?

    Thanks

  11. #31
    SMHouston is offline Member
    Join Date
    Sep 2009
    Posts
    80
    Rep Power
    0

    Default

    Your right, and I'll be going at this tomorrow morning hard.

    I think what happened is I got myself headed in a bad direction, and tried to veer off that path, but could never make it off. So tommorow I'm gonna wipe it all out like I never touched it and go back at it.

    I wrote my book program in a half an hour and it works up to a point now, but its 75% done, and this problem should only be half as hard.

    I'll let ya know what I come up with.

  12. #32
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Could one not just prompt the user for the number value of the day, e.g - 1 sun or 1 mon (not sure which day you want to start the week with)
    Then take the digit and just write a simple swith statement to assign the current day.
    First of all I think that it's important to learn early to keep separate concepts in separate classes, and in this exercise I'm meaning separating out the Day class from any class or code that does user interaction. I think that Day should just concern itself with representing the days of the week and should have no user interaction within it whatsoever. Then if you want to, you can create another class that has user interaction in it and also has an object of the Day class, via user interaction gets input from the user, and stores the pertinent information in the Day object. Your other idea seems as if you'll be switching from number to string and back and forth inordinately. Probably the best way to have a class for this is to not use ints, not use Strings, but use enums, perhaps something like so:

    Day.java
    Java Code:
    public enum Day {
      SUNDAY("Sunday", "Sun", 0),
      MONDAY("Monday", "Mon", 1),
      TUESDAY("Tuesday", "Tue", 2),
      WEDNESDAY("Wednesday", "Wed", 3),
      THURSDAY("Thursday", "Thu", 4),
      FRIDAY("Friday", "Fri", 5),
      SATURDAY("Saturday", "Sat", 6);
      
      private String name;
      private String abbrev;
      private int value;
      private Day(String name, String abbrev, int value) {
        this.name = name;
        this.abbrev = abbrev;
        this.value = value;
      }
      
      public String getName() {
        return name;
      }
      public String getAbbrev() {
        return abbrev;
      }
      public int getValue() {
        return value;
      }
      
      public Day next() {
        int ord = this.ordinal() + 1;
        ord %= values().length;
        return values()[ord];
      }
      
      public Day prev() {
        int ord = this.ordinal() - 1 + values().length;
        ord %= values().length;
        return values()[ord];
      }
      
      public static Day dayFromString(String text) {
        return Day.valueOf(text.toUpperCase());
      }
    }
    and can use it like so:
    Java Code:
    public class UseDay {
      public static void main(String[] args) {
        Day d1 = Day.WEDNESDAY;
        System.out.println("d1: " + d1.getName());
        System.out.println("d1.next(): " + d1.next().getName());
        System.out.println("d1.next().next().next().next().next(): " + d1.next().next().next().next().next().getAbbrev());
        System.out.println("d1.prev(): " + d1.prev().getName());
        System.out.println("d1.prev().prev().prev().prev(): " + d1.prev().prev().prev().prev().getName());
        System.out.println();
        
        Day d2 = Day.dayFromString("Tuesday");
        System.out.println("d2: " + d2.getAbbrev());
      }
    
    }
    Last edited by Fubarable; 09-04-2009 at 02:44 AM.

  13. #33
    SMHouston is offline Member
    Join Date
    Sep 2009
    Posts
    80
    Rep Power
    0

    Default

    Ok, reworked this without enums or anything like that. Now, everything is right (I think) up until i get to the toString method

    I think I'm not understanding the toString and what I need to do here.

    Also, would I need to change int i; to int j; in the previous day calculations?

    Here's the code, I left the tostring blank as everything I've put in there is wrong and just can't get it.

    Java Code:
    public class Day
    {
       private String nextDay;
       private String previousDay;
       private String weekDay;
       private String[] weekDays = {"Sunday", "Monday", "Tuesday",
                                     "Wednesday", "Thursday", "Friday",
                                     "Saturday"};
                                     
        public Day()
        {
    		weekDay = "Sunday";
        }
    
        public Day(String d, String e, String f)
        {
    		weekDay = d;
    		nextDay = e;
    		previousDay = f;
        }
        
        public void printDay()
        {
           System.out.print("Today is: " + weekDay + "Tomorrow is: " + nextDay + "Yesterday was: " + previousDay);
        }
    
        public String toString()
        {
           // ???
        }
    
        public String nextDay()
        {
    		int i;
            
    		for(i = 0; i < 7; i++)
    			if(weekDay.equals(weekDays[i]))
    				break;
    		return weekDays[(i + 1) % 7];
        }
    
        public String prevDay()
        {
    		int i;
    		
    		for(i = 0; i < 7; i--)
    			if(weekDay.equals(weekDays[i]))
    				break;
    		return weekDays[(i - 1) % 7];
    	 }
    
        public void addDays(int nDays)
        {
            int i;
            for(i = 0; i < 7; i++)
                if(weekDay.equals(weekDays[i]))
                   break;
    
            weekDay = weekDays[(i + nDays) % 7];
        }
    
    	public void setDay(String d, String e, String f)
    	{
    		weekDay = d;
    		nextDay = e;
    		previousDay = f;
    	}
    
    	public String getDay()
    	{
    		return weekDay;
    	}
    	 
    	public String getNextDay()
    	{
    		return nextDay;
    	}
    		
    	public String getPreviousDay()
    	{
    		return previousDay;
    	}
    }
    Last edited by SMHouston; 09-04-2009 at 07:13 PM.

  14. #34
    JavaVideos is offline Member
    Join Date
    Sep 2009
    Posts
    13
    Rep Power
    0

    Default

    toString just returns what you want displayed in a human readable form as a String.

    So it can be as simple as returning the string you built up in the printDay method like so:

    Java Code:
    @Override
    public String toString() {
         return "Today is: " + weekDay + "Tomorrow is: " + nextDay + "Yesterday was: " + previousDay;
    }
    This does get a bit messy though, so you may want to investigate the StringBuilder class if you have time.

    However this then means that code is repeated, so you could change the printDay method to us toString like so:

    Java Code:
        public void printDay()
        {
           System.out.print(toString());
        }
    This will then avoid code duplication, which is good to avoid, as changes often don't get reflected in all places if code is duplicated.

    As far as changing int i to int j is concerned there is no need. In both methods i is defined as a local variable to the method so it can be repeated in each method without any problem.

  15. #35
    JavaVideos is offline Member
    Join Date
    Sep 2009
    Posts
    13
    Rep Power
    0

    Default

    I also have a bit of advice if you don't mind.

    Java Code:
       
       public Day(String d, String e, String f)
       {
    		weekDay = d;
    		nextDay = e;
    		previousDay = f;
        }
    By using d, e and f as the parameter names for the constructor you are not helping anyone else who is trying to use your class. They won't have any idea what d, e, f are and will mat even wonder what happened to a,b and c! If you give the parameters well thoughtout names it will help everyone, as these parameter names are part of the public definition of the class that anyone can see, where as the actual code inside the constructor is not.

    It would be alot more helpful to have:

    Java Code:
       
       public Day(String weekDay , String nextDay , String previousDay )
       {
    		this.weekDay = weekDay ;
    		this.nextDay = nextDay;
    		this.previousDay = previousDay ;
        }
    The "this" part means use the fields within the class, rather than any locally defined version of the variable name.

    You should also think about invalid input what happens if the constructor is called with the following

    "Monday", "Wednesday", "Friday"

    or even:

    "xxx", "yyy", "zzz"

  16. #36
    SMHouston is offline Member
    Join Date
    Sep 2009
    Posts
    80
    Rep Power
    0

    Default

    much appreciated advice.

    Now with that advice I got a bit confused. The book wants me to write a test program. What the program will do is ask for user input i.e the day of the week.

    When they enter the day of the week it will then take that day print it out and print the next and previous days.
    In my mind I know what needs to be done but I can't even get it started right. I can get their input, but it doesnt do anythign with the previous day and next day because of the array. I'm not very good with working with arrays at and not sure what I need to do here.
    Last edited by SMHouston; 09-04-2009 at 10:02 PM.

  17. #37
    SMHouston is offline Member
    Join Date
    Sep 2009
    Posts
    80
    Rep Power
    0

    Default

    I get this far :

    Java Code:
    import java.io.*;
    
    public class TestWeekdays
    {
    	static BufferedReader keyboard =
                    new BufferedReader(new InputStreamReader(System.in));
    	public static void main(String[] args) throws IOException
    	{
    		Day yourDay = new Day();	
    		
    		String weekDay;
    		String nextDay;
    		String previousDay;
    		String[] weekDays = {"Sunday", "Monday", "Tuesday",
                                     "Wednesday", "Thursday", "Friday",
                                     "Saturday"};
    		
    	
    		System.out.println("What day of the week is it?");
    		
    		weekDay = keyboard.readLine();
    		yourDay.printDay();				
    				
    	}
    }
    Now the problem I'm having is no matter what the user Inputs it always comes back as sunday and even then it shows a null value for tomorrow and yesterday like so:

    Tuesday
    Today is: Sunday
    Tomorrow is: null
    Yesterday was: null
    ----jGRASP: operation complete.

  18. #38
    JavaVideos is offline Member
    Join Date
    Sep 2009
    Posts
    13
    Rep Power
    0

    Default

    The object yourDay is created before you ask the user for input.

    You then as the user for the input, but then the program does not do anything with the answer.

    Your program asks a question to the user, but takes no notice of the answer !

    Try creating the object yourDay after you have received the answer from the user, but don't use the default constructor.

    As far as the next and previous days are concerned. Your day class knows how to create them. So there is no need for the constructor to require today, tomorrow and yesterday. The constructor can just take the parameter for today, and then calculate yesterday and tomorrow.

    Hope that makes sense.

  19. #39
    SMHouston is offline Member
    Join Date
    Sep 2009
    Posts
    80
    Rep Power
    0

    Default

    Yeah, I've been playing with it. Ok, heres what I have going atm.

    I can take the user input and output the current day, and next day.

    I'm throwing this error upon the previous day, and not sure why. I calculated it just like I would adding the days except with the -- and - 1.

    Java Code:
    Monday
    
    Today is: Monday
    Tommorow is Tuesday
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
    	at Day.prevDay(Day.java:45)
    	at TestWeekdays.main(TestWeekdays.java:30)
    I'm also not having a good time getting to the point where I add the days, I've tried numerous things.

    Heres my prevDay code:

    Java Code:
    public String prevDay()
        {
    		int i;
    		
    		for(i = 0; i < 7; i--)
    			if(weekDay.equals(weekDays[i]))
    				break;
    		return weekDays[(i - 1) % 7];
    	 }
    Only way I can get it to work is by switching the prev day to adding 6 days not subtracting them. Is that how I have to do it?
    Last edited by SMHouston; 09-04-2009 at 11:37 PM.

  20. #40
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    8

    Default

    Perhaps it's about time you started reading the tutorials?
    Here is the array tutorial.

Page 2 of 3 FirstFirst 123 LastLast

Similar Threads

  1. How Does One Get Started Learning Java?
    By Wataru in forum New To Java
    Replies: 29
    Last Post: 08-08-2009, 10:45 AM
  2. Just started with Java
    By javades in forum New To Java
    Replies: 2
    Last Post: 07-24-2008, 06:39 AM
  3. getting started
    By ash in forum Advanced Java
    Replies: 1
    Last Post: 07-23-2008, 10:31 AM
  4. Just getting started with java
    By DuceDuceExplorer in forum Introductions
    Replies: 4
    Last Post: 06-29-2008, 06:13 AM
  5. Getting Started
    By Doorsmaniac in forum Java Applets
    Replies: 0
    Last Post: 11-24-2007, 03:40 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •