Help with Java Inserting an element into an array

325i

Senior Member
Joined
Jan 1, 2011
Messages
553
Reaction score
27
Location
Durbs
Hi guys :)

I need help with Inserting an Element into an Array, I'm using a book and when I code what's in the book called "Java Programming Made Easy - by Georgina Ramsamy" it comes up with many errors:confused: this is what I have :

Code:
import java.util.*;
public class Insert
{
 int [] arr = new int[6];
 Scanner kb = new Scanner (System.in);
 
 public static void InsertElement()
  {
   Scanner kb = new Scanner (System.in);
    System.out.println("Enter position to insert a value");
	 int pos = kb.nextInt();
	 System.out.println("Enter number to insert");
	 int num = kb.nextInt();
	 
	 for(int i=arr.length -1; i>=pos;i--)
	  {
	   arr[i]= array[i-1];
		}
		arr[pos-1] = num;
		 for (int i=0;i<6;i++)
		 {
		  System.out.println(arr[i] +" ");
		  }
		 }
		 
		 public static void main (String[]args)
		 {
		  for(int i=0;i<5;i++)
		  {
		   System.out.println("Enter value");
			arr[i]=kb.nextInt();
			}
		InsertElement();
	}
}

Please could someone explain to me what is wrong with this code and how to fix it and could you try to explain it in the simplest form :)

Thanks
325i
 
Last edited:
Simplistically, this is because of how the methods have been declared (static) vs the attributes (instance)

A static method or attribute, is one that belongs to the class. It does not require the class to be instanciated.

eg, Math.abs(), or Insert.InsertElement()

non-static methods and attributes are "unique" to each instance of a class

eg

List list = new ArrayList()
->>> list.add()



The variables int [] arr and Scanner kb are not static, and as such, they can only be accessed through an instance of Insert (ie Insert insert = new Insert() )


If you add "static" infront of those attributes, your code will work (you must also actually fix the line that says "arr= array[i-1];" to "arr= arr[i-1];"

This is another way you can do what you did, this time using non-static methods and attributes:
Code:
public class Insert {
	
	int[] arr = new int[6];
	Scanner kb = new Scanner(System.in);

	public  void insertElement() {
		Scanner kb = new Scanner(System.in);
		System.out.println("Enter position to insert a value");
		int pos = kb.nextInt();
		System.out.println("Enter number to insert");
		int num = kb.nextInt();

		for (int i = arr.length - 1; i >= pos; i--) {
			arr[i] = arr[i - 1];
		}
		arr[pos - 1] = num;
		for (int i = 0; i < 6; i++) {
			System.out.println(arr[i] + " ");
		}
	}

	public static void main(String[] args) {
		Insert insert = new Insert();
		
		for (int i = 0; i < 5; i++) {
			System.out.println("Enter value");
			insert.arr[i] = insert. kb.nextInt();
		}
		
		insert.insertElement();
	}
}



Another thing, unrelated to your question, but related to java in general, is the method name naming conventions.

Always use camel caps, eg MyClass, MyOtherClass
methods, parameters and attributes however, should use lowercase for the first method, eg myMethod(String myParameter), myOtherMethod();

so, where you have :
public static void InsertElement()
it should be
public static void insertElement()
 
more tips around standardization, although there will be some people that disagree on this, is that you should have your opening braces on the same line as the "condition".

eg, instead of
Code:
class MyClass
{
    public void myMethod()
    {
       if (dog == true)
       {
          return;
       }
    }
}

rather have
Code:
class MyClass {
    public void myMethod() {
       if (dog == true) {
          return;
       }
    }
}

In a large project, you can save 1000's of lines like this.
 
To the original poster, not to chase you away but you may find lots of valuable information on stackoverflow. Lots.

To _kabal_ - this is gonna go off topic - , I have to disagree, although I am sure that the "where to place the curly bracket" debate will rage on for quite a while. For me, personally, there is no point of saving thousands of lines of code if you sacrifice readability. If the braces line up, it is much easier to know which closing brace belongs to a opening brace, and (heaven forbid) if you have if statements continuing 1000's of lines through many levels of indentation you are going to get confused. One bug due to this screws up all gains made by saving lines of code. Besides, I am pretty sure that parsing of the code by an IDE will not be any faster, nor will the executable size differ. So at most, you save a few bytes in source code space. Big whoop.
 
Ooh, brace position debate

/gets popcorn
 
if curly brace position on same line is good enough/ the standard for Sun/Oracle, Apache, SpringSource and every other major industry standard package, its good enough for me:D

if you write crap, bloated functions and if statements, then sure :love:
 
For all the guys posting, I gather the OP is in high school. That is a text book used for teaching high school Java. Not the best one out there. This is an exercise on understanding how to insert an element into an array. However it misses simple things like checking the position is a valid position etc. however the code has mostly syntax errors. Things like arr= array[i-1] should read as arr=arr[i-1] to show that you are dropping the last element of the array and shifting everything up so that there is a space at the required position to insert the new value.
 
To _kabal_ - this is gonna go off topic - , I have to disagree, although I am sure that the "where to place the curly bracket" debate will rage on for quite a while.

I don't know why there would be a debate, it is a Java standard. Not having it on the same line is not Java standard.

If you cannot adapt to a language, then stick with a language you are comfortable with.
 
But the less whitespace you have, the faster your application runs.


But seriously, +1 on this:

For me, personally, there is no point of saving thousands of lines of code if you sacrifice readability. If the braces line up, it is much easier to know which closing brace belongs to a opening brace, and (heaven forbid) if you have if statements continuing 1000's of lines through many levels of indentation you are going to get confused. One bug due to this screws up all gains made by saving lines of code. Besides, I am pretty sure that parsing of the code by an IDE will not be any faster, nor will the executable size differ. So at most, you save a few bytes in source code space. Big whoop.
 
Hi guys :)

