For loop problem

Show 40 post(s) from this thread on one page
Page 2 of 2 First 12
• 01-22-2008, 02:16 PM
mcal
Thanks a lot. Its really kind of you to help me with this problem. I have understood what you told me, but unfortunately, its still repeating questions( to be precise it is repeating only the last question for 3 to 4 times). This is the code, where i put the source code you told me. I think that there is something wrong with the way "pos" is calculated. But i can't figure it out. Have i have done something wrong? Thanks a lot again and i'm sorry for bothering you. Thanks again. :-)

The code:

Code:

```  public void askQuestions(String[] questions, String[] answers) {               int count = 0;         int point = 0;                       int[] A = new int[questions.length];         int[] B = new int[A.length];               int countA = A.length;         int countB = 0;                 for (int i = 0; i < A.length; i++){             A[i] = i;           }             while (countA > 0){       Random generator = new Random();       int pos = generator.nextInt(A.length);         B[countB] = A[pos];       countB++;         for (int i = pos; i < A.length - 1; i++){         A[i] = A[i + 1];         }       countA--;     }               for(int j = 0; j < questions.length; j++) {                       timeForMore = true;                     int randomIndex = B[j];           String input = JOptionPane.showInputDialog(null, questions[randomIndex]);                   if(answers[randomIndex].equalsIgnoreCase(input))                     count++;  // incrementing counter if entered answer is correct           point++;                           if(!timeForMore) // if time is over, the program executes the loop an stops asking questions.                 break;     }                         JOptionPane.showMessageDialog(null, "You answered " + count +                                       " out of " + questions.length +                                       " questions correctly."); }```
• 01-22-2008, 11:37 PM
tim
Bug found
Sorry for that.

This time I use an IDE and I found a silly bug. :rolleyes:
Change this part:
Code:

```Random generator = new Random(); int pos = generator.nextInt(A.length);```
to this
Code:

```Random generator = new Random(); int pos = generator.nextInt(countA);```
I tested the method and it should work now. ;)
• 01-22-2008, 11:52 PM
mcal
Yeah it worked 100&#37; now. Thanks a lot. That was really kind of you. And no problem, i knew it was a small problem somewhere in the code, but without your help i would never had done it. Thanks again. :-)
• 01-23-2008, 12:03 AM
tim
Good
I'm glad it works now. If you want, I can show you how to use classes and vectors. Maybe some streaming perhaps? The stuff that one can do with Java is amazing.

Good luck with your studies. ;)
• 01-23-2008, 12:17 AM
mcal
Thanks, that would be a great idea. :-) But now i have to go, because its very late (11:16pm). Cu and thanks for everything. :-)
• 01-23-2008, 09:52 AM
tim
Vectors
Hello mcal.

Since you seem interested I will start with vectors. In the java.util package are many tools and data structures that one can use for a variety of problems. For most problems, I prefer to use vectors. To use vectors, make sure that you import the java.util.Vector class.

Okay, a vector is a dynamic data structure unlike arrays. That means that vectors will grow automatically as you need more space. When using vectors, it is good practice to use generics. To define a vector object that can contain a variety of different objects we divine, lets say data, like this:
Code:

`Vector[COLOR="RoyalBlue"]<Object>[/COLOR] data = new Vector[COLOR="RoyalBlue"]<Object>[/COLOR]();`
This will create a empty vector of Object types. At the moment, data has no elements. To add an element, we use the Vector.add() method like this:
Code:

```data.add("There is no spoon"); data.add(4400);```
Note that 4400 is a literal and a primitive type. Java will box this automatically, that is turn the int into an Integer. To get the size of a vector, we use the Vector.size() method. To access an element of the vector, we use the Vector.get() method. In the code below we will print all the objects:
Code:

```for (int i = 0; i < data.size(); i++){     System.out.println((data.get(i)).toString()); }```
Are you following mcal? ;)
• 01-23-2008, 08:56 PM
mcal
Yeah i understood that. Thanks a lot, Tim. :) ;)
• 01-23-2008, 10:42 PM
tim
Hello mcal :p

Lets add some classes to the show. Lets have the abstract class Animal and a few extensions of it:
Code:

```public abstract class Animal(){     protected String sound;     public Animal(){         sound = "";     }     public void printSound(){         System.out.println(sound);     }     public abstract void createSound(); }```
And the extensions:
Code:

```public class Dog extends Animal{     public Dog(){         super();     }     public void createSound(){         sound = "bark";     } }```
Code:

```public class Snake extends Animal{     public Snake(){         super();     }     public void createSound(){         sound = "hisss";     } }```
Let's create a vector of Animal instances.
Code:

