I'm new to this site so let me know if this sort of question is welcome here.
I'm currently coding a class in java to store a set of integers in an array stored in an object and i'm having trouble reassigning the array variable store in the objects created. its not compiling as is(I'm a new programmer so i'm pretty sure i'm missing something simple here).
public class Set
{
// constructor
Set()
{
int array[] = {};
}
//adds a value to the set
public static void addValue(int [] array, int element)
{
int i;
int n = array.length;
int newArray[] = new int[n + 1];
//copy original array into new array
for (i = 0; i < n; i++)
newArray[i] = array[i];
//add element to the new array
newArray[n] = element;
//the issue is this line here
this.array = newArray;
}
//print the set
public static void printSet(int [] array)
{
int i;
int n = array.length;
System.out.print("{");
for (i = 0; i < n; i++)
{
System.out.print(array[i]);
}
System.out.println("}");
}
}
edit - error message returned is:
Set.java:23: error: non-static variable this cannot be referenced from a static context
this.array = newArray;
^
Set.java:23: error: cannot find symbol
this.array = newArray;
^
symbol: variable array
2 errors
First of all, you forgot to put the array inside the class, you can handle it privately like this before the constructor in this way:
private int [] array;
Constructor is used to initialize objects. If you create an empty constructor, you won't be able to pass it any parameters to initialize the array. You can create the constructor this way:
Set (int [] array){
this.array = array;
}
At line you indicated the compiler tells you that you cannot handle the method statically because you are working on an instance method. The "this" keyword is used as a reference to an instance. Since the static methods doesn't have (belong to) any instance you cannot use the "this" reference within a static method. So, you have to remove the static handling from the method. Also, since you want to return the array with the entered value, your method cannot be of type void. So, your method will be:
//adds a value to the set
public int [] addValue(int [] array, int element){
int newArray[] = new int[array.length + 1];
for (int i = 0; i < array.length; i++)
newArray[i] = array[i];
newArray[array.length] = element;
return newArray;
}
Since the length of the array was already available (array.length), it was not necessary to create the variable n, so I took the liberty of making some improvements to your code, to make it less redundant. Similarly, the method you created to print the array would be:
//print the set
public void printSet(int [] array){
System.out.print("{ ");
for (int i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
}
System.out.println("} ");
}
However, once you've made these small changes your code should work fine. You can try to create a testing class like this, to check that everything works right:
public class TestingSet {
public static void main (String [] args){
//creating array
int [] array = {1, 2, 3};
//creating an instance of Set class
Set s = new Set(array);
//printing array
s.printSet(array);
//printing array with new value
s.printSet(s.addValue(array,4));
}
}
It looks like you are trying to access array however it cannot be seen by the addValue method.
You need to declare the array outside of the Set constructor:
public class Set
{
//New location to declear the array
int array[];
// constructor
Set()
{
//We can still initialize the array here
array[] = {};
}
Secondly, the reason for the error is that you cannot use this inside a static method. Static methods are not tied to an object (The Set class) so you need removed static from the method:
//static removed from this line
public void addValue(int [] array, int element)
{
Then to use the method you would create the Set object and use addValue something like this:
Set exampleSet = new Set();
exampleSet.addValue(yourArray, index);
The other option is to make the array a static value (it will no longer be specific to the object but shared with everything), but this is proberbly not the behaviour you want:
public class Set
{
//New location to declear the array
static int array[];
//And to access the object you could use
Set.array = newArray;
Related
I'm trying to return a 2-dimensional array from a function inside of a class. I don't want to create a new array inside the function because I want to return the same one I've passed into the function.
I've tried creating a new array with the same name, but it says it's already defined within the scope. I've also tried just doing (return plane;) which doesnt work because of incompatible data types. I've also tried (return plane[][];) but that doesnt work either.
public class Airplane {
private String maxSeats; //used for constructor
private char[][] plane = new char[13][6]; //array to be passed in
public char create(char[][] plane) {
plane[13][6]; //this is where I'm unsure what to do
//initialize them as '*' to start
for (int i = 0; i <= 12; i++) {
for ( int k = 0; k <= 5; k++) {
plane[i][k] = '*';
}
return plane;
}
}
I'm trying to return the array to be used in another function where I will modify it.
You have to change the return type to char[][] since you want to return a 2-dimensional array of characters and not just a single character
public class Airplane {
private String maxSeats;
private char[][] plane = new char[13][6];
public char[][] create(char[][] plane) {
// plane[13][6]; you should remove this line, it's the wrong syntax
//and it's unneeded since you've already declared this array
// this is a more compact version of your nested loop
for (int i = 0; i < 13; i++) {
Arrays.fill(plane[i], '*'); //fills the whole array with the same value
}
return plane;
}
}
I have to pass the values that are in my Guitar constructor and then pass them to the generateSong method. There is one catch. The generate song method can not take parameters in because since the values are in the same class, they should be able to be able to take in the values from the constructor.
When I try to implement the values in that method, the values are not able to be accessed. How can I fix this?
public Guitar(int chord, int numOfStrings) {
//pass these values to the generateSong method
System.out.println("Guitar () generated a guitar with: " + numOfStrings + "." + "Song length is " +chord);
// declare the array for which the song is stored
// store the values of the last row i (highest index of the array)
double[] max = null;
Guitar.generateSong();
// start the generate song method
public static void generateSong () {
double [] [] song = new double [numOfStrings] [chord];
double[] max;
int findmax =0;
int sum =0;
for (int i =0; i<song.length; i++) {
for (int j =0; j<song.length; j++ ) {
sum = (int) (sum +song[i][j]);
}
for (int e=0; e<song.length; e++) {
if (song[e]!=song[findmax] ) {
max[e] =e;
}
for(int k=0; k<song.length; k++) {
for (int l=0; k<song[k].length; k++)
// assign note values to the array
song [k] [l] = 27.5 + (Math.random()* 4186);
// print out the proper value
System.out.printf("8.2%f", song);
for( int m=0; m<max.length; m++)
max[m]= 1 +( Math.random() *3);
System.out.printf("8.2%f", max);
}
}
}
}
The values int chord and int numOfStrings come from command line parameters in the main method and are passed to this method through the following object:
Guitar guitar = new Guitar (numOfStrings, chord);
So, there are two syntax errors and one misunderstanding of the requirement. Let's start with the misunderstanding.
The generate song method can not take parameters in because since the values are in the same class, they should be able to be able to take in the values from the constructor.
This is only accomplishable via fields. You need to set your constructor up so that fields for those values are created, which can then be used everywhere else in this class.
In this scenario...
public class Guitar {
private int chord;
private int numberOfStrings;
public Guitar(final int chord, final int numberOfStrings) {
this.chord = chord;
this.numberOfStrings = numberOfStrings;
}
}
Second, you can't define methods inside of other methods. Move the definition of your generateSong method out of the constructor.
Third, don't make the generateSong method static! You create an instance of these to use, and you use that instance inside of main to perform the behavior you want.
// in main()
Guitar guitar = new Guitar(4, 10);
guitar.generateSong();
As an addendum, you need to be sure that you parse the integers you get from the command line, as those values are always going to be coming in as String. I leave this as an exercise for the reader.
I am making a converter from base a to base b. It is saying that I have a nullpointerexception. I have no idea how to fix it really. I know that it probably has to do with going out of bounds with the arraylist, but im not sure. I am new to java so please don't make the answer too complicated. I understand that there is a library feature to convert bases, but my professor is having us write our own.
The nullpointerexception is where the stars are (** * **)
public class NumberBase {
private static double d;
private static int i;
private static ArrayList <Character> c;
private static double sum;
private static ArrayList <Integer> result = new ArrayList <Integer>();
public NumberBase(){
i = 0;
c = new ArrayList <Character>();
}
public static String convert(String input, int base_in, int base_out){
while(i < input.length()){
c.add(input.charAt(i)); (*****)
i++;
}
int digit;
i = 0;
while(i < result.size()-1){
digit = Character.getNumericValue(c.get(i));
result.add(digit);
i++;
}
d = toBaseTen(base_in);
String str = "" + d;
return str;
}
public static void main(String args[]){
}
public static double toBaseTen(int base_in){
i--;
while(i > 0){
sum = result.get(i)*(Math.pow(base_in, i));
i--;
}
return sum;
}
public int fromBaseTen(int base_out){
}
}
Your convert method is static. That means that it is a class-wide method. Your ArrayList "c" is a property of the NumberBase class. Since convert is static, it does not have access to Object-specific properties declared in the class (static means it's a method of the class, not a method that acts on an object).
Basically - if you want to access the properties you defined, you have to make a member of the class they are defined for. Static methods don't need an actual Object to function.
If you remove the static keyword from convert:
public String convert(String input, int base_in, int base_out){
int i = 0;
while(i < input.length()){
c.add(Character.valueOf(input.charAt(i))); //(*****)
i++;
}
You can call it with:
public static void main(String args[]){
NumberBase b = new NumberBase();
String s = b.convert("test", 0, 3);
}
Because your method was static, you never actually instantiated a member of the NumberBase class. This means that your constructor was never called:
public NumberBase(){
i = 0;
c = new ArrayList <Character>();
}
Since you were instantiating (creating) your ArrayList Object in your constructor (which was never called), when the convert method tried to access the ArrayList "c" there was nothing there and you got an exception.
EDIT:
If your method must be static, to use an ArrayList inside of it you either need to pass one in as a parameter or instantiate an ArrayList inside of your method.
ArrayList<Character> c = new ArrayList<>();
^ If you put that inside of the body of your method (somewhere before you use it!) you will not get null pointer exceptions.
I have one class called DVD collection and another one called movies. The method with the array that I'm trying to return looks like this:
public class DVDCollection
{
public static DVD[] collection;
public static void searchForDVD( String DVD[], String a) {
System.out.println("What DVD would you like to search for?");
Scanner scan = new Scanner(System.in);
a = scan.nextLine();
int N = DVD.length;
for (int i = 1; i < N; i++)
for (int j = i; j > 0; j--)
if (DVD[j-1].compareTo(DVD[j]) > 0)
change(DVD, j, j-1);
else break;
for (int i = 0; i < DVD.length; i++) {
System.out.print(DVD[i] + a);
}
System.out.println();
}
}
And I'm trying to call it from my main method like so:
public class Movies
{
public static void main (String[] args)
{
DVDCollection movies = new DVDCollection();
movies.searchForDVD(DVD);
}
}
But it gives me an error saying cannot find symbol - variable DVD
So what exactly is the problem here?
You're calling
movies.searchForDVD(DVD);
but there is no DVD variable defined in the main method. And BTW, even if there was one, the searchForDVD() method takes two arguments, and not just one.
Also note that the searchForDVD() method is static. So you don't need any instance of DVDCollection to call it. Instead of
DVDCollection movies = new DVDCollection();
movies.searchForDVD(...);
you should use
DVDCollection.searchForDVD(...);
In your main method when calling the searchForDVD method you must pass it an array of strings for the dvds along with the name of the dvd as a string.
At the moment you are passing the variable DVD which you have not declared anywhere in the main method.
Code in main method should be:
String[] dvds = new String[] {"firstDVD","secondDVD","thirdDVD");
String movie = "secondDVD";
DVDCollection.searchForDVD(dvds,movie);
problem 1
movies.searchForDVD(DVD);
the parameter DVD is not defined.
problem 2
public static void searchForDVD(...) is a static method of class DVDCollection you should call it DVDCollection.searchForDVD(...) you don't need the movie object.
You are calling DVD several times in this code. I believe the mistake here is the variable name.
You have defined public static DVD[] collection; which is an array of DVD objects called collection. The variable name is collection and that is what you need to use when referencing the variable.
ie: collection.length instead of DVD.length.
When you say public static DVD[] collection;, you are telling the compiler to create you a public, static Array of DVD objects called collection. At some point this array would need to be initialized. Arrays are initialized in the following format:
DVD[] collection = new DVD[];
or
String[] arrayOfStrings = {"a","b","c","d"};
Another problem is that your method is defined as follows:
public static void searchForDVD( String DVD[], String a)
This method is requiring two arguments, not one. If you are trying to require a String[] array called "DVD" then you should declare as follows:
public static void searchForDVD( String[] DVD, String a)
That declaration says this method takes an array of strings and we'll call it DVD and another String which will be called a.
Make sure to note what your variable type is and what your variable name is.
The type tells java what to expect in the variable, the name is how you access it.
String myString = "string data";
String is the type. myString is the variable name. "string data" is the value assigned to the variable.
What makes sense to me is something like:
public class Movies
{
public static void main (String[] args)
{
DVDCollection movies = new DVDCollection();
//create an Add function inside DVDCollection which reads lines from a text file into collection
movies.Add("list_of_movies.txt");
// no arguments are needed here imo, just have it print to user to ask for a DVD to search and then search the collection
movies.searchForDVD();
}
}
public class DVDCollection
{
public DVD[] collection;
public void Add(string file)
{
// parse file and add contents to collection
}
public void searchForDVD()
{
System.out.println("What DVD would you like to search for?");
Scanner scan = new Scanner(System.in);
a = scan.nextLine();
int N = DVD.length;
for (int i = 1; i < N; i++)
for (int j = i; j > 0; j--)
if (DVD[j-1].compareTo(DVD[j]) > 0)
change(DVD, j, j-1);
else break;
for (int i = 0; i < DVD.length; i++)
{
System.out.print(DVD[i] + a);
}
System.out.println();
}
}
My assignment was to write a Java class that creates an array of integers, fills it with values, prints the unsorted values, sorts the values into ascending order, and finally prints the sorted values.
For the most part I have done that and my output is fine. However I have not been able to define the array locally within the main(), and pass it as a parameter to the other methods.
I try to define it as a static member of the class which cannot be done.
Can anyone help me out? I need to define the array in the main() and pass it as a parameter to the methods. But I just cannot figure it out despite tireless research.
Here is what I have so far.
public class ArraySort {
private static Object sc;
int[] array;
// creates question and int for user input
/**
*
*/
public void fillArray() {
Scanner keyboardScanner = new Scanner(System.in);
System.out.println("Enter the size of the array (3 to 10): ");
int n = keyboardScanner.nextInt();
array = new int[n];
// creates new question by including int
System.out.println("Enter " + n + " values" );
// creates for loop for repeating question based on array size
for (int i=0; i<n; i++) {
System.out.println("Enter value for element " + i + ": ");
array[i] = keyboardScanner.nextInt();
}
}
// prints i in the for loop
public void printArray(String msg) {
System.out.println(msg);
for (int i=0; i<array.length; i++) {
System.out.println(array[i]);
}
}
// defines method
public void sortArray() {
// sets up to output in ascending order
for (int i=0; i<array.length; i++) {
for (int j=i+1; j<array.length; j++) {
if (array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}
// main output and visual layout
public static void main(String[] args) {
ArraySort arraySort = new ArraySort();
arraySort.fillArray();
System.out.println();
arraySort.printArray("The unsorted values... ");
arraySort.sortArray();
System.out.println();
arraySort.printArray("The sorted values... ");
// Keep console window alive until 'enter' pressed (if needed).
System.out.println();
System.out.println("Done - press enter key to end program");
}
}
I have no errors, I just need help on how to define the array locally in the main()
Thanks.
Remove the int[] array; declaration from the class. Add it to the main method:
int[] array = new int[n];
And add an argument int[] array to each method which needs to access it. For example:
public void printArray(String msg, int[] array) {
...
}
You can declare your array locally in your main method. And pass it as a parameter to the method you are calling.
Since when you pass array as parameter to another method, its reference will be copied to the parameter. So any change you make to passed array in your method, will get reflected back in your main() method in your original array. Try using this. I don't think you will face any problem.
UPDATE: - Ok, here's the modified code: -
import java.util.Scanner;
public class ArraySort {
private static Object sc;
private static Scanner keyboardScanner = new Scanner(System.in);
// creates question and int for user input
/**
*
*/
public void fillArray(int[] array) {
// creates for loop for repeating question based on array size
for (int i=0; i<array.length; i++) {
System.out.println("Enter value for element " + i + ": ");
array[i] = keyboardScanner.nextInt();
}
}
// prints i in the for loop
public void printArray(String msg, int[] argsArray) {
System.out.println(msg);
for (int i=0; i<argsArray.length; i++) {
System.out.println(argsArray[i]);
}
}
// defines method
public void sortArray(int[] array) {
// sets up to output in ascending order
for (int i=0; i<array.length; i++) {
for (int j=i+1; j<array.length; j++) {
if (array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}
// main output and visual layout
public static void main(String[] args) {
System.out.println("Enter the size of the array (3 to 10): ");
int n = keyboardScanner.nextInt();
int[] array = new int[n];
ArraySort arraySort = new ArraySort();
arraySort.fillArray(array);
System.out.println();
//I still get an error saying " cannot find symbol"
arraySort.printArray("The unsorted values... ", array);
//same here
arraySort.sortArray(array);
System.out.println();
//and here
arraySort.printArray("The sorted values... ", array);
// Keep console window alive until 'enter' pressed (if needed).
System.out.println();
System.out.println("Done - press enter key to end program");
}
}
Update public void printArray(String msg) { and public void sortArray() { to accept int [] as
/ prints i in the for loop
public void printArray(String msg, int[] argsArray) {
System.out.println(msg);
for (int i=0; i<argsArray.length; i++) {
System.out.println(argsArray[i]);
}
}
// defines method
public void sortArray(int[] argsArray) {
// sets up to output in ascending order
for (int i=0; i<argsArray.length; i++) {
for (int j=i+1; j<argsArray.length; j++) {
if (argsArray[i] > argsArray[j]) {
int temp = argsArray[i];
argsArray[i] = argsArray[j];
argsArray[j] = temp;
}
}
}
}
And you may want to leave array = new int[n]; in fillArray as local as:
int[] array = new int[n];
and remove it from class variable declaration.
You've said that you need to define the array in the main() and pass it as a parameter to the methods. If so, then you'll need to change those methods, e.g.:
public void printArray(String msg, int[] argsArray)
public void sortArray(int[] array)
fillArray is different, because you create the array in the method based on a size which is input by the user, so you can't simply pass the array as an argument. You can return the new array:
public int[] fillArray()
{
int[] array;
// ...
return array;
}
But if you're only trying to test your class then note that you have access to the ArraySort.array field from main: you can set the field to an array that you create in main.
So in main:
ArraySort arraySort = new ArraySort();
arraySort.array = new int[]{ 5, 4, 3, 6, 7};
// and remove the fillArray call
// ...
Note that if you want to set the array like this, then you should also remove the fillArray call, which tries to set the array from user-entered values.