Results 1 to 2 of 2
  1. #1
    noobie_nate is offline Member
    Join Date
    Jun 2013
    Posts
    4
    Rep Power
    0

    Default getting out of a for loop

    Hello all, I'm trying to write a program that checks to see whether number input is a prime number. I got the code to work, but I want the program to keep asking the user to enter a new number until they enter a prime number.

    Java Code:
    import java.util.Scanner;
    import static java.lang.System.*;
    
    public class primeChallenge {
    	
    	public static void main(String args[]) {
    	
    		Scanner scanner = new Scanner(System.in);
    		out.print("Enter your prime number: ");
    		int num1 = scanner.nextInt();
    		int prime;
    		
    		for(prime = 2; prime <= num1; prime++) {
    			int num2 = num1 % prime;	
    			if(prime == num1) {
    				out.println("Input is a prime number");
    				break;
    			}
    		if(num2 == 0) {
    			out.println("Input is not a prime number");
    				break;
    			
    		}
    	
    		}
    
    	}
    }
    Last edited by JosAH; 06-10-2013 at 09:09 AM. Reason: added [code] ... [/code] tags

  2. #2
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,768
    Rep Power
    5

    Default Re: getting out of a for loop

    Check out the using the break statement with labels. Branching Statements (The Java™ Tutorials > Learning the Java Language > Language Basics)

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. While Loop inside a While Loop
    By steveday77 in forum New To Java
    Replies: 3
    Last Post: 05-10-2013, 01:43 AM
  2. Replies: 2
    Last Post: 11-07-2011, 02:25 AM
  3. Replies: 1
    Last Post: 10-01-2011, 02:12 AM
  4. JTextField loop 2x for-loop WEIRD!
    By Streetproject in forum AWT / Swing
    Replies: 2
    Last Post: 02-16-2011, 05:46 PM
  5. [Q] Loop issue (while loop)
    By iriscience in forum New To Java
    Replies: 9
    Last Post: 01-31-2011, 04:21 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •