-
Reverse the integers
i have the following code and it compiles and works perfectly. But the project wants me too do the revers as well
for example) if i inter 120, the program returns factors which are 2 2 2 3 5
but i also need it to return the reverse 5 3 2 2 2
the book wants me to use a StackOfIntegers class
how would i do this...i need complete details please
thank you
public class factors {
public static void main(String args[])
{
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print(
"Enter a positive integer: ");
int number = input.nextInt();
System.out.print("The factors for " + number + " is:");
int factor = 2;
while (factor <= number)
{
if (number % factor == 0)
{
number = number / factor;
System.out.print(" "+factor);
}
else {
factor++;
}
}
}
}
-
Sounds like you need to create your own StackOfIntegers class? Does it say how you need to create this class?
If it were me, I'd just add all the factors to an ArrayList. Once in the array, loop through it forwards and print out your results, then loop a second time backwards and print out the results.
-
Hi, this works fine:
Code:
public class factors
{
public static void main(String args[])
{
int[] facts = new int[100];
int i = 0, j = 0;
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter a positive integer: ");
int number = input.nextInt();
System.out.print("The factors for " + number + " is:");
int factor = 2;
while (factor <= number)
{
if (number % factor == 0)
{
number = number / factor;
facts[i] = factor;
i++;
}
else factor++;
}
for (j = i - 1; j >= 0; j--)
{
System.out.print(" " + facts[j]);
}
}
}
-
yes, i know what you said works, but i need a program that does both at the same time, thats what im haivng trouble with. i can't seem to combine a program that says for example
if you input 120,
to show 5 3 2 2 2
also revers: 2 2 2 3 5