Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,171,136 members, 7,880,569 topics. Date: Thursday, 04 July 2024 at 09:19 PM

A Little Help With Java - Programming - Nairaland

Nairaland Forum / Science/Technology / Programming / A Little Help With Java (953 Views)

Learning To Program With Java by the Fulaman / Programing With Java / Developing A Professional Bluetooth Instant Chat Messenger With Java (2) (3) (4)

(1) (Reply) (Go Down)

A Little Help With Java by adewaleafolabi(m): 9:37pm On Sep 16, 2009
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"wink;
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+"'"wink;
}
else
{
count2++;
System.out.println("'"+x+"','"+y+"'"wink;
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.
Re: A Little Help With Java by OlaMichael(m): 2:49pm On Sep 17, 2009

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+"'"wink;
                }
                else
                {
                    count2++;
                    System.out.println("'"+x+"','"+y+"'"wink;
                    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+"'"wink;
    break;
}
else
{
     count1++;
     System.out.println("'"+x+"','"+y+"'"wink;
}

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!"wink;
}
}

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
Re: A Little Help With Java by adewaleafolabi(m): 6:31pm On Sep 17, 2009
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
Re: A Little Help With Java by aquastar(m): 6:51pm On Sep 23, 2009
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
Re: A Little Help With Java by adewaleafolabi(m): 9:36pm On Sep 25, 2009
Thanks aquastar its just more study for me.
Re: A Little Help With Java by Kobojunkie: 1:45am On Sep 26, 2009


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


IS EQUIVALENT TO HAVING




if(x!=1) //Here lies the problem.if changed to || works well
{   
//proceed
if(y!=1)
{
count1++;
System.out.println("'"+x+"','"+y+"'"wink;
}
else
{
    count2++;
    System.out.println("'"+x+"','"+y+"'"wink;
    break;
}
}
else
{
    count2++;
    System.out.println("'"+x+"','"+y+"'"wink;
    break;
}
Re: A Little Help With Java by kambo(m): 5:11pm On Sep 29, 2009
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.
Re: A Little Help With Java by idozy: 7:29pm On Sep 29, 2009
wink
Re: A Little Help With Java by Ghenghis(m): 8:29pm On Sep 29, 2009
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
Re: A Little Help With Java by kambo(m): 5:19pm On Oct 10, 2009
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<10wink{
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<9wink{
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 {}

(1) (Reply)

C Please Help / modified post no longer working@ / Nigerian Government To Compel Foreign Firms To Use Locally Developed Software

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 34
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.