Query the data and put them in objects.
Then use those objects to create the JTree.
The above must be independent. One class for reading and returning the data. Then call that class take the data form the DB and build your tree.
Query the data and put them in objects.
Then use those objects to create the JTree.
The above must be independent. One class for reading and returning the data. Then call that class take the data form the DB and build your tree.
The way I see it the assignment IS the instructions! It is not like that you have been given only this:
>>>>
ITU wants you write some classes for their Personnel Record System. To make it simple, consider only 4 classes: Person, Employee, Instructor and Student. The following figure illustrates the relationship between these 4 classes. The Person class is the parent class of the Employee class and the Student class. The Employee class is the parent class of the Instructor class.
<<<<
The rest of the assignment tells you exactly what you need to do. Example:
Person
ID: int, starting from 1 and should be unique
Name: String
Create a Parent class with the above attributes
or
The Employee class is the parent class of the Instructor class.
It tells you which class extends what
Just create the classes using the instructions given. I am sure that you have
notes on how to create classes with attributes.
Read the error that you get!
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at OurGame.Board.checkCollisions(Board.java:72)
Board.java:72 line 72. Something there is null.
Print everything that you use at that line. And point out in the code that you posted where that line is.
Here is an example of how to create a simple menu. You can put that in a method and call it. You can have different menus in different methods. And you can have those methods called from another menu-method:
void menu_1 () {
int choice = 0;
while (true) {
// print the menu
//get the input
choice = ...;
if (choice==1) {
// do something
} else if (choice==2) {
//
} .... else if (choice==4) {
// exit the loop
break;
} else {
System.out.println("Invalid choice");
}
}
}
You should make the necessary changes for your case.
And you can have 1 method with the main menu: PreEmptive / Non-PreEmptive
And 2 others with menus for PreEmptive and Non-PreEmptive
In the method with the main menu, at the ifs with the choices you can call the other menus:
if (choice==1) {
// call menu of PreEmptive (different method with its own menu)
} else if (choice==2) {
// call menu of Non - PreEmptive (different method with its own menu)
} .... else if (choice==3) {
// exit the loop
break;
} else {
System.out.println("Invalid choice");
}
Have you tried to print the values of the objects you are using?
If you get a NullPointerException at the line:
Rectangle r7 = boss1.getBounds(); // first error here
Then probably, boss1 is null. I find that very hard to believe since you initialize it in the constructor! Since you correctly create the Enemies, the Boss should work.
Can you try this:
System.out.println("boss1="+boss1);
System.out.println("boss1.getBounds()="+boss1.getBounds());
Rectangle r7 = boss1.getBounds();
System.out.println("r7="+r7);
And post again the output, the error, and a small part of the code that you get the error
Where exactly is the error at the checkCollisions method? Can you mark it somehow at the code that you posted. Also go to the line that the error says and print everything that you use there.
Then you need 2 stacks not one. You use a private array in the Stack class. You can create as many instance of the PushAndPopStacks class.
Create 2 PushAndPopStacks instances. You already have one:
Stack S = new PushAndPopStacks()
The PushAndPopStacks should have only one private array. Create 2 PushAndPopStacks. Then call pop method of one instance and push the result into the other.
What errors do you get? What is the output and why you thing it is wrong. Also I don't see where is the method for putting the data from one array to the other.
Maybe you should loop one array and put its values to another, but the 0 index should be put in the length-1, the i index in the length-1-i index
As you can see the first method runs. But the insert method doesn't/ Maybe you should add some debug messages, like at the beginning and end of each method:
public static void processResults() {
System.out.println("Entering processResults");
......
.....
System.out.println("Exiting processResults");
}
Also replace the System.exit code with return statements.
And it would be a good thing inside each catch to add this:
catch(SQLException sqlEx) {
sqlEx.printStackTrace();
......
}
First of all. You open the connection and immediately you close. The finally always gets executed. So when you open it at the beginning of your program you go and close it.
At the method processResults you declare another Connection object. It is not the same as the one in the main method. You initialize to null and you try to use it.
Here is a suggestion. Use different methods. Make it simple The following code may not be very efficient but it's simple. Remove the connection from the main and have 2 methods:
processResults() {
Connection connection = null;
Statement statement = null;
ResultSet results = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection = DriverManager.getConnection("jdbc:odbc:Finances","","");
statement = connection.createStatement();
results = statement.executeQuery("SELECT * FROM Accounts");
while (results.next()) {
System.out.println();
System.out.println("Account no. " + results.getInt(1));
System.out.println("Account holder: " + results.getString(3) + " " + results.getString(2));
System.out.printf("Balance: %.2f %n%n", results.getFloat(4));
}
} catch(ClassNotFoundException cnfEx) {
System.out.println("* Unable to load driver! *");
System.out.println(cnfEx.getMessage();
System.exit(1);
} catch(SQLException sqlEx) {
System.out.println("* Cannot connect to database! *");
System.out.println(sqlEx.getMessage();
System.exit(2);
} finally {
try {
if (results!=null) results.close();
if (statement!=null) statement.close();
if (connection!=null) connection.close();
} catch(SQLException sqlEx) {
System.out.println("* Unable to disconnect! *");
System.out.println(sqlEx.getMessage();
}
}
}
insert() {
Connection connection = null;
Statement statement = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection = DriverManager.getConnection("jdbc:odbc:Finances","","");
statement = connection.createStatement();
int result = statement.executeUpdate("INSERT INTO Accounts VALUES(112233,'SMITH', 'John James',752.85)");
} catch(ClassNotFoundException cnfEx) {
System.out.println("* Unable to load driver! *");
System.out.println(cnfEx.getMessage();
System.exit(1);
} catch(SQLException sqlEx) {
System.out.println("* Cannot connect to …
why does this only happen sometimes could it be its loading them in the wrong order?
Probably because it happens at Run Time. Meaning that sometimes the object that you use has value, and sometimes it doesn't.
Maybe you have some if statements and there is a case where something is not being initialized.
Do you have some code?
Have you tried reading the error? The problem is when you run your code. Read the errors that you get:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at OurGame.Board.checkCollisions(Board.java:78)
At the file: Board.java line 78, in the method checkCollisions you are trying to use an object which is null. (java.lang.NullPointerException)
Try to print the objects that you are using and see which one is null and make sure you initialize it.
If you still having problems you can post your code (the method checkCollisions) so we can take a better look.
Is this the exact code that you use?
Because string needs capital S and system, needs capital S:
class forloop {
public static void main(String args[]){
int x;
for(x=0;x<10;x=x+1)
System.out.println("this is x:"+x);
}
}
How do you compile the .java file?
Also for future references, you should name your .java files with capital letter:
ForLoop.java
class ForLoop {
}
It is common practice.
You know we are learning and some of us older folks have a harder time. I did read your message and when the thing still was not working I tried others. Thanks for your help but don't degrade some one unless you know that they aren't a 18 year old not trying.
I would like to apologize and I had no intention of insulting anyone but I don't believe that my post was so aggressive. Still, if you felt that way, you have my apologies and I will be more careful in the future.
Many times have I seen my advices completely ignored and posters wondering why their code doesn't work. It is always a good thing when people come in this forum with the will to learn and show effort.
It is a good think that you try out a things on your own. I hope that you understood from my previous post why you shouldn't mix the list with the class Item.
And from the rest of your code, even if I don't know what you are trying to accomplish, maybe you should forget the suggestion of creating a new class for the Items list.
Just have the Item class with only attributes the description, weight, get/set methods and in the Room class put the list. That list would be like any other attribute:
public class Room {
public String description;
private HashMap<String, Room> exits;
private ArrayList<Item> items;
..........
You can have a …
Arrays begin with index 0. But you have the counter to be 0, then you increase it and then you add:
int counter = 0;
while () {
counter++ // you wrongfully increase the value and then you add:
array[counter]=peopleObj;
}
First you must add to the array and you must increase the counter. the first time the counter would be 0 and you would do this:
array[counter]=peopleObj; (array[0]=peopleObj)
Then you must increase the counter not before.
Also if you exit the while, not all of the elements of the array would have value. Some would be null. That is why you get the error.
Try this:
for(int i=0;i<array.length;i++) {
System.out.println(array[i]);
}
// some of the above would be null.
// the right way is:
for(int i=0;i<counter;i++) {
System.out.println(array[i]);
}
So you can print only the elements of the array that have been initialized
In the same way you access any element in any array:
// initializing the ARRAY:
MyCustomClass [] array = new MyCustomClass[2];
// array is not null, but array[0], array[1] are null
// array[0] is a MyCustomClass
array[0] = new MyCustomClass(....);
array[1] = new MyCustomClass(....);
// array[i] are now created
....
System.out.println(array[0].getName());
....
// we call the .length method and take each element
for (int i=0;i<array.length;i++) {
MyCustomClass mc = array[i];
System.out.println(mc.getName()+", "+mc.getAge());
}
In the constructor you do this:
public Item(String description, int weight) {
this.description = description;
weight = weight;
}
When you do weight = weight; you simply take the argument and you put its value to the argument.
When you do this.description = description; you take the argument and you assign it to the class variable.
Then you completely ignored my advices. You don't need to put the ArrayList in the Item class. The item has weight and description. IT doesn't have an items list. You need to put that in a separate class.
And whenever you create a new instance of the Item class you call the addItem() method. Why? You need to create the item and then add that item to the list.
That list needs to be in a separate class, so when you create many items all of them will be put in one single list.
What you do is: Call the constructor, which calls the addITem, which calls many constructors, each of them call the addItem() method again, which each addItem methods create new instances, which each instance calls again the addItem, .......
And so on and so on.
Remove the list from the Item class. (As already told and didn't listen)
Put those items in one list. That list must not be in the Item class because each time you create an Item instance you create a new list.
ArrayList<Item> list = new ArrayList<Item>(); …
still getting a stack overflow error when trying to add said item to room. Any suggestions.
Have you made any changes to your code? Can you post the latest full version?
You need to provide more information as what are those variables that you have?
Do you have an array and you want to see how many times the argument is inside the array?
Then loop the array and take each element of the array and compare it with the argument
In the Item constructor when you do this: description = description;
You are not initializing the attributes of the class. The description is the same as the one of the argument because it is declared locally as an argument.
You need this: this.description = description;
With "this" you say put the argument description in the description of the class. Do the same for the other.
Replace the getLongDescription() method with the toString method. The toString method is inherited from the Object class.
public String toString() {
return "Item " + description + " Weight " + weight;
}
So when you do this:
Item it = new Item();
System.out.println(it);
The toString method you overridden is automatically called.
That is exactly what happens when you do this: returnString += " " + items;
The toString method of the ArrayList class is automatically called.
Also you need to put the ArrayList in a different class. Every time you create a new instance you also create a new ArrayList. But you need to add all of tour items
in one list. So you are going to keep doing (new Item()) and then add all of those to a different item?
Remove the ArrayList from the Item class and do this:
class Items {
private ArrayList<Item> list = null;
public Items() {
list = new ArrayList<Item>();
}
// add methods
// get methods
// And of course the toString method:
public …
hi .. i am new to jsp coding - i hav created a database using mysql workbench - it is a Graphical Interface to creating databases and tables... but the problem is that i dont know how to access my tables through jsp coding .. where should i put my database .. how should i give the path for connection ... i am using Apache Tomcat server ,... please help ASAP
Start a new thread.
Create separate classes with methods for connecting, reading/inserting/updating the database. I propose a different class per database table.
Then write the html code (JSP page) and call those methods.
Also read the tutorial at the top of the JSP forum about MVC Connectivity
What is supposed to be "written underneath" is whatever code is necessary to make the method perform as you intend. E.g. If you want the method to return the sum of 2 numbers:
public int add(int num1, int num2) { int sum=0; sum = num1+ num2; return sum; }
You can do anything you want to do inside a method.
Also, In case you didn't know:
public int add -
public means the method can be accessed from anywhere in the class.(unless you are trying to access it from a static method)
The int is the return type of the method. Which means, when this method is run, it will return some value, which in this case will be
the result of adding 2 numbers.The int num1,int num2 inside the brackets are parameters. This means the method can only be called if 2 parameters of type int are passed into it. So, when you call this method, you would call is like so:
add(3,4); // where 3 and 4 are 2 integers. Of course,this call will only work inside the class that the method is declared in. If you wish //to access this method from outside the class, then use the "methods"(ways) that javaaddict showed you.
And if I may add, I already mentioned what needs to go underneath:
In your case you can have a method that takes as argument a Foot instance and an int, and call the turn method.
And I find …
No.
That is not the right answer Akill10, shame on you. You should have said:
Noooooo!
Anyway, when you signed in this forum, you agreed to the terms, and those terms say that we don't give away homework nor any code.
Show some effort, post your code and ask specific questions
I would advise you to change the choices method, because I am sorry, but it is totally wrong. You might not see it, it might never happen but, an OutOfMemoryException is about to happen.
You keep on calling the choices inside the choices method. That gives you the behavior you want, (after you make a choice, the menu prints again), BUT:
When you recursively call the same method (choices) eventually you will run out of memory. If you want the menu to keep on printing you can try this:
public void choices() {
while (true) {
// put ALL of your code here and remove the calls of the choices method:
....
....
if () { ......
} else if(choices == 2){
JOptionPane.showMessageDialog(null, "You have chosen to ADD a record");
index = index + 1;
add();
// REMOVE ALL OF THOSE
//choices();
} else if () { ... }
else {
System.out.println("Invalid choice");
}
}
}
Actually, I think, that "import a method" is just a fancy way of saying, I want to call a method of a class from somewhere else:
class MyUtils {
public MyUtils() {
}
public static void method_1() {
// ........
}
public void method_2() {
// ........
}
}
// SOME WHERE ELSE - ANYWHERE YOU CAN CALL METHODS (even in another class)
// CALL STATIC METHOD:
MyUtils.method_1();
// CALL NON STATIC METHOD:
MyUtils myUt = new MyUtils();
myUt.method_2();
myUt..........
In your case you can have a method that takes as argument a Foot instance and an int, and call the turn method.
Use code tags. And the error says: line 5. How are we suppose to know which is line 5 the way you posted. Try next time to show where that line is.
Press the button (code) when you create a post and put your code inside.
Also the problem is: class validateInfo implements validateInfo
The class names must be unique. You cannot have 2 classes with the same name. And when I say classes, I mean java files. You must use different file names and class names for each file. Change the validateInfo file's name to something else. And do the same inside the code. For example:
validateInfo.java
ValidateInfoImpl.java
You should try this:
class ValidateInfoImpl implements validateInfo {
....
}
Also in your main you do this:
updateInfo o= new updateInfo()
And I don't see where you have the updateInfo class defined. I think you should do this:
class ValidateInfoImpl implements validateInfo
{
public void update()
{
//code to update information of customer
}
public static void main(String a1[])
{
ValidateInfoImpl o = new ValidateInfoImpl();
o.update();
System.out.println("Information updated");
}
}
And another tip. It is common to have the files start with capital letter.
when you guys will help then so, i can
please
You have the code already written. Open any book with java and look at the syntax. Java is similar with C. If you written that code on your own you shouldn't have a problem. If you copied it from somewhere else why should we help you cheat.
Also we only give help to those that show effort. So far you have shown no effort.
Ok so i fixed the error by adding a try and catch statement and it works great !!!
int[] shapeArray; // declare an in array shapeArray = new int[rows]; // new array with size rows try { for (int j = 1; j <= rows; j++) { System.out.print("Please enter the number of stars in row " + j + ".."); shapeArray[j - 1] = keyboard.nextInt(); // filling the array } } catch (ArrayIndexOutOfBoundsException e) { // catches the execption e.printStackTrace(); } for (int i = 0; i < rows; i++) { for (int count = 0; count < shapeArray[i]; count++) { String printString = "*"; System.out.print(printString); } System.out.println(shapeArray[i]); } } } } }
one last minor tweak i need to do. how can i get the numbers off of the end of the line that has stars. for example the 3 ,4 ,5 in my output
: Welcome to Star Shapes ... ... a program which lets you draw star shapes First enter the number of rows (1-10) then, Enter the number of stars for each row (1-10) Okay lets start: How many rows would you like ? 3 Please enter the number of stars in row 1..4 Please enter the number of stars in row 2..3 Please enter the number of stars in row 3..5 ****4 // these numbers ***3 // *****5 //
i know it has to do with my nested for loop but i cant seem to get it :/
Actually it wasn't the try catch that you added. …
You gave a code that the poster cannot understand. From the mistakes that were made from the original code, you think that the poster can understand how to create object, instantiate them and also use ArrayLists ?
And I never said that the poster should read the API. I said that the poster should study how to declare variables, because that was clearly the problem. Don't know how to declare variables:
double total grade = int Korean(90) + English(85) + Mathematics(78) + Biology(65) + Chemistry(83);
When someone is having difficulty with the above code I am sure that your code makes perfect sense and if the poster submits that to his teacher, the teacher will have no idea that he copied it from someone else.And whose code is more similar to the poster's ?
So this post where I expressed my opinion with valid arguments has been responded with a negative vote when someone has run out of arguments. The idea of negative votes according to the rules is to mark bad posts, not when you don't like someone's opinion.
Hi, this is not against the rules of these forums. See Member Rules for more information.
I wonder which is easier....reading API (as you suggest) or reading examples of code? Hrmm.....my guess is the later.
You gave a code that the poster cannot understand. From the mistakes that were made from the original code, you think that the poster can understand how to create object, instantiate them and also use ArrayLists ?
And I never said that the poster should read the API. I said that the poster should study how to declare variables, because that was clearly the problem. Don't know how to declare variables: double total grade = int Korean(90) + English(85) + Mathematics(78) + Biology(65) + Chemistry(83);
When someone is having difficulty with the above code I am sure that your code makes perfect sense and if the poster submits that to his teacher, the teacher will have no idea that he copied it from someone else.
And whose code is more similar to the poster's ?
Switch can accept int or char. Everything else would be better suited with an appropriate logic test inside of an if-statement.
...well it can take Strings too, if you parse them (switch(Integer.parseInt(string))) {}
But why bump a thread that is 3 months old?
Actually, for conversation's sake, that example wasn't very good because the String will not always be parsed to an int. What if the programmer wants this String "abc" to be put at the switch.
I believe that the switch should be used if you have a lot of options and you don't want to write multiple ifs. And since you cannot use switch you can use ifs with Strings very easily. I don't know the reason why the developers don't allow Strings in the switch but I hardly believe that this should be used as an argument to compare the 2 languages.
And I remember vaguely another member's comment about not being able to use Strings with switch.
"If you have a lot of if statements that compare Strings then the problem is not that you cannot use switch to make the code simpler, but your logic and your decision to write code with so many ifs".
And I am not talking about 3-5 ifs statements.
And personally, I never found myself in a situation that I wished I could use Strings in a switch.
You will need a while loop. The last for loop will not be inside that while.
You will have the while and will not exit unless a correct name is entered. If it does then exit:
int Index = -1;
String locate = "";
// so that you will enter the first time
// also note that if the name is not in the list, the indexOf returns -1
while (Index == -1) {
// read locate
// get the Index.
// if the locate (Index>=0) is found then the while will exit.
// if it is not, the index will be -1 and you will not exit.
}
// REST OF THE CODE
staffList.removeElementAt(Index);
.....
Have you tried to declare a package at those classes?
Don't forget to set the classpath as well. There are instructions you can follow. Look at the tutorials at the top of the java forum
Try something like this:
import java.util.ArrayList; public class AverageGrade { private ArrayList<Double> grades = new ArrayList<Double>(); public void addGrade(double grade) { grades.add(grade); } public double getTotal() { double sum = 0; for (double grade : grades) sum += grade; return sum; } public double getAverage() { return getTotal() / grades.size(); } public static void main(String[] args) { AverageGrade ag = new AverageGrade(); ag.addGrade(90); // Korean ag.addGrade(85); // English ag.addGrade(78); // Mathematics ag.addGrade(65); // Biology ag.addGrade(83); // Chemistry System.out.println("Total: " + ag.getTotal()); System.out.println("Average: " + ag.getAverage()); } }
Hopefully that gets you on the right path!
We don't give away solution in this forum and you went and did the poster's entire homework. Not only that, but it is clearly that rhoxart faye don't even know how to declare variables and you wrote a code with ArrayList, object instantiation and confusing for loops. You think that offered any significant help? What you think will happen when rhoxart faye tries to deliver your code to the teacher.
A simple solution would be:
class Example1
{
public static void main(String[] args)
{
// declare variables
double total = 0;
double average = 0;
..... // declare the rest of the grades
// add the grades
average= total/5;
System.out.println("total grade :" + total);
System.out.println("average :" + average);
}
I would omit the line:
add(TextArea,BorderLayout.CENTER)
Since you created the scroll with the TextArea as argument, you might want to add only the scroll:
add(scroll,BorderLayout.LINE_START)
Because the scroll already has the TextArea.
You can try that for starters.
You have declare the name to be static. Meaning that you will have only "one" name saved in memory. So no matter how many instances you create there will always be ONE name in memory and will hold of course the last value entered.
Each Student instance has a name and a grade. If you make them non static, each time you create a Student, you will have a different name for each of those instances.
All of those methods need to be NON-static. Because each student must have its own name and method for input
Also prg1 class shouldn't extend the Student class. You don't need to.
help me..
Why it is having an error?
please help me to fix this my assignment..
class Example1
{
public static void main(String[] args)
{
double total grade = int Korean(90) + English(85) + Mathematics(78) + Biology(65) + Chemistry(83);
average= total/5;
{
System.out.println("total grade :" + total);
System.out.println("average :" + average);
}
}
}
end quote.
Start a new thread. And this is not java: Korean(90)
Start a new thread do some studying before posting again.
help me..how to print a sum and average of grades using Java?
Start a new thread with your question and your code. Don't expect anyone to do your homework.
You should use a for loop
Have you ever added an ActionListener to one of your buttons. So whenever you click a button the actionPeformed method will be executed.
It is the same thing. Add a KeyListener to the text field.
Use the addKeyListener method of the JTextField class. You need to implement the KeyListener listener interface. You don't need to write code in all of the methods. Just write for only the keyReleased. When you enter text at the field, every time you release a key from the keyboard that method is executed. So all you have to do is take the text from the field
JTextField nameField = new JTextField();
public void keyReleased(KeyEvent e) {
String name = nameField.getText();
System.out.println(name);
}
If you try to enter the name: JACK, the above method will print:
> J
> JA
> JAC
> JACK
Every time you release a "key" that method is executed. So if you have a method that returns the names that begin with the argument, take the text from the field call that method and show the results. That will be executed every time you keep entering characters in the field.
The hard part is after you have the list with names how to make it look like "google". For that you need to do a little search, on the net. Because I don't have the time to do some searching and point you to right direction.
send me the code of these
Using two dimensional array in java write program to print following Pascal triangle.
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
We don't give away code. We help those who are willing to learn.
Start a new thread, and post what you have done so far.
And we don't work for you to order us: "send me the code of these"
HINT: Each line has the same amount of numbers
First line has 1 (one number), Second line has 1 1 (two numbers), Third line has 1 2 1 (three numbers)
Use 2 for loops one inside the other
Do you have both the .class files and the java files in the same folder?
Test.java, Test.class, Menu.java, Menu.class ? I checked the code and it is correct.
The difference is that I have declared a package. The code should work without one. But is is better to use one. The right way would be to declare a package and set to the classpath the location of that package.
Can you verify at least that all of the above files mentioned are in the same folder?
What I would suggest 1st: Why did you started 2 threads! If you didn't get an answer at the first then will answer when you double posted. What if someone starts posting at one thread then some one else does the same at the second?
Then:
I cannot understand that 60 characters requirement? Does the input needs to be only 60 characters? Or after you get the output you need to print only up to the 60th character?
So I would like to suggest something different with masijade permission.
Don't use StringTokenizer. It is an old class. Better use the split method of the class String.
What I would do is use the replaceAll method of the String class:
import java.io.*;
import java.util.*;
public class Strinpunct{
public static void main (String [] args) throws IOException {
BufferedReader br=new BufferedReader (new InputStreamReader (System.in));
String str;
System.out.println("Enter an input: ");
str=br.readLine();
System.out.println(str); // for debugging
String regex = ""; // regular expression to use
String newStr = str.replaceAll(regex," "); // will replace everything with the empty String
/*
And now you have your final String
*/
}
}
After you get the newStr you can print it, or use the substring method to print only the first 60 characters, or use the split method to turn that String into an array of Strings: String [] array = newStr.split(" ");
Check the API in order to find out what the regular expression should be:
This link …
Web application with JSP, or Desktop application with swing ?
When you declare this: public char[][] bogglefield = new char[height][width];
The height, width variables are undefined, so they are zero, so the bogglefield array has 0x0 size.
At the method: copyPreferences you give values to the height, width, but the array bogglefield has already been created with 0 size.
So I would suggest this:
public char[][] bogglefield = null;
....
public void copyPreferences() {
width = preferences.getWidth();
height = preferences.getHeight();
bogglefield = new char[height][width];
}
Or better, just to make sure that copyPreferences is always called first, because someone might forget to call that method and the array would be null:
class Playgame {
private final List<Integer> lengte = new ArrayList<Integer>();
private int width;
private int height;
private Random random = new Random();
private static char[] alfabet = { 'a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z' };
public char[][] bogglefield = null;
// CONSTRUCTOR. Do the initializations here
public Playgame() {
copyPreferences();
}
// ---->
public void copyPreferences() {
width = preferences.getWidth();
height = preferences.getHeight();
bogglefield = new char[height][width];
}
public void fieldInit(){
for(int i = 0; i < bogglefield.length;i++){
for(int j = 0; j < bogglefield.length; j++){
bogglefield[i][j] = alfabet[random.nextInt(26)];
}
}
}
public void fieldPrint(){
for (int i =0; i < height; i++) {
for (int j = 0; j < width; j++) {
System.out.print(" " + bogglefield[i][j]);
}
System.out.println("");
}
}
void start() { …
i have the same problem! missing return statement
class MOrders
{
int nooforders;// Data members of the class
public int getorder()
{
nooforders = 500;
}
public int displayorders()
{
System.out.println("The number of orders to be delivered:"+ nooforders);
}
public static void main(String args[])
{
MOrders obj = new MOrders ();
obj.getorder();
obj.displayorders();
}
}
end quote.
Did you bother to read the rest of the thread with the answers. You resurrected an old thread just to post a question that has already been answered? Are you too lazy to read the suggestions and advices given and you want some one just to tell you again the answer, instead of you spending 5 minutes to read the rest of the thread?
If it says "missing return statement" then you haven't put a "return" statement. Why you should put one? Read the rest of the thread.
Also, the errors that you get tell you exactly where the error is at your code. Read those errors.
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Exit extends JFrame implements ActionListener{ JLabel ask; JButton btnYes,btnCancel; public Exit(){ super("Exit"); setSize(100,20); setVisible(true); ask=new JLabel("Are you sure you want to exit?"); btnYes=new JButton("Yes"); btnCancel=new JButton("Cancel"); add(btnYes); add(btnCancel); add(ask); btnYes.addActionListener(this); btnCancel.addActionListener(this); } public static void main(String [] args){ Exit ex=new Exit(); ex.setResizable(false); ex.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
I really don't understand on what I did wrong.. please do help me..
Thanks...
First of all, I have already given you the solution for the above problem. I gave you the code. You said it worked. And now you write that code that is exact opposite of you have been told. I gave you the code for the "exit", gave you the code for calling other frames when you click the button, and now you write this code, without even copying what you have been told.
If you have limited time, then why do you post here and you don't study. The API I gave you has the solution. You said you didn't have time to read it but had time to post here?
Also if you don't have access to the net buy a book! Everything you ask is in every basic book.
Every code that has been posted here solves your problems. What do you want? To come to your house and write it for you?
Also you said that this gives you the YES_NO option:
>>>
JOptionPane.showConfirmDialog(new JFrame(),
"Are you sure you want …
I THINK while printing the objet we wil get the answer in console classname with address of the object so
classname itself the object name
First of all that number is not the address of the object. Don't post wrong things that you don't know.
And this thread is way too old and your post doesn't contribute anything. Will some administrator close this thing.
Have you tried: dialog.setVisible(false) ?
First of all you need to use only one Scanner. You don't need two.
Remove the choice2. You don't need it. When you do choice = in.nextInt and you choose 3, then the check you put at the while will make your loop exit.
And most importantly, you read the name but you don't add it to the array. Also when you loop the array you need i<ctr. And every time you add a name at the array increase the ctr. The first time the array is empty, every time you add a name increase the ctr, so the loop will print only up to the number of names entered.
import java.util.Scanner;
import java.io.*;
class AddressBook
{
public static void main(String[]args)
{
Scanner in = new Scanner(System.in);
String[] name = new String[1024];
int ctr = 0;
int choice;
String exit = " Thank you for using my program ";
String menu = " WELCOME TO JOSEPH JENAIRE PUMARAS ADDRESS BOOK";
System.out.printf("\t\t%s",menu);
System.out.println();
do{
System.out.println("[1]Add Person");
System.out.println("[2]Report ");
System.out.println("[3]Exit ");
System.out.println("Enter your choice :");
choice = in.nextInt();
switch(choice)
{
case 1:
System.out.print("Enter Name: ");
name[ctr] = in.next();
ctr++;
break;
case 2:
for (int i = 0 ; i < ctr ;i++)
{
System.out.println(name[i]);
}
break;
}
}while(choice != 3);
}
}
At first the ctr is 0. So the first name should be put at name[0] (name[ctr]). Then you increase the ctr. ctr is now 1. So the next time you call: name[ctr] = in.next the ctr is …
The days left can be a static variable. The rest of the code can be put in a method. Every time you call that method reduce that variable by 1. Assuming that each call represents each day that passes. when the days becomes zero, with the help of the if statements , print that "go home" and then exit the program.
If you want to put everything in a while loop you can do this:
int daysLeft = 30;
while (daysLeft>0) {
....
....
daysLeft--;
}
System.out.println("Go Home");
The isSunny or not can be obtained by generating a random number (Math.random). It returns a number between 0 and 1.