# I need help with this program

Printable View

• 07-04-2007, 05:09 AM
Daniel
I need help with this program
It doesn't show me any error but it doesn't generate enough questions... i'm new at java so i really dont know how to get this to work... the program is for generating questions on subtraction of fractions.. i need an eye to help me on this.
Code:

public class FractionSubtraction
{
public static void main(String[] args)
{
int a, b, c, e, f, g, ans, deno;
String sent, num1, num2, fin;
int count = 20; //number of questions
String[] list = new String[count + 1];
for (int i=0; i < list.length; i++)
{
a = (int) (1 + Math.random() * 20);
b = (int) (1 + Math.random() * 20);
c = (int) (1 + Math.random() * 20);
e = (int) (Math.random() * 11);
f = (int) (Math.random() * 11);
while (b == 1)
{
b = (int) (1 + Math.random() * 20);
}
while (e < f)
{
e = (int) (Math.random() * 11);
f = (int) (Math.random() * 11);
}
while (a >= b)
{
a = (int) (1 + Math.random() * 20);
}
while (c >= b || (c == a && b != 2))
{
c = (int) (1 + Math.random() * 20);
}
while ((e*b + a) - (f*b + c) <= 0)
{
while (e < f)
{
e = (int) (Math.random() * 11);
f = (int) (Math.random() * 11);
}
while (a >= b)
{
a = (int) (1 + Math.random() * 20);
}
while (c >= b || (c == a && b != 2))
{
c = (int) (1 + Math.random() * 20);
}
}
g = 0;
ans = (e*b + a) - (f*b + c);
while (ans >= b)
{
ans = ans - b;
g++;
}

deno = b;
if (e > 0)
{
num1 = "" + e + " ";
} else
{
num1 = "";
}
if (f > 0)
{
num2 = "" + f + " ";
} else
{
num2 = "";
}
if (g > 0)
{
fin = "" + g + " ";
} else
{
fin = "";
}
if (ans > 0) //reduce fraction in final answer
{
for (int red = 2; red <= deno; red++)
{
while (ans%red == 0 && deno%red == 0)
{
ans = ans/red;
deno = deno/red;
}
}
sent = "" + num1 + a + "/" + b + " - " + num2 + c + "/" + b + " = " + fin + ans + "/" + deno;
} else
{
sent = "" + num1 + a + "/" + b + " - " + num2 + c + "/" + b + " = " + fin;
}
for (int j = 0; j < i; j++)
{
if (sent.equals(list[j])) // eliminate any repeated questions
{
i--;
break;
} else if (j == i -1)
{
list[i] = sent;
System.out.println(list[i]);
}
}
}
}
}

Thanks

Daniel:o
• 07-04-2007, 05:12 AM
Eric
You can debug this by simply putting some print statements in your loops and print out the variables involved with producing your output That way you can see what happens up to the point where it gets stuck.

I would venture to guess you are either getting stuck in an infinite loop or your loop is ending prematurely.
In either case you will be able to figure that out by printing out the variables involved.
In order to learn how to program you must also learn common debugging techniques. If you cannot use a debugging tool then print statements are you next best friend in debugging.

Greetings

Eric
• 07-04-2007, 05:14 AM
Daniel
Sorry i counted accordin to my program but not the one i posted here the infinite while loop i mentioned is the following:

Code:

while ((e*b + a) - (f*b + c) <= 0)
Thanks

Daniel:o