Calling Methods in Main Class and Other Class Differences in Java - java

I have 3 classes, Mainn, ReadFile, and Entry.
ReadFile is basically my class that does all file i/o stuff.
How come I am able to access ReadFile in my Mainn class just fine, but
when I try to access it in Entry "e.openFile()" i get an error that says identifier expected.
I know this can be fixed by making an overloaded method openFile() in Entry but why is this needed in Entry, but not in the main class Mainn?
package homework6;
public class mainn {
public static void main(String[] args){
ReadFile r = new ReadFile();
r.openFile();
//r.readFile();
r.skipFirst();
String x[] = r.getData();
String y[] = r.getData();
String z[] = r.getData();
System.out.println(x[0] + "," + x[1]);
System.out.println(y[0] + "," + y[1]);
System.out.println(z[0] + "," + z[1]);
r.closeFile();
}
}
ReadFile:
package homework6;
import java.util.*;
import java.io.*;
public class ReadFile {
Scanner x = null;
public void openFile(){
try{
x = new Scanner(new FileInputStream(
"C:\\Users\\Rohan Vidyarthi\\workspace\\Data.csv"));
}
catch(FileNotFoundException e){
System.out.println("File not found error");
}
}
public void readFile(){
while (x.hasNextLine())
System.out.println(x.nextLine());
}
public void skipFirst(){
x.nextLine();
}
public String[] getData(){ //returns String[] with Date and ADJ Close
String[] temp;
String[] out = new String[2];
temp = (x.nextLine()).split(",");
out[0] = temp[0];
out[1] = temp[6];
return out;
}
public boolean checker(){
return x.hasNextLine();
}
public void closeFile(){
x.close();
}
}
class Entry:
package homework6;
public class Entry extends ReadFile{
ReadFile e = new ReadFile();
e.openFile();
double minn = Double.MAX_VALUE;
double maxx = Double.MIN_VALUE;
/*public String[] rMax(){
String[] temp1;
String[] temp2;
}
*/
}

I suggest you move your openFile() logic to the ReadFile class constructor as shown below and this approach will give you two advantages:
(1)scanner (which is a mandatory variable of ReadFile class) gets initialized inside the class constructor which makes more sense and avoids all NullPointerException i.e., someone accidentally calling other methods first before openFile() (Always ensure that all mandatory instance variables i.e., data is being initialized by the constructors, I strongly suggest make it as a practice and never allow any object being created freely without being the mandatory variables initialized through constructors which will avoid most of the issues).
(2) It will fix your problem automatically as you don't need a call to openFile() method (well, you don't have that method itself, ReadFile constructor has initialized the scanner).
public class ReadFile {
Scanner x = null;
public ReadFile() {
try{
x = new Scanner(new FileInputStream(
"C:\\Users\\Rohan Vidyarthi\\workspace\\Data.csv"));
}
catch(FileNotFoundException e){
System.out.println("File not found error");
}
}
public void readFile(){
//add code
}
public void skipFirst(){
//add code
}
public String[] getData(){
//add code
}
public boolean checker(){
return x.hasNextLine();
}
public void closeFile(){
x.close();
}
}
Just ensure that you don't need to call openFile() anymore as shown below:
public class Entry extends ReadFile{
ReadFile e = new ReadFile();//initializes scanner as well
public String[] readFile() {//add any methods you like here in this like
return e.readFile();
}
double minn = Double.MAX_VALUE;
double maxx = Double.MIN_VALUE;
}
How come I am able to access ReadFile in my Mainn class just fine, but
when I try to access it in Entry "e.openFile()" I get an error that
says identifier expected.
In Java, invocation of any method call (like your r.openFile()) should be done from another method or from constructor or from initializers (static or instance initializer), so the answer is in your Mainn class, you are calling the openFile() inside from main(String[] args) method whereas in your Entry class your openFile() method call is not wrapped inside any of the above-mentioned code blocks (i.e., methods, constructors, initializers).
One more important point is that in general when you say A extends B in Object Oriented Languages, it means that A IS-A type of B, but in your code Entry extends ReadFile does not make much sense, so you should avoid that.

