Open Side Menu Go to the Top

04-11-2016 , 04:09 PM
Also, I should note that "bucky" is NOT a class member of your class. It's a local variable in main()
Programming homework and newbie help thread Quote
Programming homework and newbie help thread
$25m Guaranteed WPM on CoinPoker
Join the action now
Daily Rewards • Splash Pots • CoinRaces
Programming homework and newbie help thread
04-11-2016 , 04:27 PM
I understand. I'm tired and I asked the wrong question, using an irrelevant example.

I actually meant to ask about private and public variables with multiple classes. But I have the answer now.. If variables are private in a class they aren't visible to other classes. If they are public you can modify them in another class,
Programming homework and newbie help thread Quote
04-14-2016 , 10:06 PM
so I am trying to change some table data with javascript and json. right now, if you click on a table cell then a popup prompt appears and new data can be entered. that is lame though and i would rather a text box appears

so here is what happens when you click on a table cell.

Code:
function changeDueDate(event){
	
	var taskId = $(this).attr("data-taskId");
	var newDate = prompt("Enter the new due date");
	
	$.ajax({
		url : applicationURL+"/edit/"+taskId+"/2/"+newDate,
		type : "POST",
		dataType : "json"
	}).success(function(result) {
		populateTable(result);
	}).fail(function(xhr, status, errorMessage) {
		console.log(errorMessage);
		console.log(status);
		console.log(xhr);
	});
	
}
of course the table cell that is clicked on contains data that needs to be kept track of. here is how I populated the cells and gave them data.

Code:
var $dueDateLink = $("<a href='#'></a>")
			.text(task.dueDateAsString)
			.attr("data-taskId", task.taskId)
			.click(changeDueDate);


$taskRow = $("<tr></tr>");
$taskRow.append($("<td></td>").append($stuff))
	.append($("<td></td>").append($moarStuff))
	.append($("<td></td>").append($dueDateLink))
				

$("#taskList").append($taskRow);
so, rather than this line

var newDate = prompt("Enter the new due date");

how can I make that a text box and store that data somewhere?
Programming homework and newbie help thread Quote
04-15-2016 , 11:16 AM
In java, is it possible to catch an exception, and handle it differently based on what causes the exception to be thrown?
I have this try/catch block that catches a SQLException, and it can be thrown within the try block for various reasons. I'd like to handle, for example, the case where it is thrown because of a failed unique constraint separately.
Is this possible or can I only catch the exception and deal with it generically, regardless of the specific cause for it?
Programming homework and newbie help thread Quote
04-15-2016 , 11:30 AM
cant you use different catch clauses to catch the different reasons?
Programming homework and newbie help thread Quote
04-15-2016 , 11:31 AM
It's possible to attach a message (string) to an exception while rethrowing it, by calling a constructor taking both the string and the cause object as variables (see the 'Constructor Summary' section of the description of the Exception class in the Java documentation).

See the answers to a question at SO.

Also, don't forget that you can create your own exception classes (see an example at SO).

Last edited by coon74; 04-15-2016 at 11:48 AM. Reason: P.S.: I don't know Java, I'm just decent at googling :D
Programming homework and newbie help thread Quote
04-15-2016 , 11:54 AM
Thanks guys,

I don't think I can use different catch clauses to catch the different reasons, because the different reasons still throw the same exception.
So I'll have to catch that exception and then within the catch block figure out the cause of the exception and handle it accordingly.

Reading the message that's attached to the exception does in fact work.

https://docs.oracle.com/javase/7/doc...Exception.html

