1 Replies - 525 Views - Last Post: 14 November 2011 - 11:07 AM Rate Topic: -----

#1 iggyman11  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 05-October 11

expected '.class' error what am I doing wrong?

Posted 14 November 2011 - 10:54 AM

I'm pretty sure the code will work but compiling seems to be a problem. Every time it comes up with a '.class' expected error at line 6. Any ideas? And the codes goal is to generate a random integer between two user-inputted integers.

public class generateRand 
{
    public static int randomInt(int x,int y)
    {
        if (x>y)
            int num = y + (int)(Math.random()*((x-y)+1));
        else
            int num = x + (int)(Math.random()*((y-x)+1));
        return num;
    }
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter an integer: ");
        int x = input.nextInt();
        System.out.println("Enter another integer: ");
        int y = input.nextInt();
        rand = randomInt(x,y);
        System.out.println("A random integer between x and y: " + rand);
    }
}


Is This A Good Question/Topic? 0
  • +

Replies To: expected '.class' error what am I doing wrong?

#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 5121
  • View blog
  • Posts: 13,788
  • Joined: 18-April 07

Re: expected '.class' error what am I doing wrong?

Posted 14 November 2011 - 11:07 AM

It isn't liking the fact that you declared a variable inside your if statements. Not to mention you wouldn't want this because you want to return num and any variables you would define inside the if would go out of scope as soon as the if statement ends.

Secondly, you have not defined rand in main, so that is going to be a problem. Your code fixed...

public class generateRand 
{
    public static int randomInt(int x,int y)
    {
	    int num = 0;
		
        if (x>y)
            num = y + (int)(Math.random()*((x-y)+1));
        else
            num = x + (int)(Math.random()*((y-x)+1));
        return num;
    }
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter an integer: ");
        int x = input.nextInt();
        System.out.println("Enter another integer: ");
        int y = input.nextInt();
        int rand = randomInt(x,y);
        System.out.println("A random integer between x and y: " + rand);
    }
}




Edit: If you really wanted to do it this way, for some reason, you can also add opening and closing curly braces in your if. This will create the local scope and Java won't see this one line if as some attempt to initialize a variable outside the if.


Enjoy! :)

This post has been edited by Martyr2: 14 November 2011 - 11:14 AM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1