0

Read a txt.file and find max, avrg, odd, even, and prime?

Hello everyone :) Have an assignment due in two weeks. I need some help with my code. Im not looking for the answer, just for someone to help me understand how to formulate my code. So i have a few questions? 1. Do I call my methods before or after the "fileReader"? For example once I have closed the filereader does that mean I can not access the txt file to print to screen the max, aver etc? Any help would be great.

28th Feb 2017, 12:59 AM
Winiata Hunia
Winiata Hunia - avatar
13 ответов
+ 3
Okay. I'll take things in order: 1. I don't like file reader, I prefer the more general use Scanner. Just use: Scanner someName = new Scanner(new File("someFile.txt")); And then you are done, you can use someName.read() and alot of other methods. There are alot of methods that starts with "next": someName.nextInt(); nextChar(); nextLong(); etc. Which will read the next thing in the file as the proper data type you want, so you could just int i = someName.nextInt(); And it would just read the next thing in the file as an int and put it into "i". For me this looks WAY cleaner. 2. There is no need to use "try". If you put "throws whateverException" in the function header. If you need to throw an exception you can just use "throw whateverException". The IDE you are using will catch on and autocomplete it. 3. What I like about Scanner is that it has some methods that check for stuff. For example let's say that your file is a list of numbers. Like "1 22 32 19 101 88 57 9" or something like that. If you are not sure how many numbers there are you have a method for that, that simply returns a true or a false. Scanner scn = new Scanner(new File("file.txt")); while (scn.hasNextInt()) { System.out.print(scn.nextInt()); } scn.close(); Feel free to give me any other questions ^^
1st Mar 2017, 9:42 PM
Seckar
Seckar - avatar
+ 1
yes. that is exactly what it means. you close the file after you are done with ir
28th Feb 2017, 5:58 AM
Seckar
Seckar - avatar
+ 1
sure! I work in java programming, I could give you some feedbacl
28th Feb 2017, 6:37 AM
Seckar
Seckar - avatar
+ 1
Answer #2 import java.io.File; import java.io.IOException; import java.util.Scanner; public class test { public static void main(String[] args) throws IOException { // Take things in order // 1. We set up the way to read from a file String fileName = "file1.txt"; Scanner fileDescriptor = new Scanner(new File(fileName)); // Done with this part. Next. // 2. Other variable declarations. I guess you want... int max = Integer.MIN_VALUE; // ...the max number from the file here int[] numbers = new int[20]; // ...all the numbers in the file here boolean isprime; // ...this to be used to see if a number is prime int sum = 0; // ...this to be the sum of all the numbers // 3. Read the numbers int i = 0; // Will count how many numbers we have while (fileDescriptor.hasNextInt() == true) { // Check if the next value in the file is an int numbers[i] = fileDescriptor.nextInt(); // Read it and increment the counter i++; } // 4. Maximum value for (int j = 0; j < i; j++) // Iterate trough the numbers and set the max value when you find a new one if (numbers[j] > max) max = numbers[j]; // 5. Sum for (int j = 0; j < i; j++) // Iterate trough the numbers and add them one by one in sum sum += numbers[j]; // 6. Primes for (int j = 0; j < i; i++) { // Iterate trough the numbers isprime = true; //We assume that each number is prime by default for (int k = 2; k < numbers[j]; k++) // Each number in numbers is checked if it is divided by any number if (numbers[j] % k == 0) // lower than itself. isprime = false; System.out.println(numbers[j]+" is prime:"+isprime); } } } This is the slow way to do it. For beginners.
6th Mar 2017, 3:25 PM
Seckar
Seckar - avatar
0
@Secker thanx. Would you be interested in looking at my code once I have done?
28th Feb 2017, 6:32 AM
Winiata Hunia
Winiata Hunia - avatar
0
import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class TryThis { public static void main(String args[]) throws IOException { FileReader fr = null; try { fr = new FileReader("C:\\Users\\krabb\\workspace\\preRequistPrograms\\file1.txt"); } catch( FileNotFoundException fnfe ) { System.out.println("File not Found."); return; } int i; System.out.println("File Contents are : "); while( (i = fr .read()) != -1) { System.out.print((char)i); } fr.close(); } }
1st Mar 2017, 9:23 PM
Winiata Hunia
Winiata Hunia - avatar
0
@Secker this is what I am starting with. Have I declared int = i in the wrong place? Should I have declared it after main? Where would I declare methods?
1st Mar 2017, 9:25 PM
Winiata Hunia
Winiata Hunia - avatar
0
thank you for your advice. I will re write now. should i populate int data into an array before declaring other methods?
1st Mar 2017, 9:49 PM
Winiata Hunia
Winiata Hunia - avatar
0
Before even writing the other methods? What do you mean? I usually just write a populate() method and just call that first in the main function. My code usually looks like this: public class Main { //declare whatever variables you would like to use here. Make it a point to use as little variables as possible public static int/long/whatever variable_1; // some more variables public static whatever variable_n; public static void main(String[] args) { populate(); // this would take as parameters, whatever variables you want to populate initially(from the ones declared above) doSometing(); // here is where 70-90% of your code is. Either in here or in other methods used inside this one. } } A good piece of advice in Java is to try to modularize and spit little tasks into methods as much as possible. Try to aim for every function having 10 or less lines of code(not counting lines with just a "}" on them obviously, I mean 10 actual instructions), the end result is a bunch of cute little methods all calling each other, but each method is so short and simple that you can tell what is does just by looking at it for 0.5 seconds.
1st Mar 2017, 10:03 PM
Seckar
Seckar - avatar
0
OK HAHAHA!! This is what I have :( import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Test3 { public static void main(String[] args) throws IOException { String fileName = "C:\\Users\\krabb\\workspace\\preRequistPrograms\\file1.txt"; String temp; int max = Integer.MIN_VALUE; int i = 0; int[] numbers = new int[20]; boolean isprime = true; int sum = 0; try (BufferedReader br = new BufferedReader(new FileReader(fileName))) { while ((temp = br.readLine()) != null) { if (temp.isEmpty()) break; numbers[i++] = Integer.parseInt(temp); } } for ( i = 0; i < numbers.length; i++) if (max < numbers[i]) max = numbers[i]; System.out.println("The largest number is: " + max); { sum = sum + numbers[i]; int average = sum / numbers.length; } //System.out.println("Average value of array elements is : " + average); } public static boolean isPrime(int numbers){ if(numbers == 2 || numbers == 3 | numbers == 5 || numbers == 7) return true; return ((numbers % 2) != 0 && (numbers % 3) != 0 && (numbers % 5) != 0 && (numbers % 7) != 0); } }
6th Mar 2017, 12:10 AM
Winiata Hunia
Winiata Hunia - avatar
0
Answer #1 Okay first of all, use the functions and methods I gave you, they are the cleanest and most useful ones, don't just ignore advice. Now, You are obviously a beginner so ALWAYS take stuff one at a time, don't try to do it all at once. I'll give you 2 ways to do it
6th Mar 2017, 3:19 PM
Seckar
Seckar - avatar
0
Answer #3 The fast and efficient way. import java.io.File; import java.io.IOException; import java.util.Scanner; import java.util.Vector; public class test { public static void main(String[] args) throws IOException { // 1. We set up the way to read from a file String fileName = "file1.txt"; Scanner fileDescriptor = new Scanner(new File(fileName)); // 2. Do it all. Vector<Integer> numbers = new Vector<>(); Integer max = Integer.MIN_VALUE; Integer sum = 0; Boolean isPrime; while (fileDescriptor.hasNextInt()) { // While there are still numbers to read... numbers.addElement(fileDescriptor.nextInt()); // ...read them if (numbers.lastElement() > max) // Check if we found a new max value... max = numbers.lastElement(); // ...and store it sum += numbers.lastElement(); // Add the new number to the sum isPrime = true; // Assume each number is prime for (int i = 2; i <= numbers.lastElement() / 2; ++i) // Check it for any divisors if (numbers.lastElement() % i == 0) isPrime = false; if (isPrime) // Display whether it is prime or not System.out.println(numbers.lastElement() + " is prime."); else System.out.println(numbers.lastElement() + " is not prime."); } System.out.println("sum = " + sum); // Display all the other stuff System.out.println("max = " + max); System.out.println("numbers = " + numbers); } } Next time tell me what exacty your problem is too. Not just "here is what I tried, it doesn't work"
6th Mar 2017, 3:36 PM
Seckar
Seckar - avatar
0
@Seckar I do apologise i was not being desrespectful and ignoring your advice, as you said I am a beginner and the best way I learn is by analyising a complete code. My tutor moves too fast my class and becuase there are so many of us I doesnt have time to work one on one with us. I actually did do as you said and used scanner to read int from a txt file, I became stuck after that. please note i am not lazy or want someone to give me the answer, i have complete 3 online java coding courses including solo learn, but its like puzzle peices to me, I know the function or purpose of each peuce but I dont know how to put the puzzle together, like i understand the logic but i dont understand the syntax.
6th Mar 2017, 7:51 PM
Winiata Hunia
Winiata Hunia - avatar