Instructions
Objective
Write a java assignment program to implement algorithms in integers.
Requirements and Specifications
Pick a positive integer. Then repeatedly apply this (rather silly) process:
- If your number is even, pide it by 2, and the result becomes your new number.
- If your number is odd, multiply it by 3, and add 1; that result becomes your new number.
- Repeat this process until the result is the number 1.
Why stop when the number is 1? Because once you get to 1, you enter a loop. Try it: 1 -> 4 -> 2 -> 1 -> 4 ->... Hopefully, you get the idea.
You might wonder why we are even bothering to discuss this little process. It turns out to have a rather interesting history in the study of mathematics. Every positive integer that anyone has ever tried always ends up at the number 1. Always. However, no one has ever PROVEN that no matter what positive integer you choose, you will always finish in that 1,4,2,1 loop. Many mathematicians have TRIED to prove it, but (at least so far) to no avail.
Don't get nervous - I'm not going to ask you to prove anything. Instead, I want you to write a program that people can use to explore this little process.
Next week, you should develop your HW1 program. THIS week, I only want you to THINK about the problem, and design your solution without knowing what language you will use to implement your design.
Your program will interact with a human user via keyboard input and screen output. When the program starts, your program should print out a short explanation of the process described above. Then your program should give the interact user three choices:
- designate a number to start the process
- designate a range of numbers to use with the process
- quit the program
If the user decides to quit the program, exit with a pleasant message. If necessary, wait for the user to press ENTER to allow the user to see your "goodbye" message.
If the user designates a number to start the process, execute the process until the number becomes 1. Figure out a method to gracefully display the entire action (each number generated), and finish with the number of steps it took to get to 1. (Don't count the starting number from the user, and do count the 1 when you reach it.) If someone puts in a 1, then the program should say there were 3 steps (please see above). Wait for the user to push ENTER before moving on.
If the user wants to designate a range of numbers, then prompt for the smaller number, and prompt for the larger number. I'll call the smaller number S and the larger number L. When you have both those numbers, then run the process for all of the numbers from S to L, inclusive, one at a time. For each of the numbers, keep track of the shortest run (until 1), the longest run, and the average length of a run. When your program has done all the required processes, report the findings to the screen. Again, wait for the user to press ENTER to move on.
Whenever you prompt the user for an input, give clear directions on what inputs are legal. If the user enters illegal input, tell the user what went wrong, and reprompt. Keep going until the user enters a legal input.
Whenever you give output, use clear language and decent, readable formatting.
If the user chooses quit, you stop. If the user chooses either of the other two choices, you keep going, by again giving the user the three choices.
No matter what programming language you eventually use, start the source code for your program with an extensive opening comment that includes your name, the date, the name of our class, an explanation of what the program is designed to do, a description of the central data structures in your program, and an explanation of any external files used. If your program doesn't include any of these, then indicate that by listing the category, and indicating "None," or something like that. For example, if the program doesn't use external files, your opening comment should include something like:
External files: None
Internal comments should explain important data structures where they are declared and/or used, delineate large sections of code (“paragraphing comments”), and clarify anything clever or hard to understand in your code. I grade documentation carefully and critically, so I recommend that you spend some time on your opening and internal comments.
We will test your program by recompiling it, by running it with different inputs and by examining what your program does.
Source Code
/*
Author:
Email:
Date:
Class:
Explanation:
Program that applies the following procedore to an integer higher than 1
- If your number is even, divide it by 2, and the result becomes your new number.
- If your number is odd, multiply it by 3, and add 1; that result becomes your new number.
- Repeat this process until the result is the number 1.
The program starts asking to the user if the/she wants to enter a single number of a range of numbers.
It also asks to the user if he/she wants to exit the program
The input is read using the object Scanner.
The program only uses the array structure to store numbers when the user selects the
option to enter a range of numbers.
If the users selects the first option, he/she will enter a single integer
and then the program will show the resulting value after the steps explained above are done.
This process is done inside a while-loop that will continue until the resulting number is equal to 1
If the user selects the second option, he/she will enter two integers which represents
the initial and final value of the range of numbers
For this case, the numbers are then saved into an array and then, for eachh number in the
range, the algorithm is applied.
The program will check for invalid inputs such as non-integer, numbers smaller than 1, or in case
of the second option, the program checks that the second number is higher than the first one
External files: None
*/
import java.util.Scanner;
public class Main
{
public static void displayMenu()
{
// This function prints the main menu
System.out.println("1/A. Enter a number");
System.out.println("2/B. Enter a range of number separated by comma");
System.out.println("3/C. Quit");
}
public static void executeProcess(int number)
{
// base case
if(number == 1)
{
System.out.println("Number of steps: 3");
System.out.println("[1]->4->2->1");
return;
}
// execute the algorithm here. For each step, the number is printer
System.out.println("");
String ret = "";
int steps = 0;
while(number != 1)
{
if(steps == 0)
ret += "[" + String.valueOf(number) + "]";
else
ret += String.valueOf(number);
//ret += String.valueOf(number);
if(number %2 == 0) // number is even
number = number/2;
else // is odd
number = number*3+1;
if(number != 1)
ret += "->";
else
ret += "->1";
steps++;
}
steps++;
System.out.println("Number of steps: " + steps);
System.out.println(ret);
System.out.println("");
}
public static void main(String[] args)
{
// create scanner
Scanner sc = new Scanner(System.in);
// First, display greet message
System.out.println("Welcome! In this application, you'll enter a number (or numbers) and a process will be repeated. The steps of these process are the following:");
System.out.println("-------------------------------------------------");
System.out.println("1. If the number is even, divide it by 2");
System.out.println("2. If the number is odd, multiply it by 3 and add 1");
System.out.println("3. Repeat this process until then result is 1");
System.out.println("The idea is prove that, given any number, the result is always 1.");
System.out.println("-------------------------------------------------");
while(true)
{
// Display menu
displayMenu();
// get menu option
System.out.print("Enter an option: ");
//int option = Integer.valueOf(sc.nextLine());
String option_str = sc.nextLine().toLowerCase();
System.out.println("");
if(option_str.compareTo("a") == 0 || option_str.compareTo("1") == 0) // enter a number
{
System.out.print("Enter a positive number: ");
try
{
int number = Integer.valueOf(sc.nextLine());
if(number >= 1)
executeProcess(number);
else
System.out.println("Please enter a positive number higher than 1.");
}
catch(Exception ex)
{
System.out.println("Please enter a valid number.");
}
}
else if(option_str.compareTo("b") == 0 || option_str.compareTo("2") == 0) // enter a set of numbers
{
int[] arr = new int[] {};
int lower, upper;
try
{
System.out.print("Enter lower value: ");
lower = Integer.valueOf(sc.nextLine());
if(lower >= 1)
{
System.out.print("Enter upper value: ");
upper = Integer.valueOf(sc.nextLine());
if(upper >= 1 && upper > lower)
{
for(int i = lower; i <= upper; i++)
{
executeProcess(i);
}
}
else
System.out.println("Upper value must be positive and higher than lower value.");
}
else
System.out.println("You must enter a valid positive integer.");
}
catch(Exception ex)
{
System.out.println("Please enter a valid number.");
}
}
else if(option_str.compareTo("c") == 0 || option_str.compareTo("3") == 0)
{
System.out.println("Good Bye!");
break;
}
else
{
System.out.println("Please enter a valid menu option.");
}
System.out.println("");
}
}
}
Related Samples
At ProgrammingHomeworkHelp.com, students can find a range of expertly crafted Java assignment samples. Our website is dedicated to providing comprehensive assignment support, ensuring that students grasp complex Java concepts effortlessly. The Java samples showcase high-quality solutions to typical problems, offering a valuable resource for learning and reference. Whether you're struggling with object-oriented programming, data structures, or GUI development, our samples will guide you through your assignments, helping you achieve academic success with confidence and ease.
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java