```Vector<Animal> animals = new Vector<Animal>(); Dog dog = new Dog(); Snake snake = new Snake(); dog.createSound(); snake.createSound(); animals.add(dog); animals.add(snake);```
What all this code does is create a structure where we can define classes that inherit attributes and behavior from their parent. So, I've started with an abstract class Animal. An abstract class cannot be instanced. This makes sense, since we cannot create an Animal, unless we know what type of animal it is. The subclasses of Animal, Dog and Snake, are not abstract. The reason for this structure is that when you collect information, you want some way of handling all your data types will the minimum amount of work and code. Lets say that I want to print all the sounds that the animals make in my vector.
Code:

```for (int i = 0; i < animals.size(); i++){     Animal animal = animals.get(i);     animal.printSound(); }```
Now, if I wanted to add a Cat class, I just have to extend the Animal class and make sure I implement the createSound() abstract method. I don't have to touch the for loop above. This makes it easy to extend your Java programs. :D

This is all very handy, but what do you do if you want to know what classes you are handling? So, mcal, are you still interested? Just ask if something is unclear. ;)
• 01-24-2008, 09:58 AM
mcal
Yeah, thanks Tim, this is really interesting. Ok thanks a lot. You'r Awesome! ;)
• 01-24-2008, 10:37 AM
tim
Casting and instanceof
Hello mcal

I'm glad you feel that way. Lets continue with the instanceof keyword and casting.
Quote:

Originally Posted by tim
This is all very handy, but what do you do if you want to know what classes you are handling?

The answer to my question is the instanceof keyword. The instanceof keyword is used to test if an object is an instance of a class or subclasses of it. The condition:
Code:

`<object> [COLOR="RoyalBlue"]instanceof [/COLOR]<class>`
,will give a boolean value. For example:
Code:

```boolean result1 = dog instanceof Dog; boolean result2 = dog instanceof Animal;```
both result1 and result2 will now be true. Now, lets modify our for loop to display which classes we are working with:
Code:

```for (int i = 0; i < animals.size(); i++){     Animal animal = animals.get(i);     if (animal instanceof Dog) System.println("A dog goes:");     if (animal instanceof Snake) System.println("A snake goes:");     animal.printSound(); }```
I'm going to modify the Dog class a bit:
Code:

```public class Dog extends Animal{     public Dog(){         super();     }     public void createSound(){         sound = "bark";     }     public void howl(){         sound = "hawooooo";     } }```
Now, Dog has a howl method that is not inherited from Animal. So how will you access it in the for loop? The answer is to use casting. Casting is when you force one type into another. You can only cast a super class into one of its subclasses. To cast we use the synax:
Code:

`<subclass here> child = (<subclass here>)parent;`
for example, if I know the animal object is a dog then:
Code:

`Dog dog =[COLOR="Magenta"] (Dog)[/COLOR] animal;`
Back to the for loop. Let's make the dog howl, and note that snakes cannot howl:
Code:

```for (int i = 0; i < animals.size(); i++){     Animal animal = animals.get(i);     if (animal instanceof Dog){         Dog castedDog = (Dog)animal; // dog can also be used, but lets ignore that for now :)         castedDog.howl();         System.println("A dog goes:");     }     if (animal instanceof Snake) System.println("A snake goes:");     animal.printSound(); }```
We can now handle objects in a generic way. On your quiz problem you needed to save data and read it again. That is a real word problem that programmers face all the time.

Object serialization allows you to take an object just as it is and save or load it at will. Object serialization will make it possible to save an entire data structure will multiple fields and sub data structures to be saved and loaded in just a few lines of code. :eek:

Are you interested mcal? Please ask if you get stuck or if there is a bug somewhere. :D
• 01-24-2008, 07:25 PM
mcal
Yeah we have done serialization at school. We have used it in object files. We have done random files too (but i didn't understand random files much). And we have done type casting too. Thanks Tim, i really am appreciating this. Thanks again. :-)
• 01-25-2008, 04:33 PM
tim
Excellent
Hello mcal.

I was going to post on serialization and interfaces, but it looks like you already know that. I'm glad, but unfortunately, this is where my knowledge in polymorphism and data structures end. I have recently studied XML, but I still have no JDBC, HTML, SQL, ect experience yet. I'm starting second year varsity now. :D

Thank you for your interest mcal. ;)
• 01-25-2008, 04:51 PM
mcal
Ok Tim, thanks for everything. I really appreciated your help. And i wish you Good Luck for your studies. Thanks a lot again. :-)
Show 40 post(s) from this thread on one page
Page 2 of 2 First 12