Java non static method playCompletely cannot be referenced from a static context - java

I've been trying to create a method (in a separate class) that takes a String as a parameter and uses a premade SoundEngine (a different class) object to play that file inputted as a string. This is the code I have so far. The problem comes up with
SoundEngine.playCompletely(file);
import java.util.ArrayList;
public class AudioFileList
{
// Field for a quantity of notes.
private ArrayList<String> files;
// Constructor that initializes the array field.
public AudioFileList()
{
files = new ArrayList<String>();
}
// Method to add file names to the collection.
public void addFile(String file)
{
files.add(file);
}
// Method to return number of files in the collection.
public int getNumberOfFiles()
{
return files.size();
}
// Method to print the strings in the collection.
public void listFiles()
{
int index = 0;
while(index < files.size())
{
System.out.println( index + ":" + files.get(index));
index++;
}
}
// Method that removes an item from the collection.
public void removeFile(int fileNumber)
{
if(fileNumber < 0)
{
System.out.println ("This is not a valid file number");
}
else if(fileNumber < getNumberOfFiles())
{
files.remove(fileNumber);
}
else
{
System.out.println ("This is not a valid file number");
}
}
// Method that causes the files in the collection to be played.
public void playFile(String file)
{
SoundEngine.playCompletely(file);
}
}
Any help is very much appreciated.

SoundEngine's playCompletely function is an instance function, not a class function. So instead of:
SoundEngine.playCompletely(file); // Compilation error
you want:
// First, create an instance of SoundEngine
SoundEngine se = new SoundEngine();
// Then use that instance's `playCompletely` function
se.playCompletely(file);

Related

Using an ArrayList to display values from another class

I am trying to make a to do list that asks you to enter your tasks one by one then display them in order (as in 1. task1, 2. task 2, 3. task 3 etc). But when it displays the tasks it comes back as "0. null" one time instead of listing any of the tasks entered. Here is the script I am using:
1st class
package todolist;
import java.util.ArrayList;
public class ToDoList1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<ToDoList2> list = new ArrayList<ToDoList2>();
System.out.println("Time to make a digital to-do list!");
ToDoList2 n = new ToDoList2();
list.add(n);
System.out.println(ToDoList2.name + "'s to-do list");
System.out.println(ToDoList2.i + ". " + ToDoList2.l);
for(ToDoList2 enhanced : list)
{
System.out.println(ToDoList2.i + ". " + ToDoList2.m);
}
}
}
2nd class
package todolist;
import java.util.Scanner;
public class ToDoList2 {
public static String name;
public static int i;
public static String l;
public static String m;
{
Scanner s = new Scanner(System.in);
System.out.println("First type your name to identify your list in case you lose it");
name = s.nextLine();
System.out.println("Make sure to type \"end\" when you are finished");
System.out.println("Type in the first item on your to-do list");
String l = s.nextLine();
}
public ToDoList2()
{
Scanner s = new Scanner(System.in);
for(int i = 1; i == i; i++)
{
System.out.println("Type in the next item for your to-do list");
String m = s.nextLine();
if("end".equals(m))
{
break;
}
}
}
}
Your code is not correct. ToDoList2 scanning item list from standard input but not storing it. You should do as follow
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class TodoList {
public static String name;
List<String> tasks;
public TodoList(String name) {
this.name = name;
this.tasks = new ArrayList<>();
}
public void addTask(String task) {
this.tasks.add(task);
}
public String toString() {
int i = 1;
StringBuilder stringBuilder = new StringBuilder();
for (String task : tasks) {
stringBuilder.append(i + ". " + task);
stringBuilder.append("\n");
i++;
}
return stringBuilder.toString();
}
}
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("First type your name to identify your list in case you lose it");
String name = s.nextLine();
System.out.println("Make sure to type \"end\" when you are finished");
System.out.println("Type in the first item on your to-do list");
TodoList todoList = new TodoList(name);
String task = null;
while (!(task = s.nextLine()).equals("end")) {
todoList.addTask(task);
System.out.println("Type in the next item for your to-do list");
}
System.out.println(todoList);
}
}
a) Given that each ToDoList2 object is a separate task, I'm not sure why you've made the object class members static?
b) In your ToDoList2 constructor, you've got a for loop that introduces a local variable i which hides the ToDoList2 member variable i. You'd do well to change one of the variable names.
c) In your ToDoList2 constructor, you've got a for loop which is assigning a string returned by the Scanner to a local variable m. Are you sure you want m to be a local variable or do you actually want to assign the returned string to the member variable, m? I'm thinking the latter since the member variable m is never being assigned a value which explains why the code is printing out null.
d) When writing code, it is good practice to use meaningful variable names. Using names like i is OK as an index in a loop but in all other circumstances, you should go for something more descriptive that tells the reader what the variable is storing.
e) Consider making all your ToDoList2 member variables private (and final if possible). Add a print function to the ToDoList2 class to print out the task details. A key principle is Object Oriented Programming is to hide the internals of a class.