put e.openFile(); in a method or constructor. You cannot place floating codes outside methods. Any statement can only be used inside the block of codes (i.e. methods, constructors, static initializers)

If you do
public class mainn {
ReadFile r = new ReadFile();
r.openFile();
//r.readFile();
r.skipFirst();
String x[] = r.getData();
...
you will receive the same error in mainn

Related

ArrayList class separate from Java main file

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

Java - Getting the value of a method inside of a class

I am trying to get the value of a method that is inside a class into the main class.
The code is supposed to let me give the variables 'a', 's' and 'u' each a value by using the console and afterwards return the values to the main class.
import java.util.*;
public class Auslesen
{
String a;
private int s;
double u;
public class Scannen
{
Scanner scanner = new Scanner(System.in);
public int Methode()
{
s = scanner.nextInt();
return s;
}
}
}
and here is my main class:
public class Start
{
public static void main(String[] args)
{
Auslesen auslesen = new Auslesen();
//System.out.println(auslesen);
Auslesen.Scannen scannen = auslesen.new Scannen();
//System.out.println(scannen);
Auslesen.Scannen.Methode methode = scannen.new Methode();
System.out.println(methode);
//my approach which didnt worked out...
}
}
Methode is a method not a class. You don't create it with new or create it at all for that matter. A method is defined in a class and you just call it. E.g.
System.out.println(scannen.Methode());
and delete this line :
Auslesen.Scannen.Methode methode = scannen.new Methode();
Also try to stick to the Java naming convention : class names start with uppercase method and variable names with lowercase.
First of all why are you declaring a class inside another class ? If you simply want to return a value from one class to another class then you can do something like this -
String a;
private int s;
double u;
Scanner scanner = new Scanner(System.in);
public int Methode()
{
s = scanner.nextInt();
return s;
}
now in the main method just call the method -
Auslesen a=new Auslesen();
System.out.println("The entered number is: "+a.Methode());

Java, Using a String in an array in elsewhere?

I am new at coding. I was doing a project but I was stuck. My code reads a sentence from a text file. It seperates the sentence and gets the second word and records it in an array. I need to use this word in another place but I couldn't do it.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Classroom {
private String classname;
public String getClassname() {
return classname;
}
public void setClassname(String classname) {
this.classname = classname;
}
public void classroomreader(String filename) {
// This method gets the name for Classroom
File text = new File("C:/classlists/" + filename + ".txt");
Scanner scan;
try {
scan = new Scanner(text);
String line = scan.nextLine();
String classroomarray[] = line.split("\t");
// ** right now classroomarray[1] has the word which I want.**
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
}
Here is my main class:
public class ProjectMain {
public static void main(String[] args) {
// I created an array with 3 Classroom object inside it.
Classroom[] classarray = new Classroom[3];
//I hope I did this correct.
// I used classroomreader method on my first object.
classarray[0].classroomreader("class1");
// Now I need to use the word in classroomarray[1].
classarray[0].setClassname(????)
}
}
I tried: classarray[0].setClassname(classroomarray[1]); but it gave an error. How can I set the name for my first object?
i'm making just few changes in your code.. try this....definitely this'll work
class Classroom {
private String classname;
String classroomarray[]=null;//declare classroomarray[] here
public String getClassname() {
return classname;
}
public void setClassname(String classname) {
this.classname = classname;
}
public void classroomreader(String filename) {
File text = new File("C:/classlists/" + filename + ".txt");
Scanner scan;
try {
scan = new Scanner(text);
String line = scan.nextLine();
classroomarray = line.split("\t");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
}
class ProjectMain {
public static void main(String[] args) {
Classroom[] classarray = new Classroom[3];
//here you need to initialize all elements of the array
classarray[0]=new Classroom();
classarray[1]=new Classroom();
classarray[2]=new Classroom();
classarray[0].classroomreader("class1");
classarray[0].setClassname(classarray[0].classroomarray[1]);
System.out.println(classarray[0].getClassname());// here you'll surely get the the desired results
}
}
Its a little hard for me to understand what your code in the top is doing.. that being said I believe if you have a private variable in your top class and then have an accessor method like
public String getPrivateFieldValue()
{
return somePrivateFieldName;
}
Then you can can set the private variable in your main class when you find the value for it. In your main class you can then say:
Object.getPrivateFieldValue() to get that value
or in your situation:
classarray[0].setClassname(classroomreader.getPrivateFieldValue())
I think your problem lies with the concept of scope. Whenever you create a variable, like classroomarray, java registers that the name of that variable then represents the value you assign to it (in simple terms).
Now what Scope means is that not all variables can be accessed from every place. Classroomarray is created inside classroomReader(), but does not get out of that function once it completes. In a way "lives" inside that function, and that's why you can't use it in the main() method.
If you want to use classroomarray inside the main() method, you'll need to transport it there through some means. There are multiple ways of doing this:
Create a field in ClassRoom, like public String[] classroomarray
Return the classroom array you read from the file from the classroomreader() function. Returning a value means that you're "sending back" a value to whatever code called the function in the first place. For example, add(a, b) would return the sum of a and b. You do this by changing:
public void classroomreader(String filename)
To:
public String[] classroomreader(String filename)
And change:
String classroomarray[] = line.split("\t");
To:
return line.split("\t");
Then, in the main() method, you can use:
String[] classroomFile = classarray[0].classroomreader("class1");
And use the contents as you please.
This is an Example,Hope you don't mind hard interpretation. Please add return to your method like this.
public String[] demo() //Added ()
{
String[] xs = new String[] {"a","b","c","d"}; //added []
String[] ret = new String[4];
ret[0]=xs[0];
ret[1]=xs[1];
ret[2]=xs[2];
ret[3]=xs[3];
return ret;
}
So your new code will be like this
public String[] classroomreader(String filename) {
// This method gets the name for Classroom
File text = new File("C:/classlists/" + filename + ".txt");
String[] classroomarray;
Scanner scan;
try {
scan = new Scanner(text);
String line = scan.nextLine();
classroomarray = new String[] {line.split("\t")};//Change this
// ** right now classroomarray[1] has the word which I want.**
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
return classroomarray;
}
In Main method change this:
String [] strArr = demo();//Calling method which returns value clasroomarray
for ( int i = 0; i < strArr.length; i++) {
System.out.println(strArr[3]);//Printing whatever index you want
//Set Values here like this
Classroom classroom=new Classroom();//Initialize your object class
classroom.set(strArr[3]); //Set value
Hi i suggest you declare
classroomarray[]
as a member variable. Then generate getters and setters.
Later you can do what you want by setting
classarray[0].setClassname(classarray[0].getClassroomarray[1]);
I'm trying to help you on the way you want it to be done, but i don't understand why you wanna it to be done like that.
Edit : Here is the code i'm talking about in the comments below
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Classroom {
private String classname;
public String getClassname() {
return classname;
}
public void setClassname(String classname) {
this.classname = classname;
}
public void classroomreader(String filename) {
// This method gets the name for Classroom
File text = new File("C:/classlists/" + filename + ".txt");
Scanner scan;
try {
scan = new Scanner(text);
String line = scan.nextLine();
String classroomarray[] = line.split("\t");
// ** right now classroomarray[1] has the word which I want.**
this.classname = classroomarray[1];
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
}
And finally your main method should look like
public class ProjectMain {
public static void main(String[] args) {
// I created an array with 3 Classroom object inside it.
Classroom[] classarray = new Classroom[3];
classarray[0]=new Classroom();
//I hope I did this correct.
// I used classroomreader method on my first object.
classarray[0].classroomreader("class1");
// Now classname is already set
System.out.println(classarray[0].getClassname());
}
}

How do you use an array list in multiple classes? [duplicate]

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

copying array values from one class to another

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. ;)

Categories

Resources