Rewriting .txt to array by scanner - java

class Materials implements Runnable {
String path;
public Materials(String path) {
this.path = path;
}
public int checkSize() throws FileNotFoundException {
Scanner sc = new Scanner(new File(path));
int size = 0;
while(sc.hasNextLine()) size++;
sc.close();
return size;
}
public void run() {
try {
Scanner sc = new Scanner (new File(path));
int[][] materialsTab = new int[1][checkSize()];
int x=0, count=0;
while(sc.hasNext()){
count++;
materialsTab[x][0] = sc.nextInt();
materialsTab[x][1] = sc.nextInt();
x++;
System.out.println("Im working!");
if(count%200 == 0) System.out.println("Creat " + count + " objects");
}
sc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
My problem is that I have to rewrite .txt file into an array by thread, then comes the next thread, but I got stuck at the first part of the task.
public int checkSize () is responsible for counting the size of the array, because the text file consists of about 10 000 lines. The whole will look exactly like this:
[Product ID] [Weight]
So I decided to count the number of lines and create just such a table, one place where I keep ID, and next to the weight, because later I will have to count a few things.
In addition, every 200 records must appear in the message. The problem is that after starting this part... nothing happens.

Instead of
int[][] materialsTab ...
consider using something roughly like:
List<Point> materialsTab = new ArrayList<Point>();
Point mat = new Point();
mat.x = sc.nextInt();
if (!sc.hasNext())
break;
mat.y = sc.nextInt();
materialsTab.add(mat);

If I'm understanding your problem correctly, try changing Runnable to Callable<int[]> and public void run() to public int[] call() and adding return materialsTab; at the end.

Related

use a method to read numbers from a text file and return the prime numbers

the question says: Create a class named HW09. In this class implement a method named primeCounter
with the following signature, that takes a file name as string (for example “numbers.txt”) and returns the number of prime numbers in the text file. Assume the text file only contains integer numbers.
I tried to build the code for the program But I keep getting these error messages and I'm not sure how to fix them and get the program running again. My knowledge of the file access concept is very weak and my professor is horrible. I hope someone can help me understand what went wrong
import java.io.*;
import java.util.Scanner;
class HW09 {
public static int primeCounter(String fileName) throws IOException {
int count= 0;
int number;
String x= null;
File filename= new File("C:/Users/black/Desktop/file.txt");
Scanner s = new Scanner(filename);
BufferedReader data= null;
data= new BufferedReader (new FileReader(filename));
while (s.hasNextInt()) {
number= Integer.parseInt(x);
int see=0;
for (int i =1; i<=number; i++) {
if (number%i==0) {
see = see+1;
}
if (see>2) {
break;
}
}
if (see==2) {
count = count+1;
}
}
return count;
}
public static void main (String args []) {
try {
String file= ("C:/Users/black/Desktop/file.txt");
System.out.println(HW09.primeCounter(file));
}
catch (IOException e) {
System.out.println("Couldn't find file! ");
}
}
}
I see a number of issues with your current code, first and foremost is the lack of separation of concerns. I would start with a simple method to determine if a single number is prime. I wrote such a method here, and that looks like
private static boolean isPrime(int n) {
if (n == 2) {
return true;
} else if (n == 1 || n % 2 == 0) {
return false;
}
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0) {
return false;
}
}
return true;
}
Then you want to read numbers with your Scanner. And check if they are prime. And don't forget to close the Scanner when you're done. Using a try-with-resources takes care of that. Like,
public static int primeCounter(String fileName) throws IOException {
int count = 0;
try (Scanner s = new Scanner(new File(fileName))) {
while (s.hasNextInt()) {
int v = s.nextInt();
if (isPrime(v)) {
count++;
}
}
}
return count;
}
Finally, when constructing a path, it's better to use the system properties to get the home folder. That way, it can work on other people's machines more easily,
public static void main(String args[]) {
try {
String file = new File(
System.getProperty("user.home"), "Desktop/file.txt").getPath();
System.out.println(primeCounter(file));
} catch (IOException e) {
System.out.println("Couldn't find file! ");
}
}
And I created a file to test against,
$ cat ~/Desktop/file.txt
13
11
7
5
3
2
4
After running the program I get, as expected,
6

java - read file and create array

I have to follow a specific format and use scanner. I know there are better methods, but this is a requirement and I am new to java and trying to figure this out. There is a file with customer name, birth date, and other information. I need to count the number of entries in the file, then the file needs to create an array based on the number of file entries and convert the array to a string array. There is more code I need to do, but I am stuck on this part. The try/catch has to be used.
public class Customers {
//////// MAIN ////////
public static void main(String[] args) {
File file = new File("customers.txt");
int numEntries = countCustomers(file);
Person[] customers = readIntoArray(file, numCustomers);
int min = locateBirthdate(customers);
System.out.println("Birthdays this month: " + customer[mon].getBirthdate());
}
//* Counts customers in the file.//
public static int countCustomers(File f) {
int i = 0;
try {
Scanner scan = new Scanner(f);
while (scan.hasNextLine()) {
i++;
scan.nextLine();
}
} catch (Exception e) {
System.out.println("Check filename.");
}
return i;
}
//read data into array and convert into string array
public static Customer[] readIntoArray(File f, int num) {
//num = countCustomers(f);
num = 0;
try {
Scanner input = new Scanner(f);
Customer[] birth = new Customer[num];
String[] strBirth = new String[num];
while (num < countCustomers(f)) {
strBirth[num] = input.nextLine();
birth[num] = makeCustomer(strBirth[num]);
num++;
System.out.println(num);
}
} catch (Exception e) {
System.out.println("Error");
}
return null;
Ok. I have several comments.
First - do you really need 'strBirth' array? Looks like you only write elements but not read from the array.
Second - 'readIntoArray' method always returns null.
Also, you count customers twice, but only one is enough.
Then, do you really need an array with customers? Since you use an array, you need to know exactly the count of customers and therefore you need to scan the file twice. If you use ArrayList, you need to scan file only one time.
I have fixed the issues in the code below.
public class Customers {
//////// MAIN ////////
public static void main(String[] args) {
File file = new File("customers.txt");
Person[] customers = readIntoArray(file, numCustomers);
int numEntries = customers.length;
int min = locateBirthdate(customers);
System.out.println("Birthdays this month: " + customer[mon].getBirthdate());
}
public static Person[] readIntoArray(File f, int num) {
List<Customer> customers = new ArraList<>();
try {
Scanner input = new Scanner(f);
String[] strBirth = new String[num];
while (scan.hasNextLine()) {
customers.add(makeCustomer(scan.nextLine()));
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return customers.toArray(Person[]::new);
}

why isn't the rest of my method being called? (loop being ignored)

i'm trying to write a program that reads a file and then prints it out and then reads it again but only prints out the lines that begin with "The " the second time around. it DOES print out the contents of the file, but then it doesn't print out the lines that begin with "The " and i can't figure out why. it prints out the println line right before the loop, but then it ignores the for-loop completely. the only difference between my findThe method and my OutputTheArray method is the substring part, so i think that's the problem area but i don't know how to fix it.
import java.util.*;
import java.io.*;
public class EZD_readingFiles
{
public static int inputToArray(String fr[], Scanner sf)
{
int max = -1;
while(sf.hasNext())
{
max++;
fr[max] = sf.nextLine();
}
return max;
}
public static void findThe(String fr[], int max)
{
System.out.println("\nHere are the lines that begin with \"The\": \n");
for(int b = 0; b <= max; b++)
{
String s = fr[b].substring(0,4);
if(s.equals("The "))
{
System.out.println(fr[b]);
}
}
}
public static void OutputTheArray(String fr[], int max)
{
System.out.println("Here is the original file: \n");
for(int a = 0; a <= max; a++)
{
System.out.println(fr[a]);
}
}
public static void main(String args[]) throws IOException
{
Scanner sf = new Scanner(new File("EZD_readme.txt"));
String fr[] = new String[5];
int y = EZD_readingFiles.inputToArray(fr,sf);
EZD_readingFiles.OutputTheArray(fr,y);
int z = EZD_readingFiles.inputToArray(fr,sf);
EZD_readingFiles.findThe(fr,z);
sf.close();
}
}
this is my text file with the tester data (EZD_readme.txt):
Every man tries as hard as he can.
The best way is this way.
The schedule is very good.
Cosmo Kramer is a doofus.
The best movie was cancelled.
Try cloning sf and passing it to the other function.
Something like this:
Scanner sf = new Scanner(new File("EZD_readme.txt"));
Scanner sf1 = sf.clone();
int y = EZD_readingFiles.inputToArray(fr,sf);
EZD_readingFiles.OutputTheArray(fr,y);
int z = EZD_readingFiles.inputToArray(fr,sf1);
EZD_readingFiles.findThe(fr,z);
sf.close();
sf1.close();

How do I read and process a file in a separate method and call it in the main method in Java?

I have this code i'm working on to compute the ARI of a given text read from the a .txt file. This code works perfectly but I want to put in fewer things in my main method. How is it able to put my try and catch block in a new method and then call it to my main method instead of having everything mashed together? I have tried some few ways but i'm not getting the usual output.
Here is my main class:
public class MyClass {
public static void main(String[] args){
String EachSentence;
int wordCount;
List<Sentence> sentences = new ArrayList<>();
List<Integer> EachWordCount = new ArrayList<>();
List<Integer> EachLetterCounted= new ArrayList<>();
try{
File file = new File("a2b.txt");
Scanner scanner = new Scanner(file);
scanner.useDelimiter("[.?!]");
int SentenceCount =0;
while(scanner.hasNext()){
SentenceCount++;
EachSentence = scanner.next();
EachSentence = EachSentence.replaceAll("\\r?\\n", " ");
EachSentence = EachSentence.trim();
if (sentences.add(new Sentence(EachSentence)) && sentences.size() > 1){
System.out.println("(" + SentenceCount + ") " + EachSentence);
}
StringTokenizer tokenizer = new StringTokenizer(EachSentence, " ");
wordCount = tokenizer.countTokens();
if(EachWordCount.add(wordCount)&& EachWordCount.size() > 1){
//I removed the element at position 0 so as to correlate with EachSentence then added the counts to the arrayList
//to prepare them for addition
EachWordCount.remove(0);
EachWordCount.add(wordCount);
}
int LetterCount=1;
for(int i=1; i<EachSentence.length(); i++){
char currentChar = EachSentence.charAt(i);
if(currentChar != ' '&& currentChar!='('&&currentChar!=')'&&currentChar!=','&& currentChar!='.'){
EachLetterCounted.add(LetterCount);
LetterCount++;
}
}
}
scanner.close();
}catch (IOException ex){
System.out.println(ex.getMessage());
}
//Computes the ARI of the total sentences
double lettersCounted = (double) lettersCounted(EachLetterCounted);
double wordsCounted = (double) sum(EachWordCount);
double sentencesCounted = (double) SentencesCounted(EachWordCount);
double AutomatedReadabilityIndex= 4.71*(lettersCounted/wordsCounted) + 0.5 * (wordsCounted/sentencesCounted) -21.43;
System.out.println("\nSummary statistics: ");
System.out.println("Letters: "+lettersCounted(EachLetterCounted));
System.out.println("Words: "+ sum(EachWordCount));
System.out.println("Sentences: " + SentencesCounted(EachWordCount));
DecimalFormat df = new DecimalFormat("#.##");
System.out.println("readability: "+ df.format(AutomatedReadabilityIndex));
}
contributions would be great!
Second time answering my question.(For anyone having the same problem) I achieved this by simply putting everything I had in the main method in a ...static void ReadFile() method and calling only `ReadFile in the main method. It may not be the best way but it was what I was looking for :)
public static void main(String[] args) {
ReadFile();
}
public static void ReadFile() {
//insert all what is in main method, the exceptions were handled
//here also. So there was no need for the throws IOException that
//should've followed.
}
OR
public static void main(String[] args) {
ReadFile(//insert name of file to be read here);
}
public static void ReadFile(String filename) {
//insert all what is in main method, the exceptions were handled
//here also. So there was no need for the throws IOException that
//should've followed.
}

using get and set methods to pass an array between two classes (java)

In my class ReadInput, i read a file containing integers separated by space one by one and put them into inputArray. I then want to use inputArray (and its size) in my class B and i'm attempting to do that with get and set methods but I guess i'm not using them correctly and can't pinpoint my error. Can anyone help? Thanks
import java.io.*;
import java.util.*;
public class ReadInput
{
String INPUT_FILE_NAME = "pages.dat"; // filename
private int [] inputArray;
private int size;
public ReadInput()
{
Scanner fileIn=null; //(Initialization keeps compiler happy)
try { // open file
fileIn = new Scanner(new FileInputStream(INPUT_FILE_NAME));
} catch (FileNotFoundException e) {
System.out.println("Input file "+INPUT_FILE_NAME+" not found. ");
System.exit(1);
}
while (fileIn.hasNextLine())
{
String word = fileIn.next();
size++;
}
inputArray = new int [size];
//test to see that it gives correct size
System.out.println(size);
fileIn.close(); // close file
try { // open file
fileIn = new Scanner(new FileInputStream(INPUT_FILE_NAME));
} catch (FileNotFoundException e) {
System.out.println("Input file "+INPUT_FILE_NAME+" not found. ");
System.exit(1);
}
int i=0;
while (fileIn.hasNextLine())
{
inputArray[i] = fileIn.nextInt();
i++;
}
fileIn.close();
}
public int [] getinputArray()
{
return inputArray;
}
public void setinputArray(int [] inputArray)
{
this.inputArray = inputArray;
}
public int getSize()
{
return size;
}
public void setsize(int size)
{
this.size = size;
}
}
public class B
{
ReadInput in = new ReadInput();
int [] inputs;
public B()
{
}
//this method does not work and gives an error
public void method()
{
System.out.println("in FIFO: " + in.getSize());
for(int j=0; j< inputs.length; j++)
System.out.print(inputs[j] + " ");
}
}
In B's constructor, you need to call in.initializeArrays() and in.getJobs().
Right now, in.getSize() is 0 since that's the default value of ReadInput.size. In addition, in.getInputArray() will be null since that is the default value of ReadInput.inputArray.
Alternatively, you could remove ReadInput.initializeArrays() and ReadInput.getJobs() and simply move the code into a zero-argument constructor for ReadInput, like so:
class ReadInput {
// previous fields: size, inputArray, etc.
public ReadInput() {
// code for setting size and populating inputArray from the file
}
// other methods: getJobs, etc.
}
If you do this, then you should be set. You're already calling ReadInput's constructor through your ReadInput in = new ReadInput(); line, so that line should then populate in's data.
In B's constructor, I don't see you calling
in.initializeArrays
or
setinputArray(int [] inputArray)
anywhere to actually set the array before getting the size.

Categories

Resources