It says here that each SQLException has (amongst other things) a String error message (This is what I'm using now), and "an integer error code that is specific to each vendor. Normally this will be the actual error code returned by the underlying database."
I'm not entirely sure what this means, but if it means that each error that might throw the exception has his own integer error code, then that is an even better solution (or they're equivalent really, but number comparison is shorter than string comparison so should make for more readable code)
Programming homework and newbie help thread Quote
04-15-2016 , 12:03 PM
well what are the reasons that are causing the error?
Programming homework and newbie help thread Quote
04-15-2016 , 12:30 PM
Quote:
Originally Posted by Mavoor
It says here that each SQLException has (amongst other things) a String error message (This is what I'm using now), and "an integer error code that is specific to each vendor. Normally this will be the actual error code returned by the underlying database."
I'm not entirely sure what this means, but if it means that each error that might throw the exception has his own integer error code, then that is an even better solution (or they're equivalent really, but number comparison is shorter than string comparison so should make for more readable code)
Yes, you can use getErrorCode() and it's useful, but the codes are 'vendor-specific' so you need to consult the documentation of your DB connector for a mapping between error codes and underlying error causes.
Programming homework and newbie help thread Quote
04-15-2016 , 02:29 PM
Quote:
Originally Posted by Victor
so, rather than this line

var newDate = prompt("Enter the new due date");

how can I make that a text box and store that data somewhere?
Code:
$inputBox = $('<input type ="text" id="changeDate" name="changeDate">');

$(this).replaceWith($inputBox);
ok so this makes a nice text box over the cell that I want to be able to change. anyone know how to create a submit button that will submit the data entered in that text box?

I am pretty bad at javascript.
Programming homework and newbie help thread Quote
04-15-2016 , 06:06 PM
Quote:
Originally Posted by Victor
well what are the reasons that are causing the error?
The error I wanted to handle specifically was when a unique constraint is violated ie when attempting to write into the db with an already existing username in my case.
Other errors that might cause the same exceptions I'd imagine are any connection issues that might come up, among other things
Programming homework and newbie help thread Quote
04-15-2016 , 06:14 PM
large-ish rails question that I haven't been able to noodle for some time:

Say I'm building a recipe site. I have something set up where people can create beautiful recipes complete with pictures, text, etc. This has a title and text.

Now I want to let people create custom meal planners for a week, so I take recipes x, y, and z, and have them be a custom meal plan named mealXYZ. If the recipe owner updates the recipe, the meal plan should reflect this when it is accessed. (references I assume)

If another user likes that plan, I then want them to be able to copy the entire plan and, if they want, add, remove, or create some amount of recipes, and then save it all as an e-book where each page is a different recipe (pdf maybe, whatever). When the e-book is created, it should not change if recipes are updated. (Make a copy of the recipe at the time the e-book is created?)

How would I go about doing this?

I will gladly take my answer in the form of a link to a tutorial that points me in the right direction. I feel like I have a logical grasp on how to accomplish this, but not enough technical know how yet.
Programming homework and newbie help thread Quote
04-15-2016 , 08:57 PM
That seems like a pretty standard set of models. You'd create a Recipe class however you want to do that. Then you'd create a MealPlan class with a has_many :recipes association. Then finally you'd create, say, a CookBook class with a has_many :meal_plans association. Then in your controllers and views you'd figure out how you want to let the user create/update/view/etc all the various models. Just look for any basic tutorial where they teach you how to make a simple blog, you'll see how associations work when they go through how a blog post can have many comments. And yeah, if you want your CookBooks to remain static even if the underlying recipe changed, you'd have to create a new instance of each MealPlan/Recipe when the CookBook is created so that future updates don't affect them.
Programming homework and newbie help thread Quote
04-15-2016 , 10:33 PM
Quote:
Originally Posted by Mavoor
The error I wanted to handle specifically was when a unique constraint is violated ie when attempting to write into the db with an already existing username in my case.
Other errors that might cause the same exceptions I'd imagine are any connection issues that might come up, among other things
wouldnt it be easier and more useful to authenticate a user before they are able to write into the database?
Programming homework and newbie help thread Quote
04-16-2016 , 07:17 AM
Quote:
Originally Posted by Mavoor
In java, is it possible to catch an exception, and handle it differently based on what causes the exception to be thrown?
I have this try/catch block that catches a SQLException, and it can be thrown within the try block for various reasons. I'd like to handle, for example, the case where it is thrown because of a failed unique constraint separately.
Is this possible or can I only catch the exception and deal with it generically, regardless of the specific cause for it?
Either the exceptions are distinguishable because they have different messages or error codes or whatever, or else they're being thrown at different points in the code in which case have nested try/catch blocks that throw custom exceptions, or else you're dealing with very bad code.
Programming homework and newbie help thread Quote
04-16-2016 , 09:18 AM
I removed code from this guys program to simplifiy as it probably isn't necessary for my questions.

