Life,the Universe,and Everything

Can anyone tell me what is wrong with this code ?

package easy;
import java.util.Scanner;

public class Life_universeandEverything 
{
	public static void main(String args[])
	{	System.out.println("Enter a number");
		int a[]=new int[1000];
		Scanner s=new Scanner(System.in);
		for(int i=0;i<10000;i++)
		{
			a[i]=Integer.parseInt(s.nextLine());
		}
		for(int i=0;i<10000;i++)
		{
			if(a[i]!=42)
			{
				System.out.println(a);
				break;
			}
	    }
	}
}

If you are solving the problem TEST , then in that problem it has not been mentioned that how many i/p are there in the test file. You just need to sptop processing when you encounter integer 42. Hence your code should go like:

    //package easy; // it should be hidden as compiler can't find the package called easy.
    import java.util.Scanner;

    public class Life_universeandEverything //it shouldn't be public as mentioned by @betlista
    {
        public static void main(String args[])
        {   
            //System.out.println("Enter a number");  // hide it as it doesn't follow o/p format.
            //int a[]=new int[1000];//you don't know number of tests, better don't take an array.
            int n;
            Scanner s=new Scanner(System.in);
            while((n=s.nextInt())!=42)  
                  System.out.println(n); // o/p until you don't encounter integer 42.
        }
    }

Corrected code : hBSn9W - Online IDE & Debugging Tool - Ideone.com

1 Like

You are getting compilation error from judge, because your class cannot be public, change it to default visibility (aka package visible)

from

public class Life_universeandEverything 

to

class Life_universeandEverything 

:wink:

well, your for loop goes well beyond the array capacity, so it would throw a ArrayIndexOutOfBoundsException.

 make the loop stop at 1000 like this:
for(int i=0;i<1000;i++)

Also, you better make sure the input is really a number, otherwise a runtime exception will be thrown.

Hello…
In C language,I am unable to understand where to store the list of numbers being entered by the user i.e. either array,or some other thing because array is not working over there. Kindly tell me the answer. Thanx in advance.

thanx a lot

THANX BUT IT IS NOW GIVING NZEC ERROR

Hide the package line.

HOW TO AVOID NZEC ERROR?

STOP SHOUTING and start reading @lucas_prestes helped you, also @bit_cracker007 did…

1 Like

Nice one @betlista :wink:

1 Like