Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Looking for a better way than to break after if statement

$
0
0
I'm looking for a better way to execute my for loop without using a "break;" in my code
if (msg.equalsIgnoreCase("done")) {  break;  }


Here is my full code which is a program that counts how many times a digit is entered between 0 and 10 inclusive. I believe my logic is right, but I need a way to execute my for loops without breaking and also I need to know how to give the user the option of playing again.

         import java.util.*;

               public class ArbitraryNumbers {

               public static void main(String[] args)
	{
		// local variables
		Scanner scan = new Scanner (System.in); // used to read integers being entered
		int[] numbersArray; // iniatilizes array for numbers entered
		int enoughLines = 50; // used to seperate input from output screen
		int[] histogram = new int[11]; // new array for groups of numbers 0 - 11
		String[] groups = {"0 | ", "1 | ", "2 | ", "3 | ", "4 | ", "5 | ", "6 | ", "7 | ", "8 | ", "9 | ", "10 | " };
		String msg; // Used to scan lines entered by user

		System.out.println("Please enter lines numbers in range 0 - 10 (or 'done' when finished):");

		// DO Scan the next line of input
		do {
			msg = scan.nextLine(); //

			// IF the line of text is not "done"
			if (!msg.equals("done")) {

				// Pass the integer into the conditions below
				int number = Integer.parseInt(msg);
					// IF the number is between 0 and 10
					if (number > -1 && number < 11)
				{
					//
					if(number <= 0) {
			histogram[0] += 1;
		}
		if(number <= 1 && number >0) {
			histogram[1] += 1;
		}
		if(number <= 2 && number >1) {
			histogram[2] += 1;
		}
		if(number <= 3 && number >2) {
			histogram[3] += 1;
		}
		if(number <= 4 && number >3) {
			histogram[4] += 1;
		}
		if(number <= 5 && number >4) {
			histogram[5] += 1;
		}
		if(number <= 6 && number >5) {
			histogram[6] += 1;
		}
		if(number <= 7 && number >6) {
			histogram[7] += 1;
		}
		if(number <= 8 && number >7) {
			histogram[8] += 1;
		}
		if(number <= 9 && number >8) {
			histogram[9] += 1;
		}
		if(number <= 10 && number >9) {
					histogram[10] += 1;
		}

				}
		else System.out.println ( " Please enter a valid number " );
			}

			if (msg.equalsIgnoreCase("done")) {
							break;
						}

					}
						while (true);

					for (int i = 0; i<histogram.length; i++)
					{
						System.out.print(groups[i]);

						int count = histogram[i];

						for(int k = 0; k < count; k++)
						{
							System.out.print("*");
						}
						System.out.print("\n");
					}

				}


}



My code runs fine like this but I would appreciate any help on alternate ways not involving a "break;"

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>