Read a positive integer n. From 1 to n monitor the occurrence of 1. Your program should contain the method Monitor1. Include an option to repeat the process.
Sample Output
Enter the value of n: 15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Total Occurrence of 1: 8
Try again Y/N?
1
Expert's answer
2012-03-27T09:35:23-0400
import java.util.Scanner;
public class Main { private static Scanner input = new Scanner(System.in); public static void main(String[] args) { int number=0; int nuberof1=0; char ch=' '; String arrayofNumber=""; System.out.print("Enter the value of n: "); number=input.nextInt(); for(int i=1;i<=number;i++){ arrayofNumber+=i; } for(int i=0;i<arrayofNumber.length();i++){ if(arrayofNumber.charAt(i)=='1'){ nuberof1+=1; } } System.out.print("Total Occurrence of 1: "+nuberof1+"\n"); System.out.print("Try again Y/N?"); ch=input.next().charAt(0); if(ch=='Y' || ch=='y' ){ main(args); }else{ System.exit(0); } } }
Comments
Leave a comment