A Little Help With Java

Welcome. Please Login, Register, Or Activate! 
type your username and password to login
Date: November 22, 2009, 10:34 PM
430978 members and 298061 Topics
Latest Member: 2f
Nairaland [Nigerian Forum] Home Help Search Who is currently online? Login Register
Nairaland Forum  |  Technology  |  Programming  |  A Little Help With Java
Pages: (1) Go Down Send this topic Notify of replies
Author Topic: A Little Help With Java  (Read 269 views)
adewaleafolabi (m)
A Little Help With Java
« on: September 16, 2009, 09:37 PM »

i have a little problem with java.

for(i=0;i<=10;i++)
    {
        System.out.println(i);
    }
the output is 0 1 2 3 4 5 6 7 8 9 10
my problem with this is that it begins with 0. Now since i=0 and its less than 10, its supposed to increment it by one so the output should have started with 1.
I could just change the value of i such that i=1; but that would create another issue

   ArrayList<Integer> points;
       points = new ArrayList<Integer>();
       System.out.println(points.size());

   for(i=0;i<=points.size();i++)
       {
        points.add(i);
        System.out.println(i+" The size is "+points.size());
        System.out.println(points.get(i));
        if(i==9)
        {
            System.out.println("Out ok");
            break;
        }
       
       
       }
Now my array would start from 0 which of course i don't want.

if i>1; then would generate an exception


Problem 2: I wrote a program to roll a pair of die and count the number of rolls. The program would end if it gets a 1,1.

public class NewEmptyJavaApp2 {


   public static void main(String args[])
   {
            int x=0;
            int y=0;
            int count = 0;
            int count1 = 0;
            int count2 = 0;

            while(true)
            {
                x=(int)(6*Math.random()+1);
                y=(int)(6*Math.random()+1);
                count++;
                if(x!=1 && y!=1) //Here lies the problem.if changed to || works well
                {    count1++;
                     System.out.println("'"+x+"','"+y+"'");
                }
                else
                {
                    count2++;
                    System.out.println("'"+x+"','"+y+"'");
                    break;
                }
               
            }
            System.out.println("Total:"+count);
            System.out.println("Non snake:"+count1);
            System.out.println("snake:"+count2);
   }
}

The problem here is the && operator. From my understanding && is supposed to evaluate both conditions but in this case if x=1 and y>2 the program would end which is totally incorrect.

Please could someone help me clarify these issues. Thanks.
OlaMichael (m)
Re: A Little Help With Java
« #1 on: September 17, 2009, 02:49 PM »

Quote
Problem 2: I wrote a program to roll a pair of die and count the number of rolls. The program would end if it gets a 1,1.

public class NewEmptyJavaApp2 {


   public static void main(String args[])
   {
            int x=0;
            int y=0;
            int count = 0;
            int count1 = 0;
            int count2 = 0;

            while(true)
            {
                x=(int)(6*Math.random()+1);
                y=(int)(6*Math.random()+1);
                count++;
                if(x!=1 && y!=1) //Here lies the problem.if changed to || works well
                {    count1++;
                     System.out.println("'"+x+"','"+y+"'");
                }
                else
                {
                    count2++;
                    System.out.println("'"+x+"','"+y+"'");
                    break;
                }
               
            }
            System.out.println("Total:"+count);
            System.out.println("Non snake:"+count1);
            System.out.println("snake:"+count2);
   }
}

The problem here is the && operator. From my understanding && is supposed to evaluate both conditions but in this case if x=1 and y>2 the program would end which is totally incorrect.

Please could someone help me clarify these issues. Thanks.
 

Your understanding of the && operator is not correct.  The && operator evaluates to true only (and thats a big ONLY) if all conditions specified evaluates to true.

so in your case, the first part evaluates to false (i.e. x != 1) and the second part will return true, as y != 1 will be true for all values of y excepting 1. Thus causing your if block to be evaluated.

There are two solutions. One is simply switching your test so that instead of what you have up there, you do the following.
if(x==1 && y==1) //Here lies the solution
{
   count2++;
    System.out.println("'"+x+"','"+y+"'");
    break;
}
else
{
     count1++;
     System.out.println("'"+x+"','"+y+"'");
}

So in effect, you're testing for when both dice return 1(i.e. equals 1) and if nthey do, you quit, else you continue.

The Second and PREFERED solution is to re-write the entire program properly as it is quite crappy the way it is now.
Too many counters, bad variable names, etc.

Here's a solution I came up with,

public class RollCounter
{
   private int firstDice = 0;
   private int secondDice = 0;
   private int numRolls = 0;
   
   private void rollDice()
   {
      firstDice = (int) (6* Math.random() + 1);
      secondDice = (int) (6* Math.random() + 1);
      numRolls++;
   }
   
