Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

Can anyone tell me what's wrong with my program?

  • 05-08-2004 2:28pm
    #1
    Closed Accounts Posts: 1,959 ✭✭✭


    Hi all;
    I've repeat Computer Science exams in 2 weeks and I'm struggling. Can anyone tell me whats wrong with this program?
    All I'm trying to do is

    -Initialise an array of 10 randomly generated integers between 1-20.

    1. //This program will randomly generate integers in the range
    2. // 1-20 and store them in an array. The program will then
    3. //ask the user to enter an integer and see if that integer is in
    4. //the array, and display its position if it is in the array,
    5. //and an error message if it isn't.

    6.
    7. import java.util.*;
    8. class prac9q3
    9. {
    10. public static void main(String[]args)
    11. {
    12.
    13. //Initialise variables
    14. int userNum;
    15. int START = 1;
    16. int END = 20;
    17. int i;
    18.
    19. //Initialise array
    20. int [] arrayNums = new int [10];
    21. for(i = 0; i < arrayNums.length; i++)
    22.
    23. arrayNums= (int)(Math.random()*10);
    24. while (arrayNums >= START && arrayNums =< END) {
    25. System.out.println(arrayNums); }
    26.
    27. }
    28. }
    29. }
    30.

    When I compiled I got:

    19: illegal start of expression
    20: ';' expected
    24: 'class' or 'interface' expected
    24: 'class' or 'interface' expected


    I know it probably looks so simple but I really am on the verge of just giving up and cancelling my exams.


