How can I call my array to my main class? - java

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();
}
}

Related

how to reassign array variable stored in an object in java

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;

java arrays and inputs

How do u write to a next array index by modifying this code? I'm a noob at java. for e.g, I am calling this method from my main method, so the first time it is run, it writes to index 1 of the array. the second time it is run, it writes to index 2 of the array. however, I do not want it to loop. I have also not learnt arraylists' yet so its out of the picture unfortunately.
public class staffName {
public static void staffDetails(){
String[] staffname= new String[20];
int i=0;
staffname[i]=JOptionPane.showInputDialog(null,"Please enter staff name:")
i++;
}
You are setting variable i everytime you call a function to 0. So you only change element 0 all the time. You need to put variable i outside a function and make it static so it increments when you call the function and stays incremented.
You also must put array staffname outside, otherwise, you make new empty array everytime you call a function.
public class staffName {
public static int i = 0;
public static String[] staffname= new String[20];
public static void staffDetails(){
staffname[i] = JOptionPane.showInputDialog(null,"Please enter staff name:");
i++;
}
Define the Array only once in the main and do it like this:
public class staffName {
private static int i = 0;
String[] staffname= new String[20];
public static void staffDetails(String[] array){
array[i] = JOptionPane.showInputDialog(null,"Please enter staff name:")
i++;
}
}
calling this method from my main method, so the first time it is run, it writes to index 1 of the array. the second time it is run, it writes to index 2 of the array.
Problem is both array and index loses its scope once the method staffDetails() does its job.
Option 1: Consider sending array and index as parameter
public static void staffDetails(final String[]staffname, final int i){
staffname[i] = JOptionPane.showInputDialog(null,"Please enter staff name:");
}
public static void main(String[]args){
final String[]staffname=new String[20];
int i = 0;
staffDetails(staffname,i++);
staffDetails(staffname,i++);
}
Option 2: Make array and index as class/static members
public static void staffDetails(){
staffname[i++] = JOptionPane.showInputDialog(null,"Please enter staff name:");
}
public static void main(String[]args){
staffDetails();
staffDetails();
}
private static final String[]staffname=new String[20];
private static int i = 0;

How to create an instance of a class with a variable string name in Java?

sorry if this has been posted under a different title which I'm sure it has but I failed at finding it.
Say you have the following code:
public class Main{
public static void main(String[] args)
{
String[] names = {"James", "Allison"};
int[] ages = {10, 12};
for (int i = 0; i < names.length; i++)
{
Item names[i] = new Item(ages[i]);//line that will produce the error
}
}
class Item{
private int age;
Item(int theirAge){
age = theirAge;
}
}
Now this code will produce a duplicate variable error which comes from the names[i] variable already being defined as a String but now we are trying to define it as an Item. I have tried quite a few things but just can't seem to get it.
public class Main {
public static void main(String[] args){
String[] names = {"James", "Allison"};// variable a
int[] ages = {10, 12};
for (int i = 0; i < names.length; i++){
Item names[i] = new Item(ages[i]);//variable b
}
}
class Item{
private int age;
Item(int theirAge){
age = theirAge;
}
}
Because you have two variables have the same name, variable a and variable b. The solution for you would be either you change the variable b's name, or use the existing variable without declaration it again. However, in this case, you have different type from A to B. You cannot use the existing variable. You just have to declare a new Item object, but different name.
Hope it helps.

Why is this "not a statement" in java?

I am very new to Java. My current program loops through a block that asks for users input in the console until the value they type equals done. I want to store each value the user types in an array that is a class property. When I try to append this array, I get an error that says Error:(59, 18) java: not a statement. My code is below. I will point out the line that the error occurs on inside the code. Thanks for your time!
package com.example.java;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to the musical key calculator!");
System.out.println("Enter your notes one at a time.");
System.out.println("Use uppercase letters A-G and # for sharp and b for flat.(Ex. Eb)");
System.out.println("Remember that E# and B# do not exist in music!");
System.out.println("When you have entered all of your notes, type 'done'");
System.out.println("------------------------------------------------------------------");
boolean finished = false;
Scale YourScale = new Scale();
while(finished == false) {
System.out.print("Enter a note: ");
String note = scanner.nextLine();
if (note == "done'") {
finished = true;
} else {
YourScale.addNote(note);
}
}
if(finished == true){
StringBuilder output = new StringBuilder("Your notes are ");
String[] completedNotes = YourScale.notes;
for (int i = 0; i < completedNotes.length; i++) {
output.append(completedNotes[i] + " ");
}
}
}
public static class Scale {
public String[] notes = {};
public void addNote(String note){
notes[] = note; //Error occurs here.
}
}
}
Java arrays are fixed length, and that isn't how you create (or populate an array). I would prefer to use a Collection like,
public List<String> notes = new ArrayList<>();
public void addNote(String note){
notes.add(note);
}
But, you could use Arrays.copyOf(T[], int) and something like
public String[] notes = new String[0];
public void addNote(String note){
int len = notes.length;
notes = Arrays.copyOf(notes, len + 1);
notes[len] = note;
}
Finally, you do not test String equality with ==
if (note == "done'") {
should be something like
if (note.equals("done")) {
notes is a String array, which means it has many String objects inside. Also you initialize it to an empty array. Arrays should have a fixed size.
//Declare a variable notes, and initialize it as an empty array?
public String[] notes = {};
public void addNote(String note)
{
//This doesn't make sense in java - it's syntax is wrong
notes[] = note;
}
If you want to use arrays this is an example:
//Declare a variable notes, and initialize it as an array of
//specific size (I used 5 as example)
public String[] notes = new String[5];
public void addNote(String note)
{
//Here you should have some short of counter that counts in which
// position of the array you will save 'note' or just run a 'for'
//loop and the first element that is not initialized can get the note
for (int i = 0; i < notes.length; i++)
if (notes[i] == null)
{
notes[i] = note;
break;
}
}
Although this method allows you to save a fixed size, which is not desirable in your case, but nevertheless it uses Array and can help you understand how to use them.
If you want to implement it properly you should use an ArrayList. An ArrayList is an array where you can add new elements and remove them. You can find plenty of documentation online of how to use them.
You are trying to assign a String to a String array. You probably intended to add it to the array.

Null Pointer Exception in base converter

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.

Categories

Resources