How to serialise and de-serialise an object in Java? - java

I need to modify class PrimeFactors so that it extends HashMap<Integer,ArrayList> and implements Serializable.
Let x be a number and y be an ArrayList containing the prime factors of x: add all <x,y> pairs to PrimeFactors and serialize the object into a new file.
Then write a method that de-serializes the PrimeFactors object from the file and displays the <x,y> pairs.
Right now, I am completely stuck and unsure how to continue. Any help would be greatly appreciated as I am very unfamiliar with this situation.
Here is my code so far:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.ObjectOutputStream;
public class PrimeFactors2 extends HashMap<Integer,ArrayList<Integer>> implements Serializable {
public static void findFactor(int n) {
System.out.print("Factors for the number " + n + " is: ");
for (int i = n; i >= 1; i--) {
if (n % i == 0)
System.out.print(i + " ");
}
}
public static boolean checkForPrime(int number) {
boolean isItPrime = true;
if (number <= 1) {
isItPrime = false;
return isItPrime;
} else {
for (int i = 2; i <= number / 2; i++) {
if ((number % i) == 0) {
isItPrime = false;
break;
}
}
return isItPrime;
}
}
public static void main(String[] args) {
String path = "/Users/benharrington/Desktop/primeOrNot.csv";
String line = "";
try {
BufferedReader br = new BufferedReader(new FileReader(path));
ArrayList<Integer> list = new ArrayList<Integer>();
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
for (String str : values) {
int i = Integer.parseInt(str);
boolean isItPrime = checkForPrime(i);
if (isItPrime)
System.out.println(i + " is Prime");
else
System.out.println(i + " is not Prime");
if (isItPrime == false) {
list.add(i);
}
}
for (int k : list) {
System.out.println(" ");
findFactor(k);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

What you did in your code is simply reading a file and parsing it.
If you want to serialize and se-derialize an object, it can be done with the following code:
PrimeFactors2 primeFactors2 = // you object creation code here;
// i.e:
// PrimeFactors2 primeFactors2 = new PrimeFactors2();
// primeFactors2.setX1(2);
// primeFactors2.setX2(3);
try {
FileOutputStream fileOut = new FileOutputStream("/tmp/obj.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(primeFactors2);
out.close();
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
}
Then, in some context (same or another) in the same moment (or whenvever after you created the .ser object), you may de-serialize it with the following code:
try {
FileInputStream fileIn = new FileInputStream("/tmp/obj.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
PrimeFactors2 primeFactors2 = (PrimeFactors2) in.readObject();
// YAY!!! primeFactors2 is an object with the same values you created before
// i.e: primeFactors.getX1() is 2
// primeFactors.getX2() is 3
in.close();
fileIn.close();
} catch (Exception e) {
e.printStackTrace();
}

Related

Is there a way to get values of stocks to Java faster?

I made a simple java program that lets you create a stocks scanner/screener. There aren't many features yet, but there is a problem with existing features. I have a class that has a method that creates an array of all stock tickers and returns it. Here it is:
package classes;
import Utility.ArrayModification;
import variables.Ticker;
import java.io.*;
import java.util.Scanner;
public class Market {
public static Ticker[] getAllTickers() throws FileNotFoundException {
Ticker[] allTickers = {};
File currentDirectory = new File(new File("").getAbsolutePath());
String allTickersDirectory = currentDirectory + "\\src\\AllTickers.txt";
Scanner scanner = new Scanner(new File(allTickersDirectory));
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if(!(line.contains("^"))) {
allTickers = ArrayModification.appendTicker(allTickers, new Ticker(line));
}
}
return allTickers;
}
}
AllTickers.txt is a text file with the names of all tickers in it. I also have another class that stores a datatype, Ticker. Here it is:
package variables;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class Ticker {
private String savedSymbol;
public Ticker(String symbol) {
savedSymbol = symbol;
}
public String getTicker() {
return savedSymbol;
}
public Ticker setTicker(String symbol) {
savedSymbol = symbol;
return this;
}
public double getPrice() throws IOException {
try {
String stringURL = "https://markets.businessinsider.com/stocks/" + savedSymbol + "-stock";
URL url = new URL(stringURL);
URLConnection urlConn = url.openConnection();
InputStreamReader inStream = new InputStreamReader(urlConn.getInputStream());
BufferedReader buff = new BufferedReader(inStream);
String stringPrice = "-1";
String line = buff.readLine();
while (line != null) {
if (line.contains("price: ")) {
int target = line.indexOf("price: ");
int deci = line.indexOf(".", target);
int start = deci;
int stop = deci;
while (line.charAt(start) != ' ') {
start--;
}
while (line.charAt(stop) != ',') {
stop++;
}
stringPrice = line.substring(start + 1, stop);
break;
}
line = buff.readLine();
}
double price = Double.parseDouble(stringPrice);
return price;
}
catch(Exception e) {
return -1;
}
}
public double getMarketCap() throws IOException {
try {
String stringURL = "https://finviz.com/quote.ashx?t=" + savedSymbol;
URL url = new URL(stringURL);
URLConnection urlConn = url.openConnection();
InputStreamReader inStream = new InputStreamReader(urlConn.getInputStream());
BufferedReader buff = new BufferedReader(inStream);
String stringMarketCap = "-1";
double finalMarketCap = -1;
String line = buff.readLine();
while (line != null) {
if (line.contains(">Market Cap<")) {
int deci = line.indexOf(".");
int start = deci;
int stop = deci;
while (line.charAt(start) != '>') {
start--;
}
while (line.charAt(stop) != '<') {
stop++;
}
stringMarketCap = line.substring(start + 1, stop - 1);
double marketCap = Double.parseDouble(stringMarketCap);
if (line.charAt(stop - 1) == 'B') {
finalMarketCap = marketCap * 1000000000;
} else if (line.charAt(stop - 1) == 'M') {
finalMarketCap = marketCap * 1000000;
}
break;
}
line = buff.readLine();
}
return finalMarketCap;
}
catch(Exception e) {
return -1;
}
}
}
Using all of these, you can create a simple scanner that scans for stocks with a price of, for example, 0 - 15. You can do this by doing this:
import classes.Market;
import variables.Ticker;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
Ticker[] allTickers = Market.getAllTickers();
for(int i = 0; i< allTickers.length; i++){
Ticker ticker = allTickers[i];
if(ticker.getPrice() > 0 && ticker.getPrice() < 15) {
System.out.println(ticker.getTicker());
}
}
}
}
It prints out all of the qualifying stocks. However, it is EXTREMELY slow. So slow that it's basically unusable. It is this way because the ticker.getPrice() method has to connect to markets.businessinsider.com, extract the HTML code, find the correct index, and get the price for every single stock out of the 6000 in AllTIckers.txt. Would there be a way to do this faster?

Split with new line and store in datastructure

I have text file data like :
2,2,1
data1,123,89,1
data2,124,90,2
data3,125,91,3
data4,126,92,4
data5,127,93,5
data6,128,94,6
data7,129,95,7
data8,130,96,8
data9,131,97,9
data10,132,98,10
The first line 2,2,1 indicate 2 lines from 1st set of lines and store it in nodeFile, 2 lines from 2nd set of lines store it in linkFile and 1 line from 3rd set of lines store it in moduleFile. However for example purpose I have shows small number of lines but its a larger file.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ReadFile {
static List<String> moduleFile = new ArrayList<>();
static List<String> linkFile = new ArrayList<>();
static List<String> nodeFile = new ArrayList<>();
static int a[];
public static void main(String[] args) {
File file11 = new File("/home/madhu/Desktop/node.txt");
Scanner scAll = null;
try {
scAll = new Scanner(file11);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String[] numberOfLines = (scAll.nextLine()).split(",");
int flag = 0;
int counter = 1;
while (scAll.hasNext()) {
if (flag == 0 && "\\n\\n".equals(scAll.nextLine()) && counter <= Integer.parseInt(numberOfLines[0].trim())) {
for (int i = 0; i < Integer.parseInt(numberOfLines[0].trim()); i++) {
System.out.println(scAll.nextLine());
nodeFile.add(scAll.nextLine());
counter++;
}
if (counter > Integer.parseInt(numberOfLines[0].trim())) {
flag = 1;
counter = 1;
}
} else if (flag == 1 && "\\n\\n".equals(scAll.nextLine())
&& counter <= Integer.parseInt(numberOfLines[1].trim())) {
for (int i = 0; i < Integer.parseInt(numberOfLines[1].trim()); i++) {
System.out.println(scAll.nextLine());
linkFile.add(scAll.nextLine());
counter++;
}
if (counter > Integer.parseInt(numberOfLines[1].trim())) {
flag = 2;
counter = 1;
}
} else if (flag == 2 && "\\n\\n".equals(scAll.nextLine())
&& counter <= Integer.parseInt(numberOfLines[2].trim())) {
for (int i = 0; i < Integer.parseInt(numberOfLines[2].trim()); i++) {
System.out.println(scAll.nextLine());
moduleFile.add(scAll.nextLine());
counter++;
}
} else {
continue;
}
}
scAll.close();
}
}
I have written the above code, but this code gets terminated during execution. How to get the desired result? Please help.
Hopefully I am not misunderstanding, but this is what I'd do.
I didn't check to see if this is fully working example, but it should work more or less.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
class ReadFile {
// basically just do what you did
static List<String> nodeFile;
static List<String> linkFile;
static List<String> moduleFile;
public static void main(String[] args) throws FileNotFoundException {
final File file = new File("/home/madhu/Desktop/node.txt");
final Scanner scanner = new Scanner(file);
// make it a little better for indexing
final List<Integer> selections = Arrays
.stream(scanner.nextLine().split(","))
.map(Integer::parseInt)
.collect(Collectors.toList());
// this is the meat of the code
// basically each split up block of lines is a block
final List<List<String>> blocks = new ArrayList<>();
while (scanner.hasNextLine()) {
List<String> lines = new ArrayList<>();
String line;
while (!(line = scanner.nextLine()).equals("\n")) {
lines.add(line);
}
if (!lines.isEmpty()) {
blocks.add(lines);
}
}
// allocate your files now
nodeFile = blocks.get(0).subList(0, selections.get(0));
linkFile = blocks.get(1).subList(0, selections.get(1));
moduleFile = blocks.get(2).subList(0, selections.get(2));
scanner.close();
}
}
try this code , i use BufferedReader because its more cleaner :
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ReadFile {
static List<String> moduleFile = new ArrayList<>();
static List<String> linkFile = new ArrayList<>();
static List<String> nodeFile = new ArrayList<>();
public static void main(String[] args) {
File file = new File("/home/madhu/Desktop/node.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String data[] = reader.readLine().split(",");
String s;
int nbline=0, i=0,block =0;
while ((s = reader.readLine())!=null && block < data.length) {
if(s.equals("")){
block++;
nbline = Integer.parseInt(data[block-1]);
i = 0;
}
for(;i<nbline;i++){
s = reader.readLine();
if(s == null) break;
else if(s.equals("")){
block++;
break;
}
switch(block){
case 1 :
nodeFile.add(s);
break;
case 2:
linkFile.add(s);
break;
default: moduleFile.add(s);
}
}
}
} catch (IOException | NumberFormatException ex) {
System.err.println(ex.getStackTrace());
}
finally{
closeReader(reader);
}
System.out.println("nodeFile : "+nodeFile);
System.out.println("linkFile : "+linkFile);
System.out.println("moduleFile : "+moduleFile);
}
public static void closeReader(BufferedReader reader) {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
}
output :
nodeFile : [data1,123,89,1, data2,124,90,2]
linkFile : [data5,127,93,5, data6,128,94,6]
moduleFile : [data8,130,96,8]

How to Access variable from another class in same package in java

I want to access the class Totalnoofwords in class newrepeatedcount.
I want to print "a" of class Totalnoofwords megring with
System.out.println("( "+file1.getName() +" )-" +"Total words counted:"+total);
in class newrepeatedcount.
So I could run both the code for getting System.out.println("( "+file1.getName() +" )-" +" Total no of words=" + a +"Total repeated words counted:"+total);
Here is the snippet of 1 output which I wanted
( filenameBlog 39.txt )-Total no of words=83,total repeated words counted:4
Any suggestions Welcomed.
I am a beginner to java.
Here is my two class codes below.:)
Totalnoofwords.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import org.apache.commons.io.FileUtils;
public class Totalnoofwords
{
public static void main(String[] args)
{
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".txt");
}
};
File folder = new File("E:\\testfolder");
File[] listOfFiles = folder.listFiles(filter);
for (int i = 0; i < listOfFiles.length; i++) {
File file1 = listOfFiles[i];
try {
String content = FileUtils.readFileToString(file1);
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader ins = null;
try {
ins = new BufferedReader (
new InputStreamReader(
new FileInputStream(file1)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String line = "", str = "";
int a = 0;
int b = 0;
try {
while ((line = ins.readLine()) != null) {
str += line + " ";
b++;
}
} catch (IOException e) {
e.printStackTrace();
}
StringTokenizer st = new StringTokenizer(str);
while (st.hasMoreTokens()) {
String s = st.nextToken();
a++;
}
System.out.println(" Total no of words=" + a );
}
}
}
newrepeatedcount.java
package ramki;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
public class newrepeatedcount {
public static void main(String[] args){
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".txt");
}
};
File folder = new File("E:\\testfolder\\");
File[] listOfFiles = folder.listFiles(filter);
for (int i = 0; i < listOfFiles.length; i++) {
File file1 = listOfFiles[i];
try {
String content = FileUtils.readFileToString(file1);
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader ins = null;
try {
ins = new BufferedReader ( new InputStreamReader(new FileInputStream(file1)));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String st = null;
try {
st = IOUtils.toString(ins);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//split text to array of words
String[] words=st.split("\\s");
//frequency array
int[] fr=new int[words.length];
//init frequency array
for(int i1=0;i1<fr.length;i1++)
fr[i1]=-1;
//count words frequency
for(int i1=0;i1<words.length;i1++){
for(int j=0;j<words.length;j++){
if(words[i1].equals(words[j]))
{
fr[i1]++;
}
}
}
//clean duplicates
for(int i1=0;i1<words.length;i1++){
for(int j=0;j<words.length;j++){
if(words[i1].equals(words[j]))
{
if(i1!=j) words[i1]="";
}
}
}
//show the output
int total=0;
//System.out.println("Duplicate words:");
for(int i1=0;i1<words.length;i1++){
if(words[i1]!=""){
//System.out.println(words[i1]+"="+fr[i1]);
total+=fr[i1];
}
}
//System.out.println("Total words counted: "+total);
//System.out.println("Total no of repeated words : "+total+" ");
System.out.println("( "+file1.getName() +" )-" +"Total repeated words counted:"+total);
}
}}
I tried to put both the code into a single class
but neither one of the variable is working
System.out.println("( "+file1.getName() +" )-" +" Total no of words=" + a +"Total repeated words counted:"+total);
When I run neither "a" or "total" is working.(vice versa) If i change the code (variable)order.
Anyone tell how should I get both the variable output??
:)
Here is my updated code.below.
package ramki;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
public class newrepeatedcount {
public static void main(String[] args){
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".txt");
}
};
File folder = new File("E:\\testfolder\\");
File[] listOfFiles = folder.listFiles(filter);
for (int i = 0; i < listOfFiles.length; i++) {
File file1 = listOfFiles[i];
try {
String content = FileUtils.readFileToString(file1);
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader ins = null;
try {
ins = new BufferedReader ( new InputStreamReader(new FileInputStream(file1)));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String line = "", str = "";
String st = null;
try {
st = IOUtils.toString(ins);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//split text to array of words
String[] words=st.split("\\s");
//frequency array
int[] fr=new int[words.length];
//init frequency array
for(int i1=0;i1<fr.length;i1++)
fr[i1]=-1;
//count words frequency
for(int i1=0;i1<words.length;i1++){
for(int j=0;j<words.length;j++){
if(words[i1].equals(words[j]))
{
fr[i1]++;
}
}
}
//clean duplicates
for(int i1=0;i1<words.length;i1++){
for(int j=0;j<words.length;j++){
if(words[i1].equals(words[j]))
{
if(i1!=j) words[i1]="";
}
}
}
int a = 0;
try {
while ((line = ins.readLine()) != null) {
str += line + " ";
}
} catch (IOException e) {
e.printStackTrace();
}
StringTokenizer st1 = new StringTokenizer(str);
while (st1.hasMoreTokens()) {
String s = st1.nextToken();
a++;
}
int total=0;
for(int i1=0;i1<words.length;i1++){
if(words[i1]!=""){
//System.out.println(words[i1]+"="+fr[i1]);
total+=fr[i1];
}
}
System.out.println("( "+file1.getName() +" )-" +"Total repeated words counted:"+total+","+"total no of words:"+a);
// System.out.println("total no of words:"+a);
}
}}
package Packagename;
public class newrepeatedcount {
public static void main(String[] args){
Totalnoofwords B=new Totalnoofwords();
B.somename();
System.out.println("a:"+B.a);
}
}
The variables inside the main function cannot be accessed from other class.
So you can modify Totalnoofwords.java something like.
package Packagename;
public class Totalnoofwords
{
static int a = 1;
public void somename(){
Totalnoofwords A=new Totalnoofwords();
A.a+=5;
System.out.println("a"+A.a);
}
}
and your newrepeatedcount.java be like
package Packagename;
public class newrepeatedcount {
public static void main(String[] args){
Totalnoofwords B=new Totalnoofwords();
B.somename();
System.out.println("a:"+B.a);
}
}
It looks like you have 2 main methods in the same package, I'm not sure if you wanted it this way or not, but this won't work because your not overloading the methods. For instance currently you have public static void main(String[] args) in one class, If you change the other class to accept an extra argument public static void main(String[] args1, String[]args2).
Also in order to access your second class, as stated above you would use something like
Totalnoofwords totalNoofWords = new Totalnoofwords();
totalNoofWords.accessSomething();
But this won't work, because you don't have a constructor.

read from csv file in java

I have a huge CSV file.I have to read it and store in a database using java.below code only read about 2000 rows from that file and store it into database.why? note the below calculation is to change the seconds to minutes with approximation.dont think a lot about that
import com.opencsv.CSVReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class ReadCSV {
public static void main(String[] args) throws SQLException{
MainController mc = new MainController();
boolean status=false;
String csvFile = "C:/Users/Thanushiya/Desktop/mobios/internship/csvfile/csvfile/Master.csv";
CSVReader reader = null;
List myList = new ArrayList();
String[] row = null;
int duration_m = 0;
try {
reader = new CSVReader (new FileReader(csvFile), ',', '\'', 17);
myList = reader.readAll();
int i=0;
for (Object object : myList) {
row = (String[]) object;
float duration_float = Float.parseFloat(row[12]) / 60 ;
float duration_mod = duration_float % 1 ;
if(Integer.parseInt(row[12]) <= 60){
duration_m = 1;
}
else{
if(duration_mod == 0 ){
duration_m = (int) duration_float;
}
else{
duration_m = ((int) duration_float) + 1;
}
}
String query = "INSERT INTO master(msisdn,serv,start,end,ringwithdurartion,duration_s,status,cid,duration_m) values ('"+row[0]+"','"+row[4]+"','"+row[8]+"','"+row[10]+"','"+row[11]+"','"+row[12]+"','"+row[13]+"','"+row[15]+"','"+duration_m+"')";
status=mc.insertData(query);
}//end for
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
}
}
With readAll() you're loading (or at least trying to load) the entire file into memory at once. That will severely limit the number of lines you can read before running out of memory. As indicated on the OpenCSV homepage, there's also an iterator that reads line per line:
CSVReader reader = new CSVReader(new FileReader("C:/Users/Thanushiya/Desktop/mobios/internship/csvfile/csvfile/Master.csv"), ',', '\'', 17);
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
// put the code from your for loop here
}

The method importTeams() is undefined for the type SchedulerOutput

I'm creating a scheduler in Java. I had everything inside in one class, but now I want to split it up into separate classes. It's quite small program, so there's likely little benefit, but I want to get the concepts of it correct. Code is below.
I'm getting an error in the second class on the importTeams() method. I thought that as long as I imported the package this method was in, it would be ok. Obviously not. Any tips?
package fifa.scheduler.fileimport;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import fifa.scheduler.output.*;
public class FileRead2 {
private String rrTeam;
public List<String> importTeams() {
ArrayList<String> teamList = new ArrayList<String>();
BufferedReader br = null;
int linecount = 0;
String teamcounter;
try {
br = new BufferedReader(new FileReader("path"));
while (br.readLine() != null){
linecount ++;
}
br.close();
br = new BufferedReader(new FileReader("path"));
setRrTeam(br.readLine());
while ((teamcounter = br.readLine()) != null) {
teamList.add(teamcounter);
}
if (linecount % 2 != 0) {
teamList.add("byeteam");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return teamList;
}
public static void main(String args[]){
FileRead2 fr = new FileRead2();
fr.PrintTeams();
}
private void setRrTeam(String rrTeam) {
this.rrTeam = rrTeam;
}
private String getRrTeam() {
return rrTeam;
}
}
package fifa.scheduler.output;
import java.util.Collections;
import java.util.List;
import fifa.scheduler.fileimport.FileRead2;
public class SchedulerOutput {
public void PrintTeams(){
List<String> teamList = importTeams();
int tl = teamList.size();
int bh = 0;
int uh = (tl - 2);
for (int i = 0; i <=(teamList.size()-1); i++) {
System.out.println("Week " + (i+1) + " fixtures");
System.out.println(getRrTeam() + " vs " + teamList.get(tl -1));
while ((bh <= (tl / 2)) && (uh >= ((tl / 2)))) {
System.out.println(teamList.get(bh) + " vs " + teamList.get(uh));
bh++;
uh--;
}
Collections.rotate(teamList, 1);
tl = teamList.size();
bh = 0;
uh = (tl - 2);
}
}
}
When you import the class using import statement, only the class's interface is imported. In order to call member methods, you need an instance of the class.
In your case, you should create an object of type FileRead2 to call the importTeams() method on it.
// Since FileRead2 has some member variable, you should also think about
// initializing it appropriately if it is needed by importTeams method.
FileRead2 fileRead2Obj = new FileRead2();
fileRead2Obj.importTeams();
Similarly, to call static methods, you need to qualify the method name with the class name (though Java 5+ allows static import of methods as well).
If importTeams() was static method, then you should call it as follows, after importing the class:
FileRead2.importTeams();

Categories

Resources