Comments

  • Closed Accounts Posts: 17,208 ✭✭✭✭aidan_walsh


    Your first for loop is missing an opening brace. And you're not taking in input anywhere... But you knew that much already... ;)


  • Registered Users, Registered Users 2 Posts: 678 ✭✭✭briano


    What errors are you getting?


  • Registered Users, Registered Users 2 Posts: 21,264 ✭✭✭✭Hobbes


    I think the problem is you didn't study enough.

    You have an extra "}". Remove one or fix it.
    You never type "=<" it is always the equates last eg. +=. -=. >=. <=

    Also I am not entirely sure what your trying to do with the While loop. Can you explain what you are doing?

    Edit: Also loops are more readable if you wrap the command in a brace, even if there is only one command.


  • Closed Accounts Posts: 1,959 ✭✭✭Nala


    I've edited the post now to include the errors I got.
    I changed the last for-loop to a while-loop.


  • Registered Users, Registered Users 2 Posts: 227 ✭✭stas


    import java.util.*;
    class prac9q3
    {
    	public static void main(String[]args)
    	{
    	
    		//Initialise variables
    		int userNum;
    		int START = 1;
    		int END = 20;
    		int i;
    
    		//Initialise array
    		int [] arrayNums = new int [10];
    		
    		for(i = 0; i < arrayNums.length; i++) [b]{[/b]
    			arrayNums[i]= (int)(Math.random()*10);
    			while (arrayNums[i] >= START && arrayNums[i] [b]<=[/b] END) 
    			{
    				System.out.println(arrayNums[i]); 
    			}
    		}
    	}
    }
    
    In fact you had two errors there:
    - No opening clause for the "for" loop (mentioned above)
    - There's no such operator as =<, it should be <= instead.


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 21,264 ✭✭✭✭Hobbes


    stas wrote:
    		for(i = 0; i < arrayNums.length; i++) [b][/b]
    			arrayNums[i]= (int)(Math.random()*10);
    
    In fact you had two errors there:
    - No opening clause for the "for" loop (mentioned above)
    - There's no such operator as =<, it should be <= instead.

    I disagree. He should have a brace loop, but it shouldn't close where you have it.


  • Closed Accounts Posts: 1,959 ✭✭✭Nala


    Hobbes wrote:
    I think the problem is you didn't study enough.

    You have an extra "}". Remove one or fix it.
    You never type "=<" it is always the equates last eg. +=. -=. >=. <=

    Also I am not entirely sure what your trying to do with the While loop. Can you explain what you are doing?

    Edit: Also loops are more readable if you wrap the command in a brace, even if there is only one command.

    The while loop is for making sure the randomly generated number is between 1 and 20.


  • Registered Users, Registered Users 2 Posts: 227 ✭✭stas


    Spot on Hobbes! Problem was the initial code wasn't formatted properly and I didn't pay much attention to actual logic, rather trying to fix the *compilation* problem. So here goes then:
    import java.util.*;
    class prac9q3
    {
    	public static void main(String[]args)
    	{
    	
    		//Initialise variables
    		int START = 1;
    		int END = 20;
    
    		//Initialise array
    		int [] arrayNums = new int [10];
    		
    		for(int i = 0; i < arrayNums.length; i++)
    			arrayNums[i]= (int)(Math.random()*10);
    		
    		while (arrayNums[i] >= START && arrayNums[i] <= END) 
    			System.out.println(arrayNums[i]); 
    	}
    }
    


  • Registered Users, Registered Users 2 Posts: 21,264 ✭✭✭✭Hobbes


    neev wrote:
    The while loop is for making sure the randomly generated number is between 1 and 20.

    read it again and tell me what the code is doing.


  • Registered Users, Registered Users 2 Posts: 227 ✭✭stas


    neev wrote:
    The while loop is for making sure the randomly generated number is between 1 and 20.
    Well, it doesn't look quite right. Imagine the first number in your array is greater than value of END or lesser than START. What happens is it will break right on the first one and nothing will be printed in the console.


  • Advertisement
  • Closed Accounts Posts: 1,959 ✭✭✭Nala


    Stas I tried your code but it c"couldnt resolve symbol" for i so I initialised i and re-comiled without errors but when I ran it it threw and ArrayIndexOutOfBoundsException at line 18(the while-loop).


  • Registered Users, Registered Users 2 Posts: 227 ✭✭stas


    Sorry :-) Try this.
    import java.util.*;
    class prac9q3
    {
    	public static void main(String[]args)
    	{
    	
    		//Initialise variables
    		int START = 1;
    		int END = 20;
    
    		//Initialise array
    		int [] arrayNums = new int [10];
    				
    		for(int i = 0; i < arrayNums.length; i++)
    			arrayNums[i]= (int)(Math.random()*10);
    		
    		
    		for(int i = 0; i < arrayNums.length; i++) 
    			if (arrayNums[i] >= START && arrayNums[i] <= END) 
    				System.out.println(arrayNums[i]); 
    	}
    }
    


  • Registered Users, Registered Users 2 Posts: 21,264 ✭✭✭✭Hobbes


    Stas you shouldn't just be giving him the code.

    I asked him to explain what the while loop was doing as it is clear he doesn't know. If you can't explain exactly what your code is doing then your not ready for the exam.

    Edit: removed the last part as it appears that Stas gave you the answer to your exam question(well almost). Lets hope you can explain what it does.

    Btw, any IDE would of told you exactly what your problems were with the code. Which leads me to believe you haven't studied at all.


  • Registered Users, Registered Users 2 Posts: 227 ✭✭stas


    Well, Hobbes you maybe right. But guy asked for help with his particular problem. He didn't ask to teach him Java. And I'm not a teacher nor I want to be.


  • Closed Accounts Posts: 1,959 ✭✭✭Nala


    Hobbes wrote:
    If you can't explain exactly what your code is doing then your not ready for the exam.

    Believe me I'm not in any way ready for the exam!
    Hobbes wrote:
    Also Neev, you code does not do what the test tells you what it should do. All stas has done is make your code compile.

    It compiled alright and printed out 8 numbers instead of 10, dont know why.

    P.S. I'm a girl! :)


  • Registered Users, Registered Users 2 Posts: 21,264 ✭✭✭✭Hobbes


    neev wrote:
    Believe me I'm not in any way ready for the exam!



    It compiled alright and printed out 8 numbers instead of 10, dont know why.

    Write out exactly what you think each part is doing.
    P.S. I'm a girl! :)

    Which means what exactly?


  • Closed Accounts Posts: 1,959 ✭✭✭Nala


    Hobbes wrote:
    Write out exactly what you think each part is doing

    OK...

    import java.util.*;
    Imports the Java utility package so I can use the Math class

    class prac9q3 Creates the class file
    {
    public static void main(String[]args) Main method
    {

    //Initialise variables
    int START = 1; Initialises 2 integers for the limits 1 and 20, i.e. the range the array's elements must fall into
    int END = 20;

    //Initialise array
    int [] arrayNums = new int [10];Creates a 1D array with 10 elements of type int

    for(int i = 0; i < arrayNums.length; i++) Goes through each element of the array
    arrayNums= (int)(Math.random()*10);Randomly generates the array's elements. The "*10" bit is because math.random only generates numbers between 0 and 1 which are not integers.


    for(int i = 0; i < arrayNums.length; i++) Same as the previous for-loop
    if (arrayNums >= START && arrayNums <= END) Checks the numbers are between 1 and 20 and prints them if so.
    Now I think I know why it only printed 8 numbers when I ran the program.

    System.out.println(arrayNums); //Prints the array.



    } Ends main
    } Ends class


  • Registered Users, Registered Users 2 Posts: 227 ✭✭stas


    Hobbes wrote:
    Which means what exactly?
    Means i shouldn't have been calling her a guy :-)

    I guess I know understand what this program should be doing, but I won't post the code here. Let's have it your way Hobbes.


  • Registered Users, Registered Users 2 Posts: 227 ✭✭stas


    Neev, you don't need java.util there as Math is located in java.lang package which is imported automatically by a compiler.


  • Closed Accounts Posts: 1,959 ✭✭✭Nala


    Oh ok. I'm just trying to figure out how to make sure the number is between 1-20 without using an if-statement so all 10 numbers are printed every time.


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 21,264 ✭✭✭✭Hobbes


    Imports the Java utility package so I can use the Math class

    Math is part of java.lang.* and because of this does not require to be imported.

    Randomly generates the array's elements. The "*10" bit is because math.random only generates numbers between 0 and 1 which are not integers.

    Correct, but your exam says it must be a number between 1 and 20. Also with random, your number will be 0-10 (0-20 when fixed) as Random can return 0.

    Checks the numbers are between 1 and 20 and prints them if so.
    Now I think I know why it only printed 8 numbers when I ran the program.


    Great, but also note that the random portion will never fall outside of the check you are making here, so it is kind of not needed. It will be later when you add the inputting section of the question.

    Another thing to note about the last IF statement, is you are using a short circut AND ( && ). What this does if the first statement is false it will automatcally ignore the second statement. So try to right the if statement where the first statement is more efficent.

    eg. Testing for null before other test which would fail on a null, or first statement is more likely to be false then the second statement.


  • Closed Accounts Posts: 660 ✭✭✭naitkris


    ok, just spent a little time on this (repeating 3 subjects in 2nd year CS myself btw - didn't study for the exams). anyways, the code below does no error checking and is very inefficient (put it together very quickly) and also does not compile as it is not finished (may finish it later when i get home if there's nothing on tv). i should note i would use a Comparator (or something similar) for the last part but seeing as i have a bus to catch i don't have that extra time to do that or fix the code up.
    import java.util.*;
    import java.io.*;
    
    /**
    * This program will randomly generate integers in the range 1-20 and store them
    * in an array. The program will then ask the user to enter an integer and see if
    * that integer is in the array, and display its position if it is in the array,
    * and an error message if it isn't.
    */
    
    public class prac9q3 {
    
       public static void main(String[] args) {
    
          //Initialise variables
          int userNum;
          int START = 1;
          int END = 20;
          int i;
    
          //Initialise array
          int [] arrayNums = new int [10];
    
          // Loop to add integers to the array until it is full
          for(i = 0; i < arrayNums.length; i++) {
             // Generate random number between 1 and 20
             arrayNums[i] = (int)(Math.random()*20);
             // Print out on a new line that number
             System.out.println(arrayNums[i]);
          }
    
          InputStreamReader in = new InputStreamReader(System.in);
          BufferedReader bufReader = new BufferedReader(in);
    
          String line = null;
          
          while (true) {
             System.out.println("Enter an integer to check if it is in the array:");
             line = bufReader.readLine();
             if (line == null) {
                break;
             }
             for(int j = 0; j < arrayNums.length; j++) {
                String temp = "" + arrayNums[j];
                if(temp == line) {
                   System.out.println("True");
                }
                // not implemented below, will loop through until all array length checked though
                else if() {
                   System.out.println("False");
                }
             }
          }
       }
    }
    


  • Registered Users, Registered Users 2 Posts: 21,264 ✭✭✭✭Hobbes


    if (line == null) {

    Will never happen.

    if(temp == line) {

    If I was to take a guess, that would work but it is VERY BAD and should never be done.


  • Closed Accounts Posts: 1,959 ✭✭✭Nala


    Thanks for all your help guys. I'm sure I will be in a muddle all over again tomorrow but hopefully it will all come right in the end.

    40%...thats all I want...just 40%!!!


  • Registered Users, Registered Users 2 Posts: 227 ✭✭stas


    Hobbes wrote:
    if(temp == line) {

    If I was to take a guess, that would work but it is VERY BAD and should never be done.
    You sure it would? What are the odds those objects are the same? My bet would go for temp.equals(line) instead :-)


  • Registered Users, Registered Users 2 Posts: 21,264 ✭✭✭✭Hobbes


    stas wrote:
    You sure it would? What are the odds those objects are the same? My bet would go for temp.equals(line) instead :-)

    Yea :) I was taking a guess.

    String a= "Hello";
    String b= "Hello";
    String c = new String "Hello";

    a == b // true
    a == c // false
    a.equals(c) // true

    So as the string was the same contents and it wasn't generating a new string it would probably be the same, but as you said equals() is the way to go.


  • Registered Users, Registered Users 2 Posts: 6,336 ✭✭✭OfflerCrocGod


    Try this...may work
    class some{
     public static void main(String[] args){
       int[] x = new int[10];
       int start=0;
      
       while(x[9]==0){
        int temp = (int)(Math.random()*21);
        
        if(1 <= temp && temp <= 20){
         x[start]=temp;
         start++;   
        } 
       }
       
       for(int i=0; i<x.length; i++){
        System.out.println(x[i]);
       }   
     }
    }
    


  • Moderators, Society & Culture Moderators Posts: 9,689 Mod ✭✭✭✭stevenmu


    (int)(Math.random()*21);

    Will that not give 0 to 21 ?
    There is a really easy, obvious way of making sure it creates 1 to 20 in that line, it's one of those things that's so obvious you feel like putting your head through a monitor when you find out ......


  • Closed Accounts Posts: 19,777 ✭✭✭✭The Corinthian


    Hobbes wrote:
    Which means what exactly?
    It means she can't program. Or drive. Or go to a toliet without a support group. Everyone knows that.


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 21,264 ✭✭✭✭Hobbes


    person wanted help for repeat exam not answer to exam or homework, so code should be allowed

    There is no point giving someone working code, because it stops them from learning and building a 'cut and paste' mentality to exams.

    If they can explain what the code is doing even if it is wrong is better then just handing over code. That way you can explain what parts are wrong.


  • Closed Accounts Posts: 1,959 ✭✭✭Nala


    It means she can't program. Or drive. Or go to a toliet without a support group. Everyone knows that.

    I'm actually the ONLY girl I know who goes to the toilet by herself!


  • Closed Accounts Posts: 1,959 ✭✭✭Nala


    Hobbes wrote:
    There is no point giving someone working code, because it stops them from learning and building a 'cut and paste' mentality to exams.

    If they can explain what the code is doing even if it is wrong is better then just handing over code. That way you can explain what parts are wrong.

    That's a good point but sometimes I need a bit of code, like methods.


  • Closed Accounts Posts: 1,959 ✭✭✭Nala


    OK...

    This is the finished program. Ot will compile but throws an ArrayIndexOutOfBoundsException when I run it. Has anyone any ideas on how to fix this?

    1. //Write a Java program that randomly generates 10 integers
    2. //in the range 1 – 20 and stores them in an array.
    3. //You should then ask the user to enter a number and search
    4. //the array to determine if the number entered is in the array.
    5. //If the number is found in the array display the location
    6. //the number was found at, otherwise display a message
    7. //stating the number entered is not in the array.

    8.
    9. class sec6q1
    10. {
    11.
    12. //Initialise read only variables
    13. final static int SIZE=10;
    14. final static int END=20;
    15.
    16. public static void main(String[]args)
    17. {
    18.
    19. //Initialise variables
    20. boolean valid = false;
    21. boolean found = false;
    22. int number = 0;
    23. int index = 0;
    24. int i = 0;
    25.
    26. //Initialise the array
    27. int numArray[] = new int[SIZE];
    28. for (i=0; i<numArray.length; i++);
    29.
    30. //Randomly generate 10 numbers in the range for the array
    31. for (i = 0; i<numArray.length; i++); {
    32. numArray = (1 + (int) (Math.random() * END) );
    33. }
    34.
    35. //Get user input, ensuring the number is between 1-20,
    36. // i.e. it is valid

    37.
    38. //Use a while-loop to ensure the number is valid.
    39. //If !valid = false, the number is not in the range.

    40.
    41.
    42. while (!valid) {
    43.
    44. System.out.println("Please enter a number between 1-20");
    45. number=SavitchIn.readLineInt();
    46.
    47. //Determine it is in the range
    48. if(number>0 && number<=END)
    49. valid = true;
    50.
    51. }
    52. //ends while
    53.
    54. //Search the array for the user's input while we
    55. //are still within bounds and we have not found
    56. //what we are looking for.

    57. // !found = true because found = false.
    58.
    59. for(i = 0; i < numArray.length && !found; i++) {
    60.
    61. if(numArray == number) {
    62. index = i;
    63. found = true;
    64. }
    65. } //ends for
    66.
    67. //Display the results

    68. if(found)
    69. System.out.println(number + " found at position "+index+ " in the array");
    70. else
    71. System.out.println(number + " not found in the array");
    72. }
    73. }


  • Registered Users, Registered Users 2 Posts: 21,264 ✭✭✭✭Hobbes


    neev wrote:
    OK...

    This is the finished program. Ot will compile but throws an ArrayIndexOutOfBoundsException when I run it. Has anyone any ideas on how to fix this?

    No one can run you code if you put line numbers on it like that. Use the [ C O D E ] tags.

    Your Exception should of told you what line number is causing the problem.


  • Registered Users, Registered Users 2 Posts: 2,426 ✭✭✭ressem


    Line 31, you left a semicolon in the wrong place after cutting and pasting the previous line, so at line 32, i = 10.
    Therefore out of bounds.

    Have you learned about using an IDE, like Eclipse (free download), for your course,
    to let you step through your application line by line, and see, as in this exercise, that line 32 wasn't hit till the loop was finished, and the value of i used when the exception occurred on line 32 will be available in the variables window.

    That was day 1 of the course when I was learning C back in the day and is essential for finding mistakes easily.


  • Advertisement
  • Closed Accounts Posts: 1,959 ✭✭✭Nala


    UPDATE

    Got the results this morning............





    I PASSED!!!!!!!!!

    Can't believe it tbh, exam was tough and I only got 60% of it done.
    Thanks to everybody for helping me out!

    Neev


  • Registered Users, Registered Users 2 Posts: 21,264 ✭✭✭✭Hobbes


    Congrats. :) Free positive rep for you (when the board lets me)


Advertisement