Empty array when calling function(java) - java

so I have this code that input stuff and store it to an listarray
public class manage extends admin{
public ArrayList<Game> thegame = new ArrayList<Game>();
public List<Game> ajout_jeux() {
boolean loop = true;
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 a method in this class that should print the array:
public void information(List<Game> thegame) {
System.out.print(thegame);
}}
And then,from another class I need to call it like this
manage management = new manage(); //the instance
manage.information();
Theres no erros,however,even if I take care of creating an object and putting it in array before trying to print the array, when I call manage.information(); it just return an empty [] list.I dont know why?
heres the class that needs to calls it
public class themenu{
public static void adminmenu(){
boolean loop=true;
while(loop){
System.out.print("1:List items \n");
System.out.print("4:Add \n");
System.out.print("6:Infos \n");
System.out.print("7:Quit \n");
System.out.print("Choice:");
Scanner choiceuser = new Scanner(System.in);
String userchoix = choiceuser.nextLine();
manage management = new manage();
if(userchoice.equals("1")){
manage.information(thegame); //here I get the error
}
else if(userchoice.equals("4")){
manage.ajout_jeux();
}
thank you

instead of calling the type of the object
manage management = new manage(); //the instance
manage.information();
you should call the method inside the object and pass an array to it.
management.information(new ArrayList<Game>());

You need to call manage.ajout_jeux before manage.information(); and then pass that list to information method. But please note that currently the return type of ajout_jeux method isList<Jeux> while you are returning from inside the method List<Game>. So you need to fix that also. Method invocation will look like this
manage management = new manage(); //the instance
manage.information(yourListName);

Related

How to proceed with making an in - BlueJ Java file manager

I know that it is a bit of a noob program, but I'm slowly getting confused. The 'down' function is going to act like cd and the 'up' function would act like cd..
I have no clue how to allow the user to create a file or folder. I attempted using arrayLists instead of arrays but couldn't sort out the errors. Any help would be appreciated.
import java.util.Scanner;
class FileManager {
//array of arrays will go here
String Dir[] = {"UserOne"};
String SystemFolders [] = {"Documents","","",};
String SubFiles [] = {"","","","","",""};
String Nav [][] = { Dir, SystemFolders, SubFiles};
int levelCounter = 0;
public void main(String[]args) {
Scanner sc = new Scanner (System.in);
System.out.println("Enter a command");
String command = sc.next();
if (command.compareTo("down") == 0)
down();
//else if is on the way
}
void down () {
//This will execute when the command is 'down'
System.out.println(Nav[++levelCounter]);
}
void up () {
//This will execute when the command is 'up'. It acts like cd..
System.out.println(Nav[--levelCounter]);
}
}
If this is the entry point of your program then you need to declare your main method as static, like so
public static void main(String[] args)
Then to access the methods in your FileManager class in your main method you need to create an instance of your class in your main method. Like this
public static void main(String[]args) {
FileManager fm = new FileManager(); // Creates an instance
Scanner sc = new Scanner (System.in);
System.out.println("Enter a command");
String command = sc.next();
if (command.equals("down")) // equals will suffice in this case
// or equalsIgnoreCase() if you dont want case to be a problem
fm.down(); // Notice now this calls the down method from the instance
//else if is on the way
}
Then look at this to example to create files or this to create folders

How to access input variable from another class? java

Trying to get the 1st class to recognize what the user inputs in the 2nd class. Any ideas as to what is going wrong here? The 2nd class works fine, but when i try to call 'input' from the main class, it says that 'input' cannot be resolved. Any suggestions and pointers much appreciated. Thanks for your time.
1st class:
public class Filter {
public static void main(String[] args) throws IOException {
BufferedReader in4 = new BufferedReader(new StringReader(automata.input));
String s = input.readLine();
while (automata.UserInput()==true){
if (automata.accepts(s)) System.out.println(s);
s = input.readLine();
}
}
}
2nd class:
public class automata extends Filter {
public static String input;
public static boolean UserInput() {
System.out.println("Please enter test data: ");
Scanner user_input = new Scanner(System.in);
input = user_input.next();
if (accepts(input) == true){
System.out.print("works");
return true;
} else {
System.out.println("Problem");
return false;
}
}
2nd class should look like:
public class Automata { // we use upper case for class names
public String input; // or better private and use a get-method
public Automata() {} // constructor
public boolean readUserInput() { // lower case here
System.out.println("Please enter test data: ");
Scanner user_input = new Scanner(System.in);
String nextInput = user_input.next();
input += nextInput; // otherwise you overwrite your current input
/*if (accepts(input) == true){
System.out.print("works");
// return true;
} else {
System.out.println("Problem");
return false;
}*/
// It is a terrible idea to return every time a single word is read
// rather read the whole String and then check if it is accepted
if (accept(input)) // whole String is checked
return true;
return false;
}
// in case the input variable is private
public String getInput() {
return input;
}
}
And then you have to access the class in this way:
public class Filter {
public static void main(String[] args) throws IOException {
Automata automata = new Automata();
if (automata.readUserInput()) {
// BufferedReader in4 = new BufferedReader(new StringReader(automata.getInput())); or automata.input in case it is public
// I don't understand why you want to read the input here again step by step
// rather read the whole input here
String userInput = automata.getInput();
}
}
}
You are confused with two different things: Class and Object. The Object is an Instance of the Class. Without understanding this you cannot understand what is wrong here.
Calling, for example Automata automata = new Automata() creates new Object of the class Automata.
"Extends" never helps you to get to the variables. It may help you to extend the current class and to use the methods that have been implemented in parent class, but you can never get to the pointers on the address spaces of that parent class.
To access a variable of another object you should declare public getter method for that variable in that class.
I think you need to replace
String s = input.readLine();
by
String s = in4.readLine(); in Filter class.
as readLine() is a method of BufferedReader Class
Try to rename the name of BufferedReader in input like this:
BufferedReader input = new BufferedReader(new StringReader(automata.input));
I think you have a typo..
Change input in the 1st class to in4.
'input' variable is declared in the 2nd class and you are trying to access it in the 1st class which is really impossible.
In class Filter, You do not have any member named input, due to which compile time exception is coming at input.readLine();.
From the context of your program, it appears that in4 should be used instead of input.
public class Filter {
public static void main(String[] args) throws IOException {
BufferedReader in4 = new BufferedReader(new StringReader(automata.input));
String s = in4.readLine();
while (automata.UserInput()==true){
if (automata.accepts(s)) System.out.println(s);
s = in4.readLine();
}
}
}

Retrive and compare int value from an ArrayList

good night. I'm trying to retrieve and compare an int variable value from an ArrayList (if that is possible) but no matter what I do it never works. I already tried methods like contains(), get() and others. My logic is really bad I guess, could someone help me ? Please?
public class Obras extends Books implements ILibrary {
protected ArrayList<Obras> ListObra = new ArrayList<Obras>();
protected String typeObra;
protected String statusBorrow;
protected int ISBNuser;
Scanner userInput = new Scanner(System.in);
Scanner tipoInput = new Scanner(System.in);
public void createnewObra()
{
System.out.println("Insert the type of the new item: [Book, article...");
typeObra = tipoInput.nextLine();
super.createnewObra();
}
....
public void addObra() {
Obras newObra = new Obras();
newObra.createnewObra();
ListObra.add(newObra);
System.out.println("> Uma nova obra foi adicionada com sucesso!\n");
....
public void BorrowObra() {
System.out.println("> Choose a book from the list: ");
showListObras();
System.out.println("\n\n> Please choose one of the items from the above list by typing it's ISBN value: ");
ISBNuser = opcaoInput.nextInt();.
if(ListObra.get(ISBN).equals(ISBNuser))
{
System.out.println("> You successfully borrowed this book");
statusBorrow = false;
}
To get an int from an ArrayList, your ArrayList would have to be defined along the lines of this:
ArrayList<Integer> arrayListOfIntegers = new ArrayList<Integer>();
or
List<Integer> listOfIntegers = new ArrayList<Integer>();
Your list appears to contain objects of class Obras.
Also, when you call ListObra.get(ISBN), this method is designed to return the object at the specified index within the list - I suspect ISBN is not an index in the list, rather an ISBN of a book?
On a separate note, try to stick to Java naming standards - variables start with lower case letters and methods use camel case (e.g. createNewObra()). It makes things easier for other developers to understand.
ListObra.get(ISBN).equals(ISBNuser)
to:
Obras o = ListObra.get(ISBN);
if (o != null && o.getISBNuser() == ISBNuser) {
System.out.println("> You successfully borrowed this book");
statusBorrow = false;
}
because you only get a object Obras and you doesn't Override equal function in Obras, so you need to get Integer ISBUser and equal to the user input.
Another Way:
Override equal:
public class Obras extends Books implements ILibrary {
#Override
public boolean equals(Object e) {
Integer i = (Integer)e;
if (this.ISBUser == i) return true;
return false;
}
}
so now can use equals function to compare:
ListObra.get(ISBN).equals(ISBNuser)

Java Class access from main

public class mainTest {
public static void main(String[] args) throws Exception {
Scanner KB = new Scanner(System.in);
String VehiclesFile = "Vehicles.txt";
File file1 = new File(VehiclesFile);
Scanner infile1 = new Scanner(VehiclesFile);
Vehicle[] Vehicles = new Vehicle[0];
try {
Scanner scanner = new Scanner(file1);
int lineCount = 0;
while (scanner.hasNextLine()) {
lineCount++;
scanner.nextLine();
}
Vehicles = new Vehicle[lineCount];
scanner = new Scanner(file1);
int VehicleCount = 0;
while (scanner.hasNextLine()) {
String[] temp1 = scanner.nextLine().split(",");
// file has been read into temp1[] now to use Vehicles
// class type
Vehicles[VehicleCount] = new Vehicle();
Vehicles[VehicleCount].setregistration(temp1[0]);
Vehicles[VehicleCount].setmake(temp1[1]);
Vehicles[VehicleCount].setModel(temp1[2]);
Vehicles[VehicleCount].setyear(temp1[3]);
Vehicles[VehicleCount].setodometer(temp1[4]);
Vehicles[VehicleCount].setowner(temp1[5]);
VehicleCount++;
}
} catch (IOException e) {
// Print out the exception that occurred
System.out.println("Unable to find ");
}
//*******This is where I need to access the class to print****************
System.out.println (Vehicle.class.getClasses());
}
}
I cannot seem to understand how to reference a specific part of the class/array of class objects
The class for Vehicle is in defined with get/set so I didn't include the code.
System.out.println(Arrays.toString(Vehicles));
Make sure that the vehicle class has toString() method overriden. Otherwise it will just print out the references.
See:
How to override toString() properly in Java?
If you want to print off data from the Vehicle objects you'll have to loop through that array and call the getter methods you mentioned before.
It should be something like
for(Vehicle v : Vehicles)
{
System.out.print(v.getYear() + " " + v.getMake() + " " + v.getModel());
}
Seems to me like you're mixing up the concept of classes and objects. Class is short for classification, so a class is a type of something. An object is a single instance of a class. So it's a single item of a certain type.
What you have is an array of objects, not classes, and you want to print the information of each object. So say you have five vehicles in your array, you will have to call the function System.out.println(/*data to print*/) five times. One for each element in the array.
To omit repetition, you can use a loop:
for (int index = 0; index < Vehicles.length; ++i) {
System.out.println(Vehicle[index].getMake());
// do the same to print other attributes of the Vehicle class
}

accessing variable within main method

I am very new to Java and writing this program to shuffle words and fix the suffle words. The following is my program. After I call mix(), I would like to be able to assign the output of word to team array within main.
For some reason, I can call mix() it works but I cannot access word which is in the shuffle function. Since I am in main and all these function within main, I thought I can access the variables. Any ideas what I am missing here?
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class Project2
{
public static void main(String[] args)
{
System.out.println("Select an item from below: \n");
System.out.println("(1) Mix");
System.out.println("(2) Solve");
System.out.println("(3) Quit");
int input;
Scanner scan= new Scanner(System.in);
input = scan.nextInt();
//System.out.println(input);
if(input==1) {
mix();
System.out.println(word);
char team[]=word.toCharArray();
for(int i=0;i<team.length;i++){
System.out.println("Data at ["+i+"]="+team[i]);
}
}
else{
System.out.println("this is exit");
}
}
static void mix()
{
String [] lines=new String[1000];//Enough lines.
int counter=0;
try{
File file = new File("input.txt");//The path of the File
FileReader fileReader1 = new FileReader(file);
BufferedReader buffer = new BufferedReader(fileReader1);
boolean flag=true;
while(true){
try{
lines[counter]=buffer.readLine();//Store a line in the array.
if(lines[counter]==null){//If there isn't any more lines.
buffer.close();
fileReader1.close();
break;//Stop reading and close the readers.
}
//number of lines in the file
//lines is the array that holds the line info
counter++;
}catch(Exception ex){
break;
}
}
}catch(FileNotFoundException ex){
System.out.println("File not found.");
}catch(IOException ex){
System.out.println("Exception ocurred.");
}
int pick;
Random rand = new Random();
pick = rand.nextInt(counter ) + 0;
System.out.println(lines[pick]);
///scramble the word
shuffle(lines[pick]);
}
static void shuffle(String input){
List<Character> characters = new ArrayList<Character>();
for(char c:input.toCharArray()){
characters.add(c);
}
StringBuilder output = new StringBuilder(input.length());
while(characters.size()!=0){
int randPicker = (int)(Math.random()*characters.size());
output.append(characters.remove(randPicker));
}
String word=output.toString();
}
}
Return string value from shuffle() method using return statement:
static String shuffle(String input) {
// . . .
return output.toString();
}
...and then use it in mix:
String word = shuffle(lines[pick]);
But it is better to read basic java tutorials before programming.
In Java, variables cannot be seen outside of the method they are initialized in. For example, if I declare int foo = 3; in main, and then I try to access foo from another method, it won't work. From the point of view of another method, foo does not even exist!
The way to pass variable between methods is with the return <variable> statement. Once the program reaches a return statement, the method will quit, and the value after the return (perhaps foo) will be returned to the caller method. However, you must say that the method returns a variable (and say what type is is) when you declare that method (just like you need to say void when the method does not return anything!).
public static void main(String[] args){
int foo = 2;
double(foo); //This will double foo, but the new doubled value will not be accessible
int twoFoo = double(foo); //Now the doubled value of foo is returned and assigned to the variable twoFoo
}
private static int double(int foo){//Notice the 'int' after 'static'. This tells the program that method double returns an int.
//Also, even though this variable is named foo, it is not the same foo
return foo*2;
}
Alternatively, you could use instance variable to have variables that are accessible by all the methods in your class, but if you're new to Java, you should probably avoid these until you start learning the basics of object-oriented programming.
Hope this helps!
-BritKnight

Categories