I need help with Inserting an Element into an Array, I'm using a book and when I code what's in the book called "Java Programming Made Easy - by Georgina Ramsamy" it comes up with many errors:confused: this is what I have :

Code:
import java.util.*;
public class Insert
{
 int [] arr = new int[6];
 Scanner kb = new Scanner (System.in);
 
 public static void InsertElement()
  {
   Scanner kb = new Scanner (System.in);
    System.out.println("Enter position to insert a value");
	 int pos = kb.nextInt();
	 System.out.println("Enter number to insert");
	 int num = kb.nextInt();
	 
	 for(int i=arr.length -1; i>=pos;i--)
	  {
	   arr[i]= array[i-1];
		}
		arr[pos-1] = num;
		 for (int i=0;i<6;i++)
		 {
		  System.out.println(arr[i] +" ");
		  }
		 }
		 
		 public static void main (String[]args)
		 {
		  for(int i=0;i<5;i++)
		  {
		   System.out.println("Enter value");
			arr[i]=kb.nextInt();
			}
		InsertElement();
	}
}

Please could someone explain to me what is wrong with this code and how to fix it and could you try to explain it in the simplest form :)

Thanks
325i

What happens when the user enters a number larger than 6 for pos?
 
Thank you to Kabal for fixing the code and explaining what was wrong with it, also thanks to BloodBurner9000 for the site will look in to it and to graviti, what you gathered is correct and our teacher just tells us the basics and we figure the rest out, well try to anyway. Thanks guys for all your help, really appreciate it:)
 
What happens when the user enters a number larger than 6 for pos?

I vortex rift opens and everyone dies! MWHAHAHAHAHAHAHA!!!!!!!!!


Regarding the curly braces thing - do whatever the hell you want it's your projects. But when you work in a group you follow the standards agreed upon by the team and shut up about it once that decision has been made.

If the team cannot agree on a stasndrad - switch to Python :twisted:
 
Top
Sign up to the MyBroadband newsletter
X