He creates an instance but never uses it, why? And a constructor with no arguments passed to it, why? The video tutorials I'm following, the guy always creates another class, which is what I did when I wrote the same program. Why are his methods private, for example getting integers from screen.




Code:
public class LeapYear{
	public static void main(String... Args){
		
			LeapYear instance = new LeapYear();
		
	}	
	public LeapYear(){
		    //

			int year = getIntFrmScn("Year");
			
	}	
	private void getDaysInMonthForYear(int y, int m){
		
	}
	
	private int getIntFrmScn(String question){
		Scanner sc = new Scanner(System.in);
		//
		return input;
	}
}

Last edited by mackeleven; 04-16-2016 at 09:42 AM.
Programming homework and newbie help thread Quote
04-16-2016 , 09:47 AM
Quote:
Originally Posted by Victor
wouldnt it be easier and more useful to authenticate a user before they are able to write into the database?
Well the user is only attempting to write it's own registration into the database, so I thought I could simply let the database handle the "authentication", that is check to see if the chosen username is available.
At first I was going to do this by reading all the existing usernames from the database, and check if a username is already in use. But I feel like I can probably skip this, since when writing into the database the database itself performs the same check.
Not sure if this is bad practice or a bad idea for some reason though

Quote:
Originally Posted by ChrisV
Either the exceptions are distinguishable because they have different messages or error codes or whatever, or else they're being thrown at different points in the code in which case have nested try/catch blocks that throw custom exceptions, or else you're dealing with very bad code.
Yeah the exceptions are distinguishable. Could probably have figured that out myself with a quick google search, actually did just after I asked
The exception I'm dealing with, SQLException, is a part of java's official api fwiw
Programming homework and newbie help thread Quote
04-16-2016 , 09:51 AM
Yeah that code makes no sense. There's nothing wrong with default constructors (meaning ones without arguments) but they should contain code necessary to set up an instance of an object, not random things you want to run when your program executes.

His program should have a class "ScreenGrabber" or something. In the constructor for that class it should set up that "Scanner" thing. It should expose a public method that says whether or not it's a leap year (which is I assume what this thing does). Then the main method should create an instance of that class and call the method on it to get the answer.
Programming homework and newbie help thread Quote
04-16-2016 , 11:54 AM
Quote:
Originally Posted by Mavoor
Well the user is only attempting to write it's own registration into the database, so I thought I could simply let the database handle the "authentication", that is check to see if the chosen username is available.
At first I was going to do this by reading all the existing usernames from the database, and check if a username is already in use. But I feel like I can probably skip this, since when writing into the database the database itself performs the same check.
Not sure if this is bad practice or a bad idea for some reason though

So when a new users tries to create an account you want to try write in his chosen username as a primary key which will trigger a checked exception if the username already exists?

That doesn't seem the best way though I am not able to articulate why. So this is a good reason for me to study up on Java exceptions
Programming homework and newbie help thread Quote
04-16-2016 , 01:06 PM
Thanks ChrisV.
Interesting. In my class of mature students he would be considered the best at Java already having a bachelors in software dev, where my bg is different and I'm fairly new to Java.

Quote:
Then the main method should create an instance of that class and call the method on it to get the answer.
Him nNot doing this is what is putting me off.

Let me post the entire program ( removing his name) just in case I'm doing him injustice so that I can know to avoid studying any code he uploads to the cloud in future. Judging by your reply about what should go in the constructor, though I suspect your answer will be the same.. cheers

