Java- Happy Number PDF

Title Java- Happy Number
Course Object Oriented Programming and Data Structures
Institution California State University Long Beach
Pages 3
File Size 37.8 KB
File Type PDF
Total Downloads 51
Total Views 134

Summary

Java- Happy Number...


Description

import java.util.ArrayList; import java.util.Scanner; public class happynumber{ static Scanner in = new Scanner(System.in); static ArrayList MyList = new ArrayList(); public static void main(String[] args) { System.out.print("\n1) Show happy sequence for a number"); System.out.print("\n2) Show all happy numebrs in a range"); System.out.print("\n3) Exit"); int UserChoice = in.nextInt(); while (UserChoice != 3) { switch (UserChoice) { case 1: System.out.print( "Input:"); int number = in.nextInt(); while (checkNum(number) == false) { System.out.print("Enter a positive number: "); number = in.nextInt(); } boolean result = happy(number); System.out.print("Output: "); for (int o = 0; o < MyList.size(); o++) { if (o + 1 == MyList.size()) { System.out.print(MyList.get(o) + " "); } else { System.out.print(MyList.get(o) + ", "); } } if (result) { System.out.println("Happy\n"); } else { System.out.println("Not Happy\n"); } break; case 2: System.out.print( "Start number:"); int start = in.nextInt(); while (!checkNum(start)) { System.out.print("Enter a positive number: "); start = in.nextInt(); } System.out.print( "End number:"); int end = in.nextInt(); while (checkNum(end) == false) {

System.out.print("Enter a positive number: "); end = in.nextInt(); } System.out.print("\nHere are the happy numbers:"); int count = 0; for(int a = start; a 50) { count = 50; } } else { System.out.print("."); count++; } } System.out.println("\nDone\n"); break; default: System.out.println("Invalid Entry! Try again.\n"); break; } } }

public static boolean happy(int n) { MyList.clear(); MyList.add(n); boolean condition = false; while (condition == false) { int number = sumOfSquaresofDigits(n); if (number == 1) { condition = true; } if (MyList.contains(number)) { MyList.add(number); break;

} MyList.add(number); n = number; } return condition; } public static boolean checkNum(int num) { boolean condition = false; if (num > 0) { condition = true; } return condition; } public static int sumOfSquaresofDigits(int num) { if (num >= 10) { int digit = num % 10; return ((digit * digit) + sumOfSquaresofDigits(num / 10)); } return num * num; } }...


Similar Free PDFs