Seriously screwed for Java assessment

Associate
Joined
17 Oct 2002
Posts
2,165
Location
London
no, else I would have typed that. It all depends on the needs of shicky, though yours will be closer to them.

I am also avoiding doing shicky's homework for him/her.
I certainly appreciate that.

The problem is your example is very confusing. It looks like a concrete example answering the question "How do I return an array?". Use the type "Array". Sounds quite reasonable when not familiar with the language.

Anyway, another book you may find useful is Bruce Eckel's Thinking in Java.

The older editions are a little dated now but are available FREE in pdf format.
http://www.planetpdf.com/developer/article.asp?ContentID=6632
 
Associate
OP
Joined
13 Jan 2007
Posts
2,424
Location
Belfast,Northern Ireland
return the variable, and make sure your method signature contains the class name of the object you are returning.
Code:
public Array foo () {
    Array foobar = new Array();
    return foobar;
}

Dont quite understand there. I have this:
Code:
public static int enterMarks();
	{
		
		int[] classMarks = new int[30];

at the start. then simply return classMarks;

at the end of the method. I dont quite understand as it works in the textbook im looking at, yet wont for me, and the functioned fine when it was part of the main method.

As for doing my homework, fair enough magical trevor did help me to a degree i didnt expect, but what he did helped me get a grasp of what i was trying to do and i've since completed another 5 sections. Plus its an assessed practical in a few hours, not homework.

Even still i thought asking what is probably a relatively simple one line question to most on here, wasnt exactly asking a huge amount
 
Associate
Joined
17 Oct 2002
Posts
2,165
Location
London
Dont quite understand there. I have this:
Code:
public static [b]int[/b] enterMarks();
	{
		
		[b]int[][/b] classMarks = new int[30];

		...

		return classMarks;

Have a look at the bold bits then at the examples Dj_Jestar and I posted.

The variable type and method signature don't match.

Code:
public static [b]int[/b] enterMarks();
Method returns an integer.

Code:
public static [b]int[][/b] enterMarks();
Method returns an array of integers.
 
Soldato
Joined
16 Dec 2005
Posts
14,443
Location
Manchester
When a method is supposed to return something, you need to tell the compiler what it is you intend to return.

So if you had a method "getInt()" you would have this signature:

public int getInt()

The same if you wanted to return a String:

public String getString()

When it comes to an array, you need to tell the compiler what type of array [int in your case] and the fact that it is an array "[]"

public int[] getArray()

The variable you return must match the type you have declared in the signature.

public int[] getArray()
{
int x = 20;
return x;
}

This would fail, as "x" does not match the return type.
 
Associate
OP
Joined
13 Jan 2007
Posts
2,424
Location
Belfast,Northern Ireland
Ah right, i'd never been shown that before. Though it still isnt working for me. Its saying im trying to return outside the method, which i've got on a few variations and now im getting that the method ody is missing. This is what i've got for the array and the part of the main which matters in terms of the array.

Code:
public class marks2
{	// creates the array which the user will enter 30 values between 0-20 into
	public static int[] enterMarks();
	{
		
		int[] classMarks = new int[30];
		int a = 0;
		
		for(int i = 0; i < classMarks.length;)
		{
		a = getScannerInput.anInt("Please enter a mark: ");
		if (a >= 0 && a <= 20)
    	{
     	classMarks[i] = a;
     	i++;
    	}
    	else
    	{
      System.out.println("The number you entered was not between 1 and 20");
   		}
  		}		
	
		for (int i = 0; i < classMarks.length; i++)
		{
 		if (i < classMarks.length - 1)
  		{
   		System.out.print(classMarks[i] + ", ");
 		}
  		else
  		{
    	System.out.print(classMarks[i]);
  		}
  		return classMarks;
		}

Code:
public static void main (String args[])
	{
		enterMarks();
	}

Is that not right or am i getting completely the wrong idea? I thought by changing the public static int[] enterMark would mean im able to return an array to work on through main?
 
Soldato
Joined
16 Dec 2005
Posts
14,443
Location
Manchester
If you add a type identifyer to a method, that method expects to return something. You aren't returning anything in your enterMarks() method.

So you need to remove the "int[]" and replace it with "void".

EDIT: As an aside, you might want to sort out your code formatting... at the moment nothing is lining up properly which make it hard to follow.

EDIT 2: You also have used the For loop incorrectly.

It should be:

Code:
for(int i = 0; i < classMarks.length; i++)
{
}
For some reason you have put the "i++" bit at the bottom of the loop block.

EDIT 3: OK I re-read your code and you were returning something. However you don't need to so I have removed it. I have just formatted your code a bit:

Code:
public class marks2
{    // creates the array which the user will enter 30 values between 0-20 into
    public static void enterMarks();
    {
        
        int[] classMarks = new int[30];
        int a = 0;
        
        for(int i = 0; i < classMarks.length; i++;)
        {
            a = getScannerInput.anInt("Please enter a mark: ");
        
            if (a >= 0 && a <= 20)
            {
                  classMarks[i] = a;
            }
            else
            {
                  System.out.println("The number you entered was not between 1 and 20");
            }
        }        
    
        for (int i = 0; i < classMarks.length; i++)
        {
             if (i < classMarks.length - 1)
             {
                 System.out.print(classMarks[i] + ", ");
             }
             else
             {
                 System.out.print(classMarks[i]);
             }
         }
    }
}
Try that and see if it works.
 
Last edited:
Associate
OP
Joined
13 Jan 2007
Posts
2,424
Location
Belfast,Northern Ireland
But aren't I returning the array from within the method so i can use it in main? Therefore it should indeed be int[] ? I tried using void anyway and got nowhere.

As for the i++ i thought it stopped the value being entered into the array if it was outside the values i need and stopped it skippin ahead with no value or something dodgy.

I suggest you give up on me after a valiant effort! Thanks all for the patience but i dont see me getting this in a hurry. Again thank you for all the help, i'll hopefully get my head around it later when i try to go over where i screwed up :)
 
Soldato
Joined
16 Dec 2005
Posts
14,443
Location
Manchester
I made a mistake when I said you weren't returning anything. I apologise - said as much in one of my several edits :p

The i++ isn't separate from the values inside the loop. The for loop has been designed like that in order to make it easy to set up and follow. It is much better to write

Code:
for (int i = 0; i < something; i++)
{
}

than say:

Code:
int x = 0;
while (x < something)
{
//do something
x++;
}

And I haven't given up on you just yet :p
 
Associate
Joined
17 Oct 2002
Posts
2,165
Location
London
Shicky, you are right but a while loop would be a better fit.

SiriusB, we only want to increment "i" when valid input is entered.

Code:
        int i= 0;
        while(i < classMarks.length)
        {
            a = getScannerInput.anInt("Please enter a mark: ");
        
            if (a >= 0 && a <= 20)
            {
                  //valid input - record and move on to the next mark
                  classMarks[i] = a;
                  i++;
            }
            else
            {
                  //invalid input - ask again
                  System.out.println("The number you entered was not between 1 and 20");
            }
        }
 
Caporegime
Joined
18 Oct 2002
Posts
29,491
Location
Back in East London
This is why I suggested using ArrayList.

Code:
public class Marks
  private ArrayList marksArray;

  public static void main (String[] args) {
    Marks marks = new Marks();
    marks.collectMarks();
    marks.printMarks();
  }

  public void collectMarks () {
    int i = 0;
    String input = '';
    while (i < 30) {
      input = System.in.readLine();
      if (input > 0 && input < 21) {
        i++;
        this.marksArray.add(input);
      } else {
        System.out.printLn('Please enter a number between 1 and 20.');
      }
    }
  }

  public void printMarks () {
    // depending on desired formatting, either this for simplicity:
    System.out.print(this.marksArray.toString());
    // or
    Iterator it = marksArray.iterator();
    Boolean sep = false;
    while (it.hasNext()) {
      if (sep) {
        System.out.print(',');
      } else {
        sep = true;
      }
      System.out.print(' ' + it.next().toString());
    }
  }
}
Totally untested, and I've obviously gone back on what I said earlier.
 
Associate
Joined
17 Oct 2002
Posts
2,165
Location
London
Associate
Joined
3 Dec 2003
Posts
943
Dj Jester,

you need walk before you run, when i went to uni if an assignment said use an Array i used an array, if the assignment said use a Vector, i used a vector.

And if your going to introduce ArrayList why not declare with type safety?, and why not keep handle to the interface (List) rather than a specific implementation(ArrayList)?
 
Caporegime
Joined
18 Oct 2002
Posts
29,491
Location
Back in East London
Because I was not implementing any form of polymorphism in that scenario. A habit I picked up from optimising. Having to call the interface of a parent class/Interface increases memory usage when it is not necessary, over calling the specific interface of the object you will be instantiating. As for type safety.. coding in Java is like coding in a straight jacket as it is..

Walking before running is fine, but even students are expected to learn how to put one foot infront of the other by themselves. This is somehing especially necessary in development.. you don't get a textbook telling you how to create code for your customers needs.. you, shock horror I know, need to come up with that design yourself.
 
Last edited:
Permabanned
Joined
13 Jan 2005
Posts
10,708
Having to call the interface of a parent class/Interface increases memory usage when it is not necessary, over calling the specific interface of the object you will be instantiating.

Bull.

Code:
public interface Test {
   void test();
}

Code:
public class TestImpl implements Test {
   public void test()
{
   System.out.println("test") ;
}
}

Code:
public class Main {
    public static void main(String[] args){
        Test referenceToTest = new TestImpl();
        TestImpl referenceToTestImpl = new TestImpl();

        //Call 1
        referenceToTest.test();

        //Call 2
        referenceToTestImpl.test();
    }
}

Are you really saying that Call 1 has a greater memory overhead than call 2?

(Hint: compile the above example and profile it.....)
 
Associate
Joined
14 Apr 2003
Posts
1,101
Walking before running is fine, but even students are expected to learn how to put one foot infront of the other by themselves. This is somehing especially necessary in development.. you don't get a textbook telling you how to create code for your customers needs.. you, shock horror I know, need to come up with that design yourself.

True... but for the purposes of this exercise he should use an array... Once he has done that he could create the same program using an ArrayList (if he wanted to). At least that way he will have something to compare it to.
 
Caporegime
Joined
18 Oct 2002
Posts
29,491
Location
Back in East London
Bull.

Code:
public interface Test {
   void test();
}

Code:
public class TestImpl implements Test {
   public void test()
{
   System.out.println("test") ;
}
}

Code:
public class Main {
    public static void main(String[] args){
        Test referenceToTest = new TestImpl();
        TestImpl referenceToTestImpl = new TestImpl();

        //Call 1
        referenceToTest.test();

        //Call 2
        referenceToTestImpl.test();
    }
}

Are you really saying that Call 1 has a greater memory overhead than call 2?

(Hint: compile the above example and profile it.....)
Hint: You're calling upon two objects when not referencing the same interface.
 
Back
Top Bottom