I'm trying to give the value of an array of a class to another array with the same class, is there something I'm missing here?

The class is called Exposicion and has a String and an INT value, so I used it as an array to grab some input from the user.
class Exposicion {
public String nombreExpo;
public int duracionExpo;
Exposicion(String nombreExpo, int duracionExpo) {
this.nombreExpo = nombreExpo;
this.duracionExpo = duracionExpo;
}
}
With the Function SortExpo I plan to copy only the values of the array as long as the INT values don't add up to 180, but java flags an error when doing:
arrExpoT[posHor].nombreExpo = arrExpoS[k].nombreExpo;
This is the whole function
void SortExpo(Exposicion[] arrExpoS,int posicion,Exposicion[] arrExpoT){
int poshor=0;
int total=0;
for (int k = 0; k < posicion; k++) {
if ( total < 180 || arrExpoS[poshor].nombreExpo != "TOMADO123") {
arrExpoT[poshor].nombreExpo = arrExpoS[k].nombreExpo;
arrExpoT[poshor].duracionExpo = arrExpoS[k].duracionExpo;
arrExpoS[poshor].nombreExpo = "TOMADO123";
total = total + arrExpoS[k].duracionExpo;
poshor++;
} else {
k = posicion;
}
}
}
Error
I've added the .java file in this link
Also Main.java if this helps
You are getting a NullPointerException because "expo1" and "sala1" variables are both null. You have to pass a reference to an object on both variables. Something like this:
class SalaExpo(){
Exposicion[] expo1=new Exposicion[100];
}
public class ConsoleMenu {
private SalaExpo sala1;
void execute(){
sala1 = new SalaExpo();
}
}
Also you should poblate the sala1.expo1 array, like this (don't know if this is what you are intending but you should do this in order not to get a NullPointerException) :
void GuardarExpo(Exposicion[] arrExpoG,int posicion,Exposicion[] arrSala) {
/*
Bunch
of
code
*/
arrExpoG[posicion] = new Exposicion(inputNombre,inputDuracion);
arrSala[posicion]=arrExpoG[posicion];
}
Finally, you should use the variable "posicion" instead of "sala1.expo1.length" to pass as argument to the "imprimirExpo" method, since the array "sala1.expo1" has a length of 100, that means a lot of null elements since you are not poblating it all:
ImprimirExpo(sala1.expo1,posicion);
instead of:
ImprimirExpo(sala1.expo1,sala1.expo1.length);

Java Adding multiple elements to an ArrayList

Still new to java, but I'm having an issue adding multiple new elements to my arraylist.
The idea for this method is to look and see if a name is already in the list, and if so return false, and if not then add the name and person's score to the arraylist.
I keep getting an error when I try to add it in. The add will work if it's just the name portion I add in, but once I also include the scoreOn1st it gives me an error.
public boolean addGolfer(String name, int scoreOn1st)
{
// check if the golfer is already in the collection
for (int i = 0; i < board.size(); i++)
{
if (board.get(i).equals(name))
{
return false;
}
}
// otherwise
board.add(new ScoreCard(name, scoreOn1st));
return true;
}
This is the constructor class already created for the arraylist:
public ScoreBoard(String tourneyName)
{
// initialize instance varable
this.tournament = tourneyName;
ArrayList<ScoreCard> board = new ArrayList<ScoreCard>();
}
The board should be declared outside. You can new it inside the constructor. The get !method returns a ScoreCard object on which you cannot directly call equals name.
public class ScoreBoard {
List<ScoreCard> board;
public ScoreBoard(String tourneyName)
{
this.tournament = tourneyName;
this.board = new ArrayList<ScoreCard>();
}
ScoreCard should be something like this:
class ScoreCard {
ScoreCard(String name) {//definition } //1st Constructor
ScoreCard(String name, int score) { //definition } //2nd Constructor
In the constructor the board variable is a method variable not a field.
public ScoreBoard(String tourneyName)
{
// initialize instance varable
this.tournament = tourneyName;
this.board = new ArrayList<ScoreCard>(); // I assume you have declared this field.
}

Print statements inside overridden methods not appearing

So I am pretty stuck. I have some code that is being using inside my main method which needs to override the given methods and print out a statement. I got the statement in offer(E s) to work, but can't seem to get the statements in peek() and size() to print. They are functioning properly, but the statements "Peeking at list" and "Reporting list size" just won't print in their methods. If some people can shed some light it would be greatly appreciated! The main is located in a separate file
import java.io.*;
import java.util.*;
import java.awt.*; //for Point
public class StudentList<E>extends LinkedList<E> {
public boolean offer(E s) {
super.offer(s);
System.out.println("Offering "+ s);
return true;
}
public boolean contains(Object o) {
super.contains(o);
return false;
}
public E peek(E slist){
super.peek();
System.out.println("Peeking at list") ;
return slist;
}
public int size(Integer ilist){
System.out.println("Reporting list size");
size(ilist);
//System.out.println("Reporting list size");
return ilist;
}
}
Here is the main method:
public class OfferDriver
{
public static void main ( String[] args)
{
StudentList<Integer> ilist = new StudentList<Integer>( );
StudentList<String> slist = new StudentList<String>( );
String s;
Integer i;
Scanner in = new Scanner(System.in);
System.out.print("Please enter a word to offer (\"stop\" to stop):\t");
while (in.hasNext()) {
s = in.next();
if (s.equalsIgnoreCase("stop")) { break; }
slist.offer(s);
System.out.println("Size is: " + slist.size());
System.out.print("Please enter a word to offer (\"stop\" to stop):\t");
}
System.out.println("\n" + slist);
String si = slist.peek();
System.out.println("Testing peek(): " + si);
System.out.print("Please enter an integer to offer (<any word> to stop):\t");
while (in.hasNextInt()) {
i = in.nextInt();
ilist.offer(i);
System.out.println("Size is: " + ilist.size());
System.out.print("Please enter an integer to offer (<any word> to stop):\t");
}
System.out.println("\n" + ilist);
int pi = ilist.peek();
System.out.println("Testing peek(): " + pi);
}
}
}
Most likely your peek and size methods are not called. You can always check that with the help of a debugger. You seems to be wrongly overriding the methods. So try adding #override on top of your methods.
LinkedList peek method does not take any param but your method does:
public E peek(E slist)
so it means that you are not overriding the method.
peek() is not the same as peek(E) that you have implemented.
You have defined peek within your StduentList as
public E peek(E slist) {
But are using
String si = slist.peek();
To call it...
In fact, I'm having a hard time trying to figure out why you need to override any of the methods in the first place...
When you are calling the peek() and size() in main, you called this method from
String java.util.LinkedList.peek()
int java.util.LinkedList.size()
this are not your method, which you write in your StudentList Class.

Java: index in array exists, ArrayIndexOutOfBoundsException: 0

Sorry if this is answered somewhere due to me missing something obvious, but I've been googling this for days now and it just doesn't seem to make any sense. I've got 3 years of experience in Javascript and am getting into Java now, so I'm not behind on the basic concepts of anything and such.
I'm using IntelliJ for this, but it fails to point out the problem. The communication (access rights and instantiations) between my classes is fine, the code syntax and variable types are as well, etc, so I really can't tell what it is.
I have a Data class, which just holds "read-only" data for the other classes to use.
public class Data {
// snip
public static int[][] specs = {
{6,1,6,40},
{5,2,5,30},
{5,3,4,40},
{4,4,3,60}
};
}
There's another class that has to read this data when it's initialized.
public class Soldier {
// snip
public int range;
public Soldier() {
int x = ...; // user input
range = Data.specs[x][1];
}
}
The specs array itself contains its data as defined (ie the array is not empty), x is valid as an index of the specs array (ie 0 <= x <= 3), its type is int and Test has read access to the specs array (all confirmed with debug output statements). And yet, when it tries to set the value of range (then and only then, at that exact point), I get the "Index out of bounds" error.
Can someone please tell me what's going wrong when trying to read the array? Or am I right in saying that this is really weird and I need to post the entire code?
Note: a small new test also shows that, if I change the code to first output a manually chosen value from the array and then set the value of range, the console prints the error statement (and exits the program) and follows it up by printing the manually picked value, but assigning the value and then asking to output range only throws the error... That makes absolutely no sense at all!
Edit: I've edited the code above. The class called Test is called Soldier in my code (I'm making a text-based game...). Below's the stack trace, if it's any good without the full code (which is way long). The basic structure of my program is this:
1) Boot contains the main method and instantiates a new Game
2) Game instantiates x Teams
3) each Team instantiates an Army
4) each Army instantiates x Soldiers
Each instance of the classes is set as an attribute of the instantiating class (public Army army; and an Army instantiation in the Team constructor, for example). It's essentially a cascade of constructors instantiating subsequent classes and assigning them as their attributes.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Army.<init>(Army.java:13)
at Team.<init>(Team.java:19)
at Game.<init>(Game.java:22)
at Boot.main(Boot.java:15)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)5
Edit edit: here's the semi-full code (I'm leaving out the stuff that has absolutely nothing to do with it, including the imports). It's in no particular order and the classes are in separate .java files within the IntelliJ project. The game continues up to the point where a new Soldier asks for its type to be designated (the function performing the user input is working fine and validating the input as proven by a technically identical other part of the game).
public class Boot {
public static void main(String[] args) {
Object[] games = new Object[] {};
if (Lib.userConfirmPrompt("Start the game?") == true) {
do {
games[games.length] = new Game();
}
while (Lib.userConfirmPrompt("Do you want to play again?") == true);
}
System.exit(0);
}
}
public class Game {
public Object[] teams = new Object[] {};
public Game() {
for (int i = 0;i < settings.xbots + 1;i++) {
teams[teams.length] = new Team(this);
}
}
}
public class Team {
public Game game;
public Army army;
public Team(Game p) {
game = p;
army = new Army(this);
}
}
public class Army {
public Team team;
public static Object[] soldiers = new Object[] {};
public Army(Team p) {
team = p;
for (int i = 0;i < team.game.settings.xsoldiers;i++) {
soldiers[soldiers.length] = new Soldier(this);
}
}
}
public class Soldier {
private Army army;
public int sight;
public int range;
public int distance;
public int damage;
public Soldier(Army p) {
army = p;
int type = Lib.userTxtIntOptionsPrompt(Data.isoldiertypes);
// HERE is where it crashes, type is assigned and valid but the array access fails
sight = Data.isoldierspecs[type][0];
range = Data.isoldierspecs[type][1];
distance = Data.isoldierspecs[type][2];
damage = Data.isoldierspecs[type][3];
}
}
public class Data {
public static List isoldiertypes = Arrays.asList("Scout","Private","Machinegunner","Grenadier");
public static int[][] isoldierspecs = {
{6,1,6,40},
{5,2,5,30},
{5,3,4,40},
{4,4,3,60}
};
}
public class Lib {
private static Scanner input = new Scanner(System.in);
// output
// default: 1 query string to print
public static void outBase(String query) {
System.out.print(query);
}
public static void outStd(String query) {
outBase(query + "\n");
}
// end of output
// input
// default: 1 query string to print,
// query and input are in-line (exception: userConfirmPrompt prints query block-wise and default instruction in-line before input),
// keeps user hostage until valid input is given (exception: userPrompt returns blindly)
public static String userPrompt(String query) {
outBase(query);
return input.nextLine();
}
public static String userTxtPrompt(String query) {
String menuinput = null;
do {
if (menuinput != null) {
userHostage();
}
menuinput = userPrompt(query);
} while (menuinput.length() == 0);
return menuinput;
}
public static int userIntPrompt(String query) {
String menuinput = null;
do {
if (menuinput != null) {
userHostage();
}
menuinput = userTxtPrompt(query);
} while(menuinput.matches("^-?\\d+$") == false);
return new Integer(menuinput);
}
// end of input
// options input
// default: takes a List of options as argument,
// prints an enumerated list of these options string-wise,
// prompts for a numeral selection of the desired option and returns the number if valid
public static int userTxtIntOptionsPrompt(List options) {
int choice = 0;
Boolean chosen = false;
do {
if (chosen == true) {
userHostage();
} else {
chosen = true;
}
chosen = true;
for (int i = 0;i < options.size() - 2;i++) {
outStd((i + 1) + ") " + options.get(i) + ",");
}
outStd((options.size() - 1) + ") " + options.get(options.size() - 2) + "\nand " + options.size() + ") " + options.get(options.size() - 1) + ".");
choice = userIntPrompt("Enter the number of the option you'd like to select: ") - 1;
} while(choice < 0 || choice >= options.size());
return choice;
}
// end of options input
// miscellaneous
public static void userHostage() {
outStd("Invalid operation. Please try again.");
}
}
The problem is in your Army class:
public static Object[] soldiers = new Object[] {};
You initialize an empty (length == 0) array named soldiers, but later you access:
soldiers[soldiers.length] = new Soldier(this);
This causes the failure.
By definition, soldiers.length is out of the bound of the array (since the bound is from 0 to soldiers.length-1)
To overcome it - make sure you allocate enough space in the array soldiers or use a dynamic array (ArrayList) instead. You can append elements to an ArrayList using ArrayList.add(), and you don't need to know the expected size before filling it up.
The x should be greater than -1 and less than 4.
The stacktrace does not mention the Solder class, its in the conctructor of the Army class.
Any how, only knowing that the index should be within a range is not enough. As a programmer its your duty to validate the index before trying to access an element at that index.
if(index > 0 && index < array.length) {
//then only acess the element at index
Problem is the array soldiers is of size 0.
This line int x = ...; // user input implies that you are taking input in some fashion from the user and accessing the array with it. Are you checking this value to see that is in range (i.e., between 0 and 3)? If not, this may be why your testing works.
Edit: something like this might solve it for you:
public class Army {
public Team team;
public Vector<Soldier> soldiers;
public Army(Team p) {
soldiers = new Vector<Soldier>()
team = p;
for (int i = 0;i < team.game.settings.xsoldiers;i++) {
soldiers.add(new Soldier(this));
}
}
}
Judging by your other code, this sort of pattern will be useful in your Game object as well.

Categories

Resources