I am learning about java inheritance and i am a bit confused, if i write a program that handles 3 files:
1) cheese.txt
2) fruits.txt
3) drinks.txt
If i have a parent class called Food that handles fruits.txt
and a class Cheese that handles cheese.txt that extends Foods
and a class Drinks that handles drinks.txt that extends Foods
so it looks like this
class Foods {
// code
}
class Cheese extends Foods {
// code
}
class Drinks extends Foods {
// code
}
public static void main(String[] args) {
Foods one = new Foods("fruits.txt"); // call to constructors
Cheese two = new Cheese("cheeses.txt"); // call to constructors
Drinks three = new Drinks("drinks.txt"); // call to constructors
}
How ever upon running this code it seems like the last class (Drinks) overlaps all the other classes. If i comment out the object three it works properly. How can i use all 3 classes in the main method at one time?
First of all, like others suggested you to do, you should show us the class with all the code in it so it would be easier for us to help you.
Second of all, you need to check all those things :
(good source of "documentation" is https://www.w3schools.com/java/java_files_read.asp)
1- Check if you have all your imports right :
import java.io.File; // Import the File class
import java.util.Scanner; // Import the Scanner class to read text files
2- Check if you code is something similar to that :
File myObj = new File("filename.txt"); // allows you to "bind" the file and use it for manipulations
Scanner myReader = new Scanner(myObj); // allows you to do manipulations on your determined file
while (myReader.hasNextLine()) { // make sure that as long as there is another line that the reader has not read, it continues to read the file
String data = myReader.nextLine(); // where the read line is stored
System.out.println(data); // print the determined line
If you could show us both the super-class and the inheriting classes, it would
Related
I am working on a homework assignment that takes input from a .csv file and will prompt the user for different questions pertaining to the information contained within (crime statistics).
My code is as follows and it's still really early so I just have some placeholder variables in there as I have been wracking my head trying to figure out the best approach to this problem.
import java.io.*;
public class USCrimeArray {
String crimeArray[][] = new String[21][20];
public void createCrimeArray() throws Exception{
String crimeArrayInputString;
int crimeArrayRowValue = -1;
try (BufferedReader crimeArrayInput = new BufferedReader(new FileReader("C:/Users/Joey/Documents/Crime.csv"))) {
while ((crimeArrayInputString = crimeArrayInput.readLine()) != null) {
crimeArrayRowValue++;
crimeArray[crimeArrayRowValue] = crimeArrayInputString.split(",");
}
} catch (IOException io) {
io.getMessage();
}
}
public USCrimeArray(){
String[][] thisArray = crimeArray.clone();
}
public String[][] getCrimeArray(){
return crimeArray.clone();
}
}
This is the code for my first class and if I do a deepToString inside of createCrimeArray I get the information back that I want. The constructor for USCrimeArray hasn't really been thought out yet my main question is how to write the information to the crimeArray[][] so that I can carry it back over to other classes.
Once again this test main hasn't been thought out too far because I am still struggling with why my method is not writing over the crimeArray[][] with the while loop and it is as follows:
import java.util.Arrays;
public class USCrimeClass {
public static void main(String[] args) {
USCrimeArray crimeArray = new USCrimeArray();
String[][] test = crimeArray.getCrimeArray();
System.out.println(Arrays.deepToString(test));
}
}
I know there's a lot I'm doing wrong here, but this is the end result so far after having altered everything over and over again and not making any progress. The result of the system out in this is obviously just a 21x20 array of null elements. Any help would be greatly appreciated.
You need to call createCrimeArray() in USCrimeClass
public class USCrimeClass {
public static void main(String[] args) {
USCrimeArray crimeArray = new USCrimeArray();
crimeArray.createCrimeArray();
String[][] test = crimeArray.getCrimeArray();
System.out.println(Arrays.deepToString(test));
}
}
Also,
in the constructor of USCrimeArray you are clonning the array into a local variable thisArray but never use it. this is redundant and can be safely removed.
in getCrimeArray() you are returning a clone of the array. this is not needed (unless you want to keep USCrimeArray immutable). you can just return the array itself
Instance variables
instance variables are non static class level variables (much like crimeArray).
One can consider instance variables as serving two purposes:
"details" of the problem domain of the class. For example Person class will have instance variables such as firstName and lastName that are details of one person.
"configuration" variables holding information related to the technological environment and not pertaining to the problem domain of the class. For example, one sometimes might find a class with a boolean deleted instance variable that signifies a "soft deleted" instance that is not to be presented to the user or included in calculations. the purpose behind this is to support undo of deletion.
so crimeArray is of category details of USCrimeArray. common best practice is to initialise instance variables in the class constructor, so by the time you finish creating a new instance, you have one that has full and valid details. So I would move all of the code of createCrimeArray() into the constructor.
If you need to modify an instance variable after it was initialised, then a "setter" method can be used. these have a standardized signature: public void setCrimeArray(crimeArray[][]). having a standardized signature allows your class to be used by frameworks and libraries that add functionality. For example, storing the data in a relational database, sending/recieving the data over the internet, etc.
Now, I see that the external input that is used to populate the array comes from a file. The way it is coded now, USCrimeArray can only read one specific file from predetermined file syatem location. a more flexible way would be for the class to receive the specification for external input as an argument:
public USCrimeArray(String filename) {
...
try (BufferedReader crimeArrayInput = new BufferedReader(new FileReader(filename))) {
...
}
now the same class can be used to process an array from different files.
now you can even make the file name an argument of the java program:
public class USCrimeClass {
public static void main(String[] args) {
USCrimeArray crimeArray = new USCrimeArray(arg[0]);
System.out.println(Arrays.deepToString(test));
}
}
now the same java program can process different files without need for recompile.
I am trying to test a single instance using weka API in Java. My aim is to predict the class value of the single instance in the test.arff file.
My java code looks like this,
import weka.core.Instances;
import weka.classifiers.Evaluation;
import weka.classifiers.trees.J48;
import weka.classifiers.*;
import java.io.*;
import java.util.Random;
public class WekaNew {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
System.out.println("Weka Tool");
BufferedReader breader = new BufferedReader(new FileReader("train.arff"));
Instances train = new Instances(breader);
train.setClassIndex(train.numAttributes() -1);
breader.close(); //loading training data
BufferedReader treader = new BufferedReader(new FileReader("test.arff"));
Instances test = new Instances(treader);
test.setClassIndex(test.numAttributes() -1);
treader.close(); //loading testing data
Classifier cls = new J48();
cls.buildClassifier(train);
Evaluation eval = new Evaluation(train);
eval.evaluateModelOnce(cls,test);
System.out.println(eval.toMatrixString("\nConfusion Matrix\n========\n"));
}
}
The train.arff has 7(attributes)+1(class label) along with 132 instances of data.
The test.arff has 7 attributes + 1 class label=? with ONE instance.
I want to predict the class label of the single instance in the test.arff.
How do I go about predicting the label and what changes are needed to be made in the dataset and the code?
I tried compiling the java file by "javac -cp "/classpath" WekaNew.java"
, it gives the following error "No suitable method found for evaluateModelOnce()"
New to the Weka API and Java in general. Apologies in advance if the question seems repeated.
I have also referred the following questions in Stackoverflow,
1. Test single instance in weka which has no class label
2. Test a single instance in Weka
but it does not seem to solve my problem.
This is the signature of evaluateModelOnce:
public double evaluateModelOnce(Classifier classifier,
Instance instance)
(see http://weka.sourceforge.net/doc.stable/weka/classifiers/Evaluation.html#evaluateModelOnce-weka.classifiers.Classifier-weka.core.Instance-)
However, you pass in "Instances" instead of "Instance", which are different classes. Thus, this is a syntax error.
To evaluate a single Weka Instance, you might want to try
eval.evaluateModelOnce(cls,instances.firstInstance());
I'm not looking for a complete answers just help on how to start it or maybe some references I could look at that may help me with this. Ok so I have to populate the JComboBox (accountnumber) from a text file. The txt files reads as:
1231<>Jack Williams<>2015/1/21<>463.02
1232<>Jane Brown<>2015/1/21<>13510.54
1233<>Paul Gonzales<>2015/1/22<>680.17
1234<>Jian Chen<>2015/1/22<>1117.54
1235<>Lily Makki<>2015/1/22<>1124.89
1236<>Michael Lopez<>2015/1/23<>800.0
1237<>Jose Alvarez<>2015/1/23<>607.21
1238<>Tina Lin<>2015/1/24<>11077.0
It reads as acctNumber<>CustomerName<>openDate<>balance
How would I go about starting this? Which would be easiest to split the 4 variables. array/arraylist/hashmap etc.?
I'm not familiar with file I/O. and trouble with collections so this is the only part I'm stuck on.
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class AccountUtility {
List<String> accountsInfo = new ArrayList<>();
BufferedReader in;
File file = new File("accounts.txt");
public AccountUtility(){
ReadFile();
}
public void ReadFile(){
String nxtLine = " ";
try{
in = new BufferedReader(new FileReader(file));
while(nxtLine != null){
nxtLine = in.readLine();
accountsInfo.add(nxtLine);
}
for(String items : accountsInfo)
System.out.println(items);
in.close();
}catch(IOException ex){
}
}
public static void main(String[] args) {
AccountUtility ut = new AccountUtility();
}
}
so i decided to use a list , this is just my accountutility class I just added a mainmethod so i can test just this class and the result when i Run it comes to
1231<>Jack Williams<>2015/1/21<>463.02
1232<>Jane Brown<>2015/1/21<>13510.54
1233<>Paul Gonzales<>2015/1/22<>680.17
1234<>Jian Chen<>2015/1/22<>1117.54
1235<>Lily Makki<>2015/1/22<>1124.89
1236<>Michael Lopez<>2015/1/23<>800.0
1237<>Jose Alvarez<>2015/1/23<>607.21
1238<>Tina Lin<>2015/1/24<>11077.0
null
How do i split an list using a delimiter?
You're primary identifier is the account number, from this you need to be able to ascertain the account details.
This would lead me to use some kind of Map.
I would then create an Account class which held all the information in a simple, easy to use class, which provided appropriate setters and getters.
This would then lean me to the fact that I wouldn't actually need the Map, because all the information I need was in the Account class, so instead, I would simply create a ListCellRenderer for the combo box that would be capable of taking the account number from an instance of the Account class and display it appropriately...
This would mean I'd only need a List or a ComboBoxModel to hold the account details
Take a closer look at How to Use Combo Boxes for more details
To display an Object, Swing components will use the toString() method the Object placed in it.
One approach is to create a Data class that holds the name, ID, etc., implement toString() to display what you want (in your case, the Account Number), and then put a list of these objects in your JComboBox.
Then on change of selection in the combo, get the selected item, cast it to the data class, and then call getDate(), getName(), etc. to populate the textfields.
If you want to actually show the extra details of the Customer in the combo (after all, who really knows the person by account number?), then take a look at one approach here:
DetailedComboBox
Justin, I'm in the same boat and created a similar program that reads from text file. There was an excellent given for cells (e.g. Excel or Sql), but need to have it read from a text file. I'm thinking:
String tmp [] = line.split ("<>");
this will output data from each break.
I have a CSV file which has only one column with 100+ rows. I would like to put those values in an one dimensional array(only if its possible). So that it works as same as if I wrote a string array manually. I.e.
String[] username = {'lalala', 'tatata', 'mamama'}; //<---if I did it manually
String[] username = {after passing the CSV values}; //<---I want this like the above ones.
Then later I would like to be able to initialized that class to a different class, say if the class that holds the array is called ArrayClass, I would like to be able to initialized this to different class, like this --
public class MainClass{
ArrayClass array = new ArrayClass();
//Then I would like to be able to do this
someMethod(array.username);
}
I know I asked a lot of things but I seriously appreciate all your help. Even if you see this question and say THIS IS BS. Oh and one more thing I would prefer it to be in JAVA.
It might be easier to use an arraylist rather than an array as you dont have to worry about number of rows. An array has a fixed size that cant be changed. i.e ArrayList
As you have only one column you will not need to worry about commas in csv
Example code would look something like this:
import java.util.*;
import java.io.*;
public class MyClass {
private ArrayList<String> MyArray = new ArrayList<String>();
private Scanner scan;
public MyClass(){
try {
scan = new Scanner(new File("MyFile.csv"));
} catch (IOException ioex) {
System.out.println("File Not Found");
}
}
public ArrayList<String> getArray() {
while (scan.hasNext()) {
Scanner line = new Scanner(scan.nextLine());
MyArray.add(line.next());
}
return MyArray;
}
}
And in the main:
MyClass f = new MyClass();
System.out.println(f.getArray());
If it's just a csv you can use the split method of string with a proper regex.
Please do check the split method
The first half of your question is easy and can be handled in a number of different ways. Personally, I would use the Scanner class and set the delimiter to be ",". Create a new Scanner Object and then call setDelimiter(",") on it. Then simply scan through the tokens. See the example on the documentation. This method of doing things is effective because it handles reading in the file and separating it based on your criteria (the ',' character).
Okay I'll try to be direct.
I am working on a file sharing application that is based on a common Client/Serer architecture. I also have HandleClient class but that is not particularly important here.
What I wanna do is to allow users to search for a particular file that can be stored in shared folders of other users. For example, 3 users are connected with server and they all have their respective shared folders. One of them wants to do a search for a file named "Madonna" and the application should list all files containing that name and next to that file name there should be an information about user(s) that have/has a wanted file. That information can be either username or IPAddress. Here is the User class, the way it needs to be written (that's how my superiors wanted it):
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class User {
public static String username;
public static String ipAddress;
public User(String username, String ipAddress) {
username = username.toLowerCase();
System.out.println(username + " " + ipAddress);
}
public static void fileList() {
Scanner userTyping = new Scanner(System.in);
String fileLocation = userTyping.nextLine();
File folder = new File(fileLocation);
File[] files = folder.listFiles();
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < files.length; i++) {
list.add(i, files[i].toString().substring(fileLocation.length()));
System.out.println(list.get(i));
}
}
public static void main(String args[]) {
System.out.println("Insert the URL of your shared folder");
User.fileList();
}
}
This class stores attributes of a particular user (username, IPAddress) and also creates the list of files from the shared folder of that particular user. the list type is ArrayList, that's how it has to be, again, my superiors told me to.
On the other hand I need another class that is called RequestForFile(String fileName) whose purpose is to look for a certain file within ArrayLists of files from all users that are logged in at the moment of search.
This is how it should look, and this is where I especially need your help cause I get an error and I can't complete the class.
import java.util.ArrayList;
public class RequestForFile {
public RequestForFile(String fileName) {
User user = new User("Slavisha", "84.82.0.1");
ArrayList<User> listOfUsers = new ArrayList();
listOfUsers.add(user);
for (User someUser : listOfUsers) {
for (String request : User.fileList()) {
if (request.equals(fileName))
System.out.println(someUser + "has that file");
}
}
}
}
The idea is for user to look among the lists of other users and return the user(s) with a location of a wanted file.
GUI aside for now, I will get to it when I fix this problem.
Any help appreciated.
Thanks
I'm here to answer anything regarding this matter.
There are lots of problems here such as:
I don't think that this code can compile:
for (String request : User.fileList())
Because fileList() does not return anything. Then there's the question of why fileList() is static. That means that all User objects are sharing the same list. I guess that you have this becuase you are trying to test your user object from main().
I think instead you should have coded:
myUser = new User(...);
myUser.fileList()
and so fileList could not be static.
You have now explained your overall problem more clearly, but that reveals some deeper problems.
Let's start at the very top. Your request object: I think it represents one request for one user with one file definition. But it needs to go looking in the folders of many users. You add the the requesting user to a list, but what about the others. I think that this means that you need another class responsible for holding all the users.
Anyway lets have a class called UserManager.
UserMananger{
ArrayList<User> allTheUsers;
public UserManager() {
}
// methods here for adding and removing users from the list
// plus a method for doing the search
public ArrayList<FileDefinitions> findFile(request) [
// build the result
}
}
in the "line 14: for (String request : User.fileList()) {" I get this error: "void type not allowed here" and also "foreach not applicable to expression type"
You need to let User.fileList() return a List<String> and not void.
Thus, replace
public static void fileList() {
// ...
}
by
public static List<String> fileList() {
// ...
return list;
}
To learn more about basic Java programming, I can strongly recommend the Sun tutorials available in Trials Covering the Basics chapter here.
It looks like you're getting that error because the fileList() method needs to returns something that can be iterated through - which does not include void, which is what that method returns. As written, fileList is returning information to the console, which is great for your own debugging purposes, but it means that other methods can't get any of the information fileList sends to the console.
On a broader note, why is RequestForFile a separate class? If it just contains one method, you can just write it as a static method, or as a method in the class that's going to call it. Also, how will it get lists of other users? It looks like there's no way to do so as is, as you've hard-coded one user.
And looking at the answers, I'd strongly second djna's suggestion of having some class that acts as the controller/observer of all the Users.