I have an Assignment that has many questions and the only ones I seem to be having trouble with are the ones with ArrayLists. I need to use a separate main method to enter and print out information.
This is my class
import java.util.ArrayList;
public class HailstoneSequence {
private int n;
public HailstoneSequence(int n) {
this.n = n;
}
public double getn() {
return n;
}
public static ArrayList<Integer> getHailstoneSequence(int n){
ArrayList<Integer> list = new ArrayList<Integer>();
//int i = 0;
while (n != 1);
for (int s : list) {
try {
if(n == 1) break;
if(n % 2 == 0) {
System.out.println(n + " is even, so I take half: " + (n / 2));
}
else
System.out.println(n + " is odd, so I make 3n+1: " + ((n * 3)+1));
// i++;
}
catch (Exception error) {
while (n <= 1) {
System.out.println("You did not enter a valid positive, greater than 1 integer. Please try again: ");
System.out.println();
}
}
}
return list;
}
}
and this is the main class (which does not work)
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class TestHailstoneSequence {
@SuppressWarnings("resource")
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.println("The Hailstone Sequence takes a number and if it odd it multiples it by 3 and adds 1,"
+ "\nit divides it by 2 and carries on until it reaches 1. \nPlease enter a positive number"
+ " (greater than 1) to generate the Hailstone Sequence: ");
int n = input.nextInt();
HailstoneSequence aHailstoneSequence = new HailstoneSequence(n);
System.out.println(Arrays.toString(aHailstoneSequence.list));
}
}
Please help me understand how to print out the results
You declared getHailstoneSequence
method as static one you should call it and store to a variable if you need in another operation and printing like this:
ArrayList<Integer> list = HailstoneSequence.getHailstoneSequence(n);
System.out.println(list);
For your current case the main method will look something like this:
import java.util.Scanner;
public class TestHailstoneSequence {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("The Hailstone Sequence takes a number and if it odd it multiples it by 3 and adds 1,"
+ "\nit divides it by 2 and carries on until it reaches 1. \nPlease enter a positive number"
+ " (greater than 1) to generate the Hailstone Sequence: ");
int n = input.nextInt();
input.close(); // do not forget to close the resource
// if you use static method in your HailstoneSequence class you can remove
// field with name "n" from that class and you don't need to create an object in this case
// Also I'd rename the class from HailstoneSequence to something like HailstoneSequenceCalculator
System.out.println(HailstoneSequence.getHailstoneSequence(n));
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.