im quite a beginner in Java and im facing a problem with my code.Bascially I have a class containing a method that create a listarray based on user input:
public class manage{
public void adding() {
boolean loop = true;
ArrayList<Game> thegame = new ArrayList<Game>();
while(loop) {
Scanner agame = new Scanner(System.in);
System.out.print("name: \n");
String Cgame = agame.nextLine();
Scanner qty = new Scanner(System.in);
System.out.print("the qty: \n");
int CQty = qty.nextInt();
Console wertgame = new Console(Cgame,Cqty);
thegame.add(new Game(Cgame,Cqty));
System.out.println("continue?");
Scanner autre = new Scanner(System.in);
int continu = other.nextInt();
if(continu==1) {
}
else if(continu==2) {
Main.menu();
}
}
return thegame;
}
And then I have another method in the same class that is to display it:
public void information(List<Game> thegame) {
System.out.print(thegame);
}}
The problem im having here, is that I need to access the information(List thegame) method, from another class(java file).However,how do I access it from my other class since I cant access(call) it using "manage.information()"since it needs argument,but my arraylist isnt created yet in my other class,it gets create only when in the manage class.So I cant pass the arguments when calling it.How do I access/call it from my other class then?
thank you
The simple answer is that you can't.
If you want to call a method that requires an argument, then you need to pass that argument in some form or another.
IMO, the best solution would simply be to not call the information method at the point where you don't have the argument it requires. The sole purpose of the method seems to be to print out its argument, so if you don't have an object (list) to print then the method call cannot do anything worthwhile.
Alternatively, you could pass a null instead of a list, but that will simply result in the method outputting "null" which seems rather pointless.
In short, you can't pass an argument that doesn't exist. It simply makes no sense. Think again about what you are actually trying to do here.
Related
I'm trying to implement a function to read files, but I cannot change the signature of the method. There are a lot of cross references in the code but maybe someone can enlighten me, I have been stuck for 3 days right now. This is for a school assignment.
The first method I'm trying to pass into the function is the following:
public static Purchase fromLine(String textLine, List<Product> products) {
Purchase newPurchase = null;
String[] purchases = textLine.split(",");
int foundBarcode = products.indexOf(getProductFromBarcode(products, Long.parseLong(purchases[0])));
products.indexOf(purchases);
newPurchase = new Purchase(
products.get(foundBarcode),
Integer.parseInt(purchases[1].trim())
);
Somehow I want to pass this function into my import file function.
public static <E> void importItemsFromFile(List<E> items, String filePath, Function<String,E> converter) {
int originalNumItems = items.size();
Scanner scanner = createFileScanner(filePath);
// TODO read all source lines from the scanner,
// convert each line to an item of type E and
// and add each item to the list
while (scanner.hasNext()) {
// input another line with author information
String line = scanner.nextLine();
// TODO convert the line to an instance of E
E newItem = converter.apply(line);
// TODO add the item to the list of items
items.add(newItem);
}
System.out.printf("Imported %d items from %s.\n", items.size() - originalNumItems, filePath);
}
I hope someone can help me and explain how to pass this function into the other function's converter parameter.
Tried to do a lot of research on this topic but I'm still not able to find the answer. Please help me stackoverflow community!:D
You need to declare this like this first inside a 'super - private function'
private Function<String, Purchase> doSomething() {
return textLine -> {
Purchase newPurchase = null;
String[] purchases = textLine.split(",");
int foundBarcode = products.indexOf(getProductFromBarcode(products, Long.parseLong(purchases[0])));
products.indexOf(purchases);
return new Purchase(products.get(foundBarcode), Integer.parseInt(purchases[1].trim())
};
}
Then before calling this importItemsFromFile() method, you declare this function as a variable
Function<String, Purchase> abcFunction = doSomething();
and then call this importItemsFromFile() function like this
importItemsFromFile(items, filePath, abcFunction);
The reason why this works is, lambda operator returns a Functional Interface, here it is "Function", if you pass 3 arguments, you will need a BiFunction<T, U, R> for that.
Thats why these FunctionalInterfaces are sometimes called super private functions, as they are used inside another function.
And Hey give me extra points for this, as I even completed your half written function, and saved your 3 days time.
I am a little lost by the top snippet, but all you need to do is define an implementation of the Function interface. You can do this simply by defining a class that implements the interface or you can specify a lambda that would do the same thing.
Assuming the top code block is what you want in your lambda you would do something like this,
(textLine) ->{
String[] purchases = textLine.split(",");
int foundBarcode = products.indexOf(getProductFromBarcode(
products, Long.parseLong(purchases[0])));
products.indexOf(purchases);
return new Purchase(
products.get(foundBarcode),
Integer.parseInt(purchases[1].trim())
)
I really want to know if there is a way to only get the value from the method to an another method. Because in the main method the first method is already call out while the the second needed the value of the input from the first method.
//Main method
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int an = 0;
an = first_method(an);
second_method();
}
//First Method
static int first_Method (int num) {
Scanner reader = new Scanner(System.in);
boolean done = false;
int num = 0;
while(!done) {
try {
System.out.print("Enter a Number: \t\t");
num = reader.nextInt();
done = true;
}
catch (InputMismatchException e) {
String s = reader.nextLine();
System.out.println("Invalid a number: " + s);
}
}
return num;
}
//Second Method
static void second_method()
{
int anum = 0;
anum = first_method(anum);
System.out.println(anum);
}
P.S. I know that my question have similar question from others in here but so far from what I have search there is none that solve my problem with a mismatch exception so if there is any same problem as me and already question in here then you can link it. Thanks
Sure. Its called a 'parameter':
static void secondMethod(int v) {
System.out.println(v);
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int an = firstMethod(an);
secondMethod(an);
}
Here, you let firstMethod run, it produces a result (it's what you return). You then pass that result to secondMethod. Parameters are like local variables, except they are initialized to a value that the code that invokes your method determines. Here, the secondMethod method has a local variable named v, and its value starts out as whatever the code that calls secondMethod wants it to be. Here, we want it to be whatever firstMethod returned, thus letting us pass something firstMethod calculated, to secondMethod to work on.
Here, you let firstMethod run, it produces a result (it's what you return). You then pass that result to secondMethod. Parameters are like local variables, except they are initialized to a value that the code that invokes your method determines. Here, the secondMethod method has a local variable named v, and its value starts out as whatever the code that calls secondMethod wants it to be. Here, we want it to be whatever firstMethod returned, thus letting us pass something firstMethod calculated, to secondMethod to work on.
I'm trying to understand Array Object, and what I want to do is call my array in every class I have.
this is my code:
projectProva.java
public class ProjecteProva {
Scanner sc = new Scanner(System.in);
private final int maxContador = 4;
private final DadeArr LlistaUsuari[] = new DadeArr[maxContador];
int ContadorActual;
}
DadeArr.java
public class DadeArr {
private String nomUsuari;
private String cognomUsuari;
public DadeArr(String nU, String nC){
nomUsuari = nU;
cognomUsuari = nC;
}
Right now I'm working in projectProva.java , I have some method that saves into array a data input with scanner.
Here is an example of one of my method:
public int inserir(int aContadorActual){
ContadorActual = 1;
for (int i=1;i<=ContadorActual;++i){
System.out.println("Introdueix el nom del usuari: ");
String nU = sc.nextLine();
//sd.setNomUsuari(Name);
System.out.println("Introdueix el teu cognom : ");
String nI = sc.nextLine();
LlistaUsuari[ContadorActual] = new DadeArr(nU,nI);
System.out.println("El teu usuari s'ha creat satisfactoriament");
}
ContadorActual++;
return ContadorActual;
}
This method asks user his name and surname and saves it in array LlistaUsuari.
Then, I want to use this array(with the data in) in another .java file from the same package, but i don't know how to properly call the array.
I just started to learn this type of array, and i want to understand it.
After solving this , im looking forward to take all array info and send it to a data base or text file.
If I can't proceed with it i will switch to Array 2D.
Plus, I'm wondering if this type of Array ( array object ) is very usefull or not.
Thanks.
I also made this question at https://www.reddit.com/r/javahelp/comments/dsyu4b/array_object/?
You have multiple gotchas in your code.
1. you should always iterate an array from index 0 (unless you have special needs or you are programming in a language like Python where arrays start from 0)
2. You should set the condition in the loop to be less than the exact length of the array. So in your case it will be i < LlistaUsuari.length. You are getting a null because you are only filling up index #1 of the array.
All you need is a public getter method for the array that you want to access.
Something like:
public DadeArr[] getLlistaUsuari() {
return this.LlistaUsuari;
}
And that should do it.
In other classes, create an instance of ProjecteProva (lets's call it pPI) and to get the array there, simply do pPI.getLlistaUsuari() and you'll have it,
I came across this code that says
new Class_Name(); // (i)
Now, normally I see the result of the new statement assigned to a variable:
Class_Name n = new Class_Name();
And n reference to the object created. What really happens when the (i) is called? And why would anyone want to do it? What are the uses for it?
CODE
class Tree {
int height;
Tree() {
print("Planting a seedling");
height = 0;
}
Tree(int initialHeight) {
height = initialHeight;
print("Creating new Tree that is " +
height + " feet tall");
}
void info() {
print("Tree is " + height + " feet tall");
}
void info(String s) {
print(s + ": Tree is " + height + " feet tall");
}
}
enter code here
public class Overloading {
public static void main(String[] args) {
for(int i = 0; i < 5; i++) {
Tree t = new Tree(i);
t.info();
t.info("overloaded method");
}
// Overloaded constructor:
new Tree();
}
}
What really happens when the (i) is called
The below line of code creates an object of type Class_Name and since it is not referred by any reference variable , it dies immediately.
new Class_Name();
This way you can create an object of that class , and invoke methods on it without assigning it to a reference. This you will do when you need that object only once in your code and don't want to unnecessarily keep a reference to it . The anonymous object is created and dies instantaneously. This is quick and dirty :
new Class_Name().someMethod();
In I/O streams and AWT, we use many objects only once in the program; for them, better go for anonymous objects as follows.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
After the Edit:
new Tree();
Your intention here was to execute the code in the constructor .But your code won't compile I believe you need to put the last line inside some method.
new Class_Name();
This statement will create the object of Class_Name and constructor will be called but you are not holding the refernece of that class, so you can not call any other method. Here this Object scope will be limited where it has written, say in method or block.
A general use of it. new Thread(new RunnableTest()).start();
class RunnableTest implements Runnable{
public void run(){
for(int i=0;i<10;i++){
System.out.println("i : "+i);
}
}
}
new class_name() will create object of class_name.As you are not storing reference of it ,you will not be able to use same object in the code after this statement.But it's good practice to store the reference of object if you want to use it later in code.Which will help you to reduce efforts in managing multiple objects and memory too.
when you want to use oop you must create lots of class with a lots of attribute
and sometimes you need to use a attribute of some class in a specific class so you need to
create a object of those class by using
new Class_Name();
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Static method in java
Ok, so I'm working on a project for a class I'm taking.. simple music library. Now I'm having some issues, the main issue is I'm getting "non-static method cannot be referenced from a static context"
Here is a function I have
public void addSong() {
Scanner scan = new Scanner(System.in);
Song temp = new Song();
int index = countFileLines(Main.databaseFile);
index = index + 2;
temp.index = index;
System.out.print("Enter the artist name: ");
temp.artist.append(scan.next());
}
Now thats in a class file called LibraryFunctions. So I can access it with LibraryFunctions.addSong();
Now I'm trying to run this in my main java file and its giving me the error, I know why the error is happening, but what do I do about it? If I make addSong() a static function then it throws errors at me with the Song temp = new Song() being static. Kind of ironic.
Much help is appreciated on this!
Follow these simple rules:
If it's a static method call it with ClassName.methodName()
If it's a non-static method call it with classInstance.methodName()
If you want to call it as LibraryFunctions.addSong(), it needs to have the signature public static void addSong().
More info:
Only static methods can be called without instantiating a class first.
You can also try:
LibraryFunctions lf = new LibraryFunctions();
lf.addSong();
Well you have two options really:
Change addSong() to static and reference Song through it's static members if possible.
Create a new instance of LibraryFunctions and then use the non-static method addSong()
I take that your class Song is a non static nested class? e.g.
class LibraryFunctions {
class Song {
// ...
}
}
If so you can either make it a static nested class, or lift the Song class into a separate class.
In terms of structure, may I suggest that the LibraryFunctions class file be turned into a MusicLibrary class? That way, in your main application code, you can instantiate a MusicLibrary every time the code runs. It will also make it easier to separate static functions and instance functions, which would probably solve your issue right now.
public class MusicManager {
public static void main(String[] args) {
MusicLibrary myMusic = new MusicLibrary();
myMusic.addSong();
// other stuff
}
}
Then MusicLibrary:
public class MusicLibrary {
public MusicLibrary() {
}
public void addSong() {
Scanner scan = new Scanner(System.in);
Song temp = new Song();
int index = countFileLines(Main.databaseFile);
index = index + 2;
temp.index = index;
System.out.print("Enter the artist name: ");
temp.artist.append(scan.next());
}
}
And finally, I would put the class Song outside of MusicLibrary so that you can reuse it later.
Another added benefit of this is that you can make MusicLibrary implement Serializable and save the library to a file. Plus you could place an array of MusicLibraries inside of a MusicLibrary and have playlists. All kinds of options.