I have this kind of structure of program.
This program have one function named run(), and the other function named solve().
In this program, I want to get some information from run() and solve().
Also, I want to put these information to one list vector (named information_one_iteration in the following code).
Because this vectors get together to form a matrix (named information in the following code).
That's why I define the information_one_iteration as static variable, and in every new iteration new objects is defined newly.
But, I know this kind of way is not effective!
How can I improve it?
package java_test2;
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.Random;
public class staticvarTest {
private Random random = new Random();
static ArrayList<ArrayList<String>> information = new ArrayList<ArrayList<String>>();
static ArrayList<String> information_one_iteration = new ArrayList<String>();
public staticvarTest() {
}
public void run() {
for (int i=0; i<10; i++) {
information_one_iteration.add(String.valueOf(i));
solve(); // add two random number generated in function solve()
information.add(information_one_iteration);
information_one_iteration = new ArrayList<String>();
}
print_information(information);
}
public void solve() {
information_one_iteration.add(String.valueOf(random.nextInt()));
information_one_iteration.add(String.valueOf(random.nextInt()));
}
public static void print_information(ArrayList<ArrayList<String>> information) {
for (ArrayList<String> newLine : information) {
ArrayList<String> list_set = newLine;
System.out.println("");
for(String data: list_set) {
System.out.print(data+" ");
}
System.out.println("");
}
System.out.println("");
}
public static void main(String args[]) {
staticvarTest na = new staticvarTest();
na.run();
}
}
Since you are not using static ArrayList<String> information_one_iteration = new ArrayList<String>(); anywhere apart from the run method you can remove it.
I have changed the random variable since it's okay for multiple objects to share it - the behaviour remains the same therefore no need to initialize every time Main object is created.
Change the solve method to take a ArrayList as a parameter too.
print_information looks okay but there is no need for ArrayList<String> list_set = newLine;
I have also made information as a state variable over a static variable so that each instance of the object can have it's own information therefore allowing you to run multiple instances of this class.
I also added a lambda to print the members to give you an idea about them newLine.forEach(data -> System.out.println(data + " "));.
Finally I have used variable names and class names that adhere to Java coding conventions for better readability. Here is one of the style guides which you may follow https://google.github.io/styleguide/javaguide.html
The cleaned up version of your code is below
package com.company;
import java.util.ArrayList;
import java.util.Random;
public class Main {
private static Random random = new Random();
private ArrayList<ArrayList<String>> information = new ArrayList<>();
private void run() {
for (int i=0; i<10; i++) {
ArrayList<String> informationInIteration = new ArrayList<>();
informationInIteration.add(String.valueOf(i));
solve(informationInIteration); // add two random number generated in function solve()
information.add(informationInIteration);
}
printInformation();
}
private void solve(ArrayList<String> iterationInformation) {
iterationInformation.add(String.valueOf(random.nextInt()));
iterationInformation.add(String.valueOf(random.nextInt()));
}
private void printInformation() {
for (ArrayList<String> newLine : information) {
System.out.println();
newLine.forEach(data -> System.out.println(data + " "));
System.out.println();
}
System.out.println();
}
public static void main(String[] args) {
Main main = new Main();
main.run();
}
}
Based on your comments I am adding a method that creates no object for storing any information.
package com.company;
import java.util.Random;
public class Main {
private Random random = new Random();
private void run() {
for (int i=0; i<10; i++) {
System.out.println(String.valueOf(i));
System.out.println(random.nextInt() + " " + random.nextInt() + "\n");
}
}
public static void main(String[] args) {
Main main = new Main();
main.run();
}
}
This should work for you.
public void run() {
for (int i=0; i<10; i++) {
staticvarTest.information.add(solve(String.valueOf(i)));
}
print_information(information);
}
public String[] solve(String i) {
return {String.valueOf(random.nextInt()),
String.valueOf(random.nextInt()),
i};
}
Or you could maybe concatenate the array returned in solve() and the i String and avoid passing the variable around.
I have not tested the code above btw but apart from accessing and modifying the static variable there shouldn't be a problem.
Hope this works for you.
Related
I am creating a program in Java for a restaurant. I am using ArrayList but for some reason my starter class doesn't seem to run in the main menu.
This is my starter class:
import java.util.ArrayList;
public class Starter
{
Starter()
{
String[] myList = {"Coffee", "Tea", "Somosas", "Cake"};
//System.out.println(myList[]);
}
}
This seems to be correct, but when I try to choose from the Main menu it doesn't seem to work.
Main Menu:
import java.util.Scanner;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Menu
{
static Scanner input = new Scanner(System.in);
public static void main(String[]args)
{
System.out.println("1=Starter");
System.out.println("2= Main Course");
System.out.println("3=Desert");
int a =input.nextInt();
input.nextLine();
if(a==1)
{
System.out.println("Starter");
Starter OS1=new Starter();
System.out.println("Your starter is "+OS1.myList[]);
}
else if(a==2)
{
System.out.println("Main Course");
MaiinCourse OMC1=new MaiinCourse();
System.out.println("Your MainCourse is "+OMC1.MCname);
System.out.println("The price is "+OMC1.MCprice);
}
else if(a==3)
{
System.out.println("Desert");
Deserrt ODS1=new Deserrt();
System.out.println("Your Desert is "+ODS1.DSname);
System.out.println("The price is "+ODS1.DSprice);
}
else
{
System.out.println("End");
System.out.println("Program Closing");
System.exit(1);
}
}
}
The error I get is:
'.class' expected System.out.println("Your starter is "+OS1.myList[]);
How to fix this?
When I run the main menu it should allow me to choose from the array list.
I did few changes to your code. Now it works. Try and see.
import java.util.Arrays;
import java.util.Scanner;
public class Menu
{
static Scanner input = new Scanner(System.in);
public static void main(String[]args)
{
System.out.println("1=Starter");
System.out.println("2= Main Course");
System.out.println("3=Desert");
int a = input.nextInt();
input.nextLine();
if (a == 1)
{
System.out.println("Starter");
Starter OS1 = new Starter();
System.out.println("Your starter is " + Arrays.toString(OS1.getMyList()));
}
}
}
class Starter
{
private String[] myList = {"Coffee", "Tea", "Somosas", "Cake"};
public String[] getMyList()
{
return myList;
}
}
Your code won't work because you are trying to give an Array values within you class constructor (Starter constructor in this case). This will lead to a RunTime exception because you cannot create Array constants within a constructor. I much more viable approach would be to create a private Array as an attribute for each object that you create of type "Starter". Then you can use something that we call a "Getter" method to get the value of the myList attribute for the instance you're creating. Here's a mini example of how we can change your Starter class structure below:
public class Starter {
private String[] myList = {"Coffee", "Tea", "Somola", "Cake"};
public String[] getterMethod() {
return this.myList;
}
}
Now we have what is called a "Getter" method in Java which will return the private class attribute so that users cannot alter the internal state of the Object. Here is an example of how you will call the Array in your main method:
public class App {
public static void main( String[] args ) throws IOException{
System.out.println("1=Starter");
Scanner input = new Scanner(System.in);
System.out.println("Enter a number");
int a = input.nextInt();
if(a == 1) {
System.out.println("Starter");
Starter OS1 = new Starter();
System.out.println(Arrays.toString(OS1.getterMethod()));
}
}
}
That is a very simplified version of your code that I simply used to illustrate the broader concept. Here is the output:
1=Starter
Enter a number
1
Starter
[Coffee, Tea, Somola, Cake]
We simply call the getterMethod() which will return the value for the private Array that you are looking for.
Actually, your myArray is not visible outside the Starter class, so you have to make it visible by declaring as public, or package default. Here you can take help of Arraylist.
So you can change your class as below :
public class Starter {
// this myList will be visible outside of this class and can be accessed to show menu.
ArrayList<String> myList = new ArrayList<>();
Starter() {
String[] myArray = { "Coffee", "Tea", "Somosas", "Cake" };
for (String str : myArray) {
myList.add(str);
}
//System.out.println(myList);
}
}
and kindly update Your Menu.java class as below :
import java.util.Scanner;
public class Menu {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("1=Starter");
System.out.println("2= Main Course");
System.out.println("3=Desert");
int a = input.nextInt();
input.nextLine();
if (a == 1) {
System.out.println("Starter : ");
Starter os1 = new Starter();
for (String str : os1.myList) {
System.out.print(str + " ");
}
}
}
}
I have two separate files, one named WonderfulArrayList, and the other named ArrayListMain (I'm experimenting with ArrayLists, and I'm not quite sure what to do) and so I have a method in the WonderfulArrayList file, but the main file cannot see the method, which I have named booladdData, which would return true once the data is added to the array list. My WonderfulArrayList file is the following:
import java.util.*;
import java.io.*;
public class WonderfulArrayList{ //implement WonderfulArrayList
public static int ADDNums;
public static int index;
public static int HEADNums;
public static ArrayList<Integer> arr = new ArrayList<Integer>(15);
public static boolean booladdData(ArrayList<Integer>arr){
arr.add(ADDNums);
return true;
}
}
As you can see, I have booladdData instantiated with the ArrayList, named arr. Now, if you look at my main file:
public class ArrayListMain{
//public ArrayList<Integer> arr = new ArrayList<Integer>(15);
public static void main(String[]args){
ArrayList<Integer> arr = new ArrayList<Integer>(15);
int MenuNum = 0;
int ADDNums = 0;
Object Obj = new Object();
Scanner scanner1 = new Scanner(System.in); //set up scanner for user input
while(MenuNum != 7){ //menu loop
Menu(MenuNum);
MenuNum = scanner1.nextInt();
if(MenuNum == 1){
arr.booladdData();
}
For some reason, even though I know that booladdData is created as public and they're both in the same folder, the main file doesn't have the scope to be able to see booladdData in the separate file.
Any idea what I'm doing wrong?
You should be calling WonderfulArrayList.booladdData(arr) instead of arr.booladdData(). The method booladdData() is defined as a class method of your WonderfulArrayList class. It's not an instance method of Java's ArrayList.
You also might want to read into object-oriented programming. Everything in your code is static.
You need to create your type instead of ArrayList
package com.jbirdvegas.test;
import java.util.ArrayList;
public class MainClazz {
public static void main(String[] args) {
// notice I'm creating my type `MyArrayList` instead of `ArrayList` type
MyArrayList myArrayList = new MyArrayList();
myArrayList.add("blah");
System.out.println("My message:" + myArrayList.getSomething());
}
}
class MyArrayList extends ArrayList {
public String getSomething() {
return "something";
}
}
Prints:
My message: something
This question already has answers here:
How to access Java array list data from another class
(2 answers)
Closed 8 years ago.
I want to store the input in my dictionary class so that I can search the words within this class. But I also need to use the array in other classes. Does anyone have an idea of how I can add input to my Dictionary() constructor?
Does anyone have an idea of how to fix this??
Thank you so much in advance!!!!
public class Dictionary {
// Private data fields
public ArrayList<String> dict;
Dictionary() {
dict = new ArrayList<String>();
}
public void add (String s){
dict.add(s);
}
public int size (){
return dict.size();
}
public String get(int i) {
return dict.get(i);
}
public ArrayList<String> getList(){
return dict;
}
public static void main(String[] args) throws IOException {
if (args.length < 1) {
System.out.print("Must have a file.");
System.exit(1);
}
try {
File dictionaryFile = new File(args[0]);
Scanner fin = new Scanner(dictionaryFile);
System.out.println(dictionaryFile.getAbsolutePath());
if (!dictionaryFile.exists()) {
System.out.println("Dictionary " + args[0] + "does not exist");
}
else if (!dictionaryFile.canRead()) {
System.out
.println("Dictionary " + args[0] + " cannot be read.");
}
Dictionary dict = new Dictionary();
while (fin.hasNext()) {
dict.add(fin.nextLine());
}
for (int i = 0; i < dict.size(); i++) {
System.out.println(dict.get(i));
}
} catch (FileNotFoundException e) {
System.out.println("No such file found " + args[0]);
}
}
}
/**
*This is the class I want to reference the array in
*/
public class FindWords {
public static void main(String[] args) {
Dictionary dictionary = new Dictionary();
System.out.print(dictionary.getList());
}
}
Okay...the problem is you are creating a new dictionary object in this class and your array list is associated with an Object or it is defined at the object level.
So, a new arraylist gets created everytime you instantiate a Dictionary object.
Try, making the arraylist as static in your Dictionary class.
for example,
public static ArrayList<String> yourArrayList;
Now, once you have added some elements in your Dictionary in the main method, you can access that array list from FindWord class like
Dictionary.dict
or, if you are not in a position to take that decision of making array list static in dictionary class then you need to initialize the list in FindWord class too as your FindWord class code shows that you are not adding elements in the dict list here.
Here, let me try again.
Why null?
public class: FindWords {
public static void main(String[] args) {
Dictionary dictionary = new Dictionary();//1
/***
. your list initialization code should come here
. It could be a code block or a method defined in Dictionary class itself
. which can be called like dictionary.initializeList();
***/
System.out.print(dictionary.getList()); //3
}
}
here, dictionary object has an arraylist associated with it(true) but it is not initialized yet. So, when you are saying
dictionary.getList();
it is actually fetching you the uninitialized list.
Modify your findwords class a s following
public class FindWords {
Dictionary dict=null;
public void (Dictionary dict){
this.dict = dict;
}
public void print(){
for(int i=0;i<dict.getList.size();i++)
{
System.out.println(dict.getList.get(i));
}
}
after that just before fininshing your try block add the following lines
FindWords f = new FindWords(dict);
f.print();
I have an Array that is in a class called MusicArray
and I want to be able to print its data and search it in my SearchClass class
import java.util.Arrays;
import java.util.Scanner;
public class Searchclass {
public static void main(String[] args) {
MusicArray ma = new MusicArray();
for(int count = 1; count <= songDetails.length; count++){
System.out.println(SongDetails.length);
System.out.println(songDetails[count - 1]);}
In the MusicArray class I have this
public Music[] getSongDetails() {
return songDetails;
I though that this code snippet made the array availabe to the other classes
What am I missing?
You need to use the ma object to retrieve the array, like this:
Music[] songDetails = ma.getSongDetails();
Then you can iterate over the Music[] array.
You should use ma.getSongDetails() to access the array from your SearchClass.
import java.util.Arrays;
import java.util.Scanner;
public class Searchclass {
public static void main(String[] args) {
MusicArray ma = new MusicArray();
Music [] details = ma.getSongDetails();
for(int count = 0; count < details.length; count++)
{
System.out.println(details.length);
System.out.println(details[count]);
}
}
}
Unfortunately, this code will probably still have problems. You don't add any instances of Music to MusicArray, so either the array will be null (you'll see a NullPointerException) or empty (nothing will print.)
Im stuck with the following problem,
I've two classes, the first is readFromFile and the second class is newClass
readFromFile.java -
This reads a text file
Parses the lines of text into seperate strings
The values of these strings are stored in a String [ ] called dArray
For testing I've printed all values out and it works
newClass.java
This class is intended to copy the value of the string [ ] dArray into a new string and from there use the values ( for simplicity all I've included in the newClass is the code relating to copying the array)
What I'm doing wrong is that I'm returning dArray but its returning an array with nothing stored in it, so I either need a way to call main method from readFromFile.class / help creating a method in readFromFile that would do the same which I call from main
please help
import java.util.Scanner;
import java.io.*;
public class readFromFile
{
static String[] dArray = new String [30];
public static void main (String[] args) throws IOException
{
String part;
Scanner fileScan, partScan;
int i = 0;
int x = 0;
fileScan = new Scanner (new File("C:\\stuff.txt"));
// Read and process each line of the file
while (fileScan.hasNext())
{
part = fileScan.nextLine();
partScan = new Scanner (part);
partScan.useDelimiter(":");
while ( partScan.hasNext()){
dArray[i] = partScan.next();
i++;
}
}
for (x = 0;x<i;x++)
{ System.out.println(dArray[x]);
}
}
public String[] getArray()
{
return dArray;
}}
newClass.java
public class newClass {
readFromFile results = new readFromFile();// creating object from class readFromFile
public void copyArray() {
String[] dArray = results.getArray(); // Trying to return the values of String [] dArray from rr classs
//Method getArray in rr class is
// public String[] getArray()
// { return dArray; }
String[] arrayCopy = new String[dArray.length];
System.arraycopy(dArray, 0, arrayCopy, 0, dArray.length);
for (int i = 0; i < arrayCopy.length; i++)
System.out.println(arrayCopy[i]);
}
public static void main(String[] args) {
newClass.copyArray();
}
}
Your results generation is in readFromFile.main(), but you're expecting to call it in your readFromFile(). You need to make a constructor for readFromFile, and call that in your main method, as well.
The problem is that both classes have a main method. Only the class that you intend to run should have a main method, the other classes need only constructors. Assuming you want to run a unshown class it would be written like this.
public class ThirdClass{
public static void main(String[] args) {
readFromFile reader = new ReadFromFile();
newClass copy = new newClass();
reader.readFromFile();
String[] strings = reader.getArray();
copy.copyArray(strings)
}
For this to work you need to put all of the code in the main of readFromFile in a method called "readFromFile". and you need a method in newClass that accepts a string array as an argument. Or a constructor that accepts a string array.
Make sure that neither of them have main methods or it won't work.
Remove the static keyword before your dArray variable
Change public static void main(String[] args) throws IOException in your first class to public readFromFile() throws IOException. Keep the code inside it the same.
Change the line newClass.copyArray(); in your second class to (new newClass()).copyArray();
Move the line in your second class readFromFile results = new readFromFile(); into the public void copyArray() method.
Change public void copyArray() in your second class to public void copyArray() throws IOException
Put a try..catch block around your code in the second class's main method. i.e. change (new newClass()).copyArray(); to something like try { (new newClass()).copyArray(); } catch (IOException e) { e.printStackTrace(); }
The above should get your thing working, but a friendly note would be to experiment with the code (once it works) since it's an excellent example to understand how static keywords are used, how Exceptions are handled or thrown, and how IO is used. ;)