The program simply takes in the month(1-12) and the year from the user and prints out whether it is a leapyear.


Code:
import java.util.Scanner;



public class LeapYear{
	public static void main(String... Args){
		try{
			LeapYear instance = new LeapYear();
		}catch(Exception e){
			System.out.println(e.getMessage());
		}
	}	
	public LeapYear(){
		try{

			int year = getIntFrmScn("Year");
			while(year<=0||year>=90000)year = getIntFrmScn("Year");
			int month = getIntFrmScn("Month");
			while(month<0||month>13)month = getIntFrmScn("Month");
			getDaysInMonthForYear(year, month);
		}catch(Exception e){
			System.out.println(e.getMessage());
		}
	}	
	private void getDaysInMonthForYear(int y, int m){
		int days;
		switch (m){
			case 2:
				if((y % 400 == 0) || ((y % 4 == 0) && (y % 100 != 0))){days=29;}else{days=28;}
				break;
			case 4:days =30;
				break;
			case 6:days =30;
				break;
			case 9:days =30;
				break;
			case 11:days =30;
				break;
			default: if(m>12||m<1){days=0;}else{days =31;}
               break;
        }
		System.out.println("year: "+y+" month: "+((m<10)?"0":"")+m+" days in month: "+days);
	}
	
	private int getIntFrmScn(String question){
		Scanner sc = new Scanner(System.in);
		int input = 0; 
			System.out.print("please Enter "+question+": ");
			while (!sc.hasNextInt()){System.out.print("please Enter "+question+": "); sc.next();}
			input = sc.nextInt();
		return input;
	}
}

Last edited by mackeleven; 04-16-2016 at 01:20 PM.
Programming homework and newbie help thread Quote
04-16-2016 , 02:31 PM
What I don't like is that 'month' and 'year' are local variables of the constructor. I'd rather declare them as private variables for the whole class, outside any function. And I wouldn't do elaborate things in a constructor, it should be as simple as
Code:
public LeapYear (int y, int m){
        year = y;
        month = m;
}
There can be a special function reading the user input of the real month and year values, like
Code:
public setYearAndMonth(){
        try{
		while(year<=0||year>=90000)
                        year = getIntFrmScn("Year");
		while(month<0||month>13)
                        month = getIntFrmScn("Month");
	}catch(Exception e){
	        System.out.println(e.getMessage());
	}
}
The difference is that such architecture makes the class more universal. Another programmer might want to use the class but initialise its variables in another fashion out of another class; then it will be enough for him to call the constructor passing the values he wishes to assign as parameters, without the need to ask the end user to put the values in the way your fellow student has specified.

And more importantly, one would be able to allow the user to input the year and month many times without creating a new instance of a class. For this reason, there would ideally be special functions for variable change like this:
Code:
public changeYear(int y){
        year = y;
}
Now, main() can first call the constructor with default values and then set its values properly:
Code:
public static void main(String[] args){
        LeapYear instance = new LeapYear(0,0);
        instance.setYearAndMonth();
        instance.getDaysInMonthForYear();
}
(note that getDays now takes no parameters because 'year' and 'month' are passed to it automatically as class variables).

getIntFrmScn might as well be a made method of a separate class as ChrisV said, as its usefulness goes far beyond the scope of the LeapYear class, though it doesn't matter that much in a small program like this where I'd be too lazy to set up a second class just for the sake of one method.

Also, it looks strange to me that he writes the '...' in public static void main(String... Args), see an SO question about the difference between '...' and '[]'.

Last edited by coon74; 04-16-2016 at 02:47 PM.
Programming homework and newbie help thread Quote
04-16-2016 , 03:14 PM
^ Heh, of course I meant public void setYearAndMonth() and public void changeYear(int y).

On a side note, Java and C# are weird (as opposed to C++) in that Main() is declared inside a class
Programming homework and newbie help thread Quote
04-16-2016 , 03:23 PM
Quote:
Originally Posted by Victor
So when a new users tries to create an account you want to try write in his chosen username as a primary key which will trigger a checked exception if the username already exists?

