Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Jan 2012
    Posts
    37
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Reading in integers into Array

    I'm trying to read integers into my array but I'm getting an error. What am I doing wrong?

    import java.util.Scanner;
    public class array {


    public static void main(String[] args) {

    int[] grades;
    int size = 5;
    grades = new int[size];

    System.out.println("Please enter 5 unique numbers");
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Please enter the first unique numbers");
    int[0] grades = keyboard.nextInt();
    System.out.println("Please enter the second numbers");
    int[1] grades
    int second = keyboard.nextInt();
    System.out.println("Please enter the third numbers");
    int third = keyboard.nextInt();
    System.out.println("Please enter the fourth numbers");
    int fourth = keyboard.nextInt();
    System.out.println("Please enter the fifth numbers");
    int fifth = keyboard.nextInt();


    }

    }

  • #2
    Senior Coder alykins's Avatar
    Join Date
    Apr 2011
    Posts
    1,723
    Thanks
    41
    Thanked 191 Times in 190 Posts
    Code:
    public class demo {
    	public static void main(String[] args) throws IOException {
    
    		int[] grade = new int[5];
    		Scanner keyboard = new Scanner(System.in);
    		Boolean validate = false;
    		System.out.println("Please Enter 5 Unique numbers...");
    		for(int i=0; i<grade.length;i++)
    		{
    			validate = false;
    			System.out.printf("Please enter the %d number\n", i+1);
    			while(!validate)
    			{
    			   try
    			   {
    				   grade[i] = keyboard.nextInt();
    				   for(int j=0; j< i; j++)
    				   {
    					   if(grade[i] == grade[j])
    						   throw new Exception();
    				   }
    				   validate = true;
    			   }
    			   catch(Exception ex)
    			   {
    				   System.out.println("That number already exists...\nPlease choose another number.");
    			   }
    			}
    		}
    		System.out.println("All done, the numbers are...");
    		for(int g : grade)
    		{
    			System.out.printf("%d\n", g);
    		}		
    	}
    }

    I code C hash-tag .Net
    Reference: W3C W3CWiki .Net Lib
    Validate: html CSS
    Debug: Chrome FireFox IE


  •  

    Posting Permissions

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