/* Copyright (c) 2020 Marek Küthe This program is free software. It comes without any warranty, to the extent permitted by applicable law. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See http://www.wtfpl.net/ for more details. */ import java.util.InputMismatchException; import java.util.Scanner; public class CollatzConjecture { public static void main(String[] args) { int startNum = 0; if (args.length >= 1) { try { startNum = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.err.println( "Error: The number supplied as a command line argument could not be recognized as such."); System.exit(1); } } else { try (Scanner scanner = new Scanner(System.in)) { startNum = scanner.nextInt(); } catch (InputMismatchException e) { System.err.println("Error: The number entered was not recognized."); System.exit(1); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); e.printStackTrace(System.err); System.exit(1); } } int workNum = startNum; int counter = 0; while (workNum != 1) { if (workNum % 2 == 0) { System.out.print(workNum + " / 2 = "); workNum = workNum / 2; System.out.println(workNum); } else { System.out.print(workNum + " * 3 + 1 = "); workNum = workNum * 3 + 1; System.out.println(workNum); } counter++; } System.out.println("The program was able to reach the number " + workNum + " in " + counter + " " + (counter == 1 ? "round" : "rounds") + "!"); } }