That doesn't seem the best way though I am not able to articulate why. So this is a good reason for me to study up on Java exceptions
Doesn't have to be a primary key. On my users table I have a column that is the lower case version of user names (I also keep the specific cased version). I have a unique index (not a primary key) on the lower_username field. This will reject any insert that tries to add a username that already exists, regardless of capitalization.

To me it's simpler to try to insert and alert on failure than to check first and then insert. And more fail-safe.
Programming homework and newbie help thread Quote
04-16-2016 , 04:27 PM
Quote:
Originally Posted by coon74
What I don't like is that 'month' and 'year' are local variables of the constructor. I'd rather declare them as private variables for the whole class, outside any function. And I wouldn't do elaborate things in a constructor, it should be as simple as
Code:
public LeapYear (int y, int m){
        year = y;
        month = m;
}
There can be a special function reading the user input of the real month and year values, like
Code:
public setYearAndMonth(){
        try{
		while(year<=0||year>=90000)
                        year = getIntFrmScn("Year");
		while(month<0||month>13)
                        month = getIntFrmScn("Month");
	}catch(Exception e){
	        System.out.println(e.getMessage());
	}
}
The difference is that such architecture makes the class more universal. Another programmer might want to use the class but initialise its variables in another fashion out of another class; then it will be enough for him to call the constructor passing the values he wishes to assign as parameters, without the need to ask the end user to put the values in the way your fellow student has specified.

And more importantly, one would be able to allow the user to input the year and month many times without creating a new instance of a class. For this reason, there would ideally be special functions for variable change like this:
Code:
public changeYear(int y){
        year = y;
}
Now, main() can first call the constructor with default values and then set its values properly:
Code:
public static void main(String[] args){
        LeapYear instance = new LeapYear(0,0);
        instance.setYearAndMonth();
        instance.getDaysInMonthForYear();
}
(note that getDays now takes no parameters because 'year' and 'month' are passed to it automatically as class variables).

getIntFrmScn might as well be a made method of a separate class as ChrisV said, as its usefulness goes far beyond the scope of the LeapYear class, though it doesn't matter that much in a small program like this where I'd be too lazy to set up a second class just for the sake of one method.

Also, it looks strange to me that he writes the '...' in public static void main(String... Args), see an SO question about the difference between '...' and '[]'.
Yes good stuff. thanks
Quote:
On a side note, Java and C# are weird (as opposed to C++) in that Main() is declared inside a class
Yeah, multiple main() methods in one program took me back for a bit when I learned of that.
Programming homework and newbie help thread Quote
04-18-2016 , 02:53 AM
ok, Ive made some progress but I'm still not quite there. when I click on the initial link I can make a nice text box and even a submit button. but I am not able to link the text to the submit button.

well, actually I have 2 problems.

so I click on the link and it calls a function replaces the table cell with a textbox and a submit button. this kinda works.

Code:
$myTextBox = $('<input type ="text" id="changeDate" name="changeDate"/>');
var newDate = document.getElementById("changeDate").value;
$myButton=$('<input type=button  value=Change />').attr("data-newDate", newDate).attr("data-taskId", taskId).click(changeDueDate);
$(this).append($myTextBox).append($myButton);
I would prefer to use the replaceWith function but that does not allow me to append. so this only shows a textbox $(this).replaceWith($myTextBox).append($myButton);

anyway, thats not big deal.

what I want to do is grab the text from the texbox and ship it to the function that is called by clicking on the button. that proper date is supposed to be in the "newDate" variable but its not working out for me and I keep getting null errors for newDate. "Uncaught TypeError: Cannot read property 'value' of null"

now, if I hard-code in a date for the bolded newDate, everything works. so how can I grab text entered into that textbox?
Programming homework and newbie help thread Quote
Programming homework and newbie help thread
$25m Guaranteed WPM on CoinPoker
Join the action now
Daily Rewards • Splash Pots • CoinRaces
Programming homework and newbie help thread

      
m