   public void run()
   {
      while(true)
      {
         rollDice();
         if (firstDice == 1 && secondDice == 1)
            break;
         else
         {
            System.out.println("Dice 1: " + firstDice + ", Dice 2: " + secondDice);            
         }         
      }
      System.out.println("Total Rolls: " + numRolls );      
   }
   /**
    * @param args
    */
   public static void main(String[] args)
   {
      RollCounter counter = new RollCounter();
      counter.run();
      System.out.println("Game Ended!");
   }
}

As seen, the names represent the program more effectively, only 1 counter used etc etc,


As for question 1, I am at a loss as to what the problem is???

adewaleafolabi (m)
Re: A Little Help With Java
« #2 on: September 17, 2009, 06:31 PM »

Thanks for the reply. That solved the problem but still am not quite clear on this issue.
I guess its more studying for me as am ne to java.
Okay for question 1, the problem is that the ouput starts from zero instead of 1
for(i=0;i<10;i++)
{
    System.out.println(i);
}
since i=0 already the first value of i that should be printed is 1 and not 0;  Thanks
aquastar (m)
Re: A Little Help With Java
« #3 on: September 23, 2009, 06:51 PM »

output starts from 0 not 1 because this is how a for loop works,

for ( exp1; exp2; exp3 )
{
.
//stuff
.
}

1. the interpreter evaluates exp1 (in your case i=0)
2. checks for boolean expression in exp2 (in your case, i<=10)
3.  if exp2 evaluates to true, it run the code (in you case the code will run with i= 0)
4. AFTER running the code, it executes exp3 (in your case, increments i by 1)
5 then goes back to step 2 and repeat the whole thing until i=11 in which case the "stuff" part with not run since exp2 would not evaluate to true

like i said your probably know all this by now,  i would help with your newest troubles though, if i can
adewaleafolabi (m)
Re: A Little Help With Java
« #4 on: September 25, 2009, 09:36 PM »

Thanks aquastar its just more study for me.
Kobojunkie
Re: A Little Help With Java
« #5 on: September 26, 2009, 01:45 AM »

Code:

if(x!=1 && y!=1) //Here lies the problem.if changed to || works well
{    count1++;
     System.out.println("'"+x+"','"+y+"'");
}
else
{
    count2++;
    System.out.println("'"+x+"','"+y+"'");
    break;
}

IS EQUIVALENT TO HAVING


Code:

if(x!=1) //Here lies the problem.if changed to || works well
{   
//proceed
if(y!=1)
{
count1++;
System.out.println("'"+x+"','"+y+"'");
}
else
{
    count2++;
    System.out.println("'"+x+"','"+y+"'");
    break;
}
}
else
{
    count2++;
    System.out.println("'"+x+"','"+y+"'");
    break;
}
kambo (m)
Re: A Little Help With Java
« #6 on: September 29, 2009, 05:11 PM »

i've not tested this yet
but i think maybe code could be different if u tried this:


for(int i=0;i<10;++i){

System.out.println(i);

}

typing from a public pc tell me if it gives u what u want.
idozy
Re: A Little Help With Java
« #7 on: September 29, 2009, 07:29 PM »

 Wink
Ghenghis (m)
Re: A Little Help With Java
« #8 on: September 29, 2009, 08:29 PM »

In a loop of this type
for ( exp1; exp2; exp3 )
{
.
//stuff
.
}

exp1 is evaluated, exactly once
exp2 is evaluated is a boolean expression that determines if the loop should continue
exp3 is evaluated every time the loop is iterated.


A && B

like you guessed && has a sort of short circuit effect hence,

if A is true , B would be evaluated
if A is false, B is ignored (this is because false AND anything results in false).

Smiley
kambo (m)
Re: A Little Help With Java
« #9 on: October 10, 2009, 05:19 PM »

hope this reply finds you.
you problem suffers from a logical error.
how would u process an array with a zero subscript element using a for loop?

this worked:
   int x=0;
for(x=0;x<10;){
x++;
System.out.println(x);

}

the print out start from 1 but exceeds 10 before it stops.

or u could try this:
for(int x=0;x<9;){
System.out.println(++x);
}
subscript exits at 10.
so u get it?
skip implementing the third part of the loop signature.
rather increment x within the loop 'body' i.e between the {}
 Ebooktalk.com - A New Ebooks Web Site  Project Topics  Please Read My Story  Page 2
Pages: (1) Go Up Send Topic to Friend by E-mail Reply 


Sections: Autos/Cars (2) Jobs/Vacancies (2) (3) Career Talk Education General(2) Politics Romance Computers Phones Travel
Sports Fashion Health Religion Celebrities TV/Movies (2) Music/Radio (2) Books Webmasters Programming

Links: Page1 Page2 Page3 Page4 Page5 Page6 Page7 Page8 Page9 Page10

Nairaland is owned by Oluwaseun Osewa. See also: Nairalist Classified Ads
Nairaland Forum | Powered by SMF 1.0.12.
© 2001-2005, Lewis Media. All Rights Reserved.