/** * Returns a string consisting of a Hailstone sequence beginning with the pos
ID: 668219 • Letter: #
Question
/**
* Returns a string consisting of a Hailstone sequence beginning with the positive integer n and ending with 1. The
* string should consist of a sequence of numerals, with each numeral followed by a single space. When a numeral m
* (other than 1) appears in the sequence, it should be followed by nextHailstone(m).
*
* For example, nextHailstone(1) should return "1 " and nextHailstone(5) should return "5 16 8 4 2 1 ".
*
* IMPLEMENTATION NOTE: Make use of your nextHailstone method. You'll need to use a loop to call it the right number
* of times.
*/
public static String hailstones (int n)
{
return "";
}
Explanation / Answer
package hailstone;
import java.util.Scanner;
public class Hailstone {
static String str="";
static String;
static int n;
public static void main(String[] args) {
int i=0;
String output="";
//accept input from user
Scanner in = new Scanner(System.in);
System.out.println("Enter the first number in series ");
n=in.nextInt();
//string output contains final hailstone seq
output=nextHailstone(n);
System.out.println("Hailstone Sequence is "+str);
}
public static String nextHailstone (int n){
str=Integer.toString(n)+" ";
while(!str.endsWith(one)){
if(n%2==1)
{
n=n*3+1;
}
else
{
n=n/2;
}
str=str+" "+Integer.toString(n);
}
return str;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.