First I create a txt file (a.txt) -- DONE
create 10 random number from - to ( like from 5 -10 ) --DONE
I write this number in txt file --DONE
I want to check its written or not -- DONE
Now I need to find: how many number, biggest, smallest, sum of numbers
But I can not call that file and search in the file (a.txt). I am just sending last part. Other parts work. I need some help to understand. It is also inside another method. not main
Scanner keyboard = new Scanner(System.in);
boolean again = true;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int a = 0;
int count = 0;
System.out.println("Enter the filename to write into all analysis: ");
outputFileName = keyboard.nextLine();
File file2 = new File(outputFileName);
if (file2.exists()) {
System.out.println("The file " + outputFileName +
" already exists. Will re-write its content");
}
try {
PrintWriter yaz = new PrintWriter(file2);
// formulas here. created file a.txt need to search into that file biggest smallest and sum of numbers
yaz.println("Numeric data file name: " + inputFileName);
yaz.println("Number of integer: " + numLines);
yaz.println("The total of all integers in file: " + numLines); //fornow
yaz.println("The largest integer in the set: " + max);
yaz.println("The smallest integer in the set " + min);
yaz.close();
System.out.println("Data written to the file.");
} catch (Exception e) {
System.out.printf("ERROR reading from file %s!\n", inputFileName);
System.out.printf("ERROR Message: %s!\n", e.getMessage());
}
So you want a code to read a text file and give you the biggest, smallest and the average.
You can use Scanner class for that and use hasNextInt() to find integers
File f = new File("F:/some_text_file.txt"); // input your text file here
if(f.exists()){
try{
Scanner sc = new Scanner(f);
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int temp=0, i=0;
double sum=0;
while(sc.hasNextInt()){
temp = sc.nextInt();
if(temp>max) max = temp;
if(temp<min) min =temp;
sum+=(double) temp;
i++;
}
System.out.println("average : " +sum/i);
System.out.println("large : "+max);
System.out.println("small :"+min);
sc.close();
}catch(Exception e){
e.printStackTrace();
}
}
See if this works
You need to read the file into memory. One way to do that is to move the text of the file into a String.
This post will help you: Reading a plain text file in Java
Here's the relevant code:
try(BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
}
Related
The idea of this is to take in a console input and use it as the file name for the text file to fill with square root values with various decimal places
however I cannot get it to let me enter anything, it throws a NoSuchElementException and I do not get why? in a previous method, I used this exact code to get the file name as a variable
This is Current Method
private static void FileWritting () throws IOException {
System.out.println("\n6.7.2 Writting Data");
System.out.println("-----------------------");
System.out.println("Enter the File name");
Scanner Scanner2 = new Scanner(System.in);
String filename = Scanner2.nextLine();
FileWriter writehandle = new FileWriter("D:\\Users\\Ali\\Documents\\lab6\\" + filename + ".txt");
BufferedWriter bw = new BufferedWriter(writehandle);
int n = 10;
for(int i=1;i<n;++i)
{
double value = Math.sqrt(i);
String formattedString = String.format("%."+ (i-1) +"f", value);
System.out.println(formattedString);
// bw.write(line);
bw.newLine();
}
bw.close();
writehandle.close();
Scanner2.close();
}
Where This is the previous method
System.out.println("6.7.1 Reading Data");
System.out.println("-----------------------");
System.out.println("Enter the File name");
Scanner Scanner1 = new Scanner(System.in);
String filename = Scanner1.nextLine();
FileReader readhandle = new FileReader("D:\\Users\\Ali\\Documents\\lab6\\"+ filename +".txt");
BufferedReader br = new BufferedReader(readhandle);
String line = br.readLine ();
int count = 0;
while (line != null) {
String []parts = line.split(" ");
for( String w : parts)
{
count++;
}
line = br.readLine();
}
System.out.println("The number of words is: " + count);
br.close();
Scanner1.close();
}
You're calling Scanner#close in your first method. This closes stdin, which makes reading from it impossible. I recommend creating a global variable to hold your scanner and closing it when your program terminates (instead of creating a new one in every method).
More info and a better explanation
i tried reading a string from a file and it worked just fine but it won't work with an integer. i can't seem to find the problem
public static void main(String[] args) throws FileNotFoundException {
File in = new File ("FCITsamba.in.rtf");
Scanner scanner = new Scanner(in);// Scanner variable to read from the input file
File outFile = new File("FCITsamba.txt");// the out file
PrintWriter out = new PrintWriter(outFile); // Printwriter to write to the file
int maxAccounts = 0;//maximum number of accounts that can be in the bank
int maxTransactions = 0;//maximum number of transactions in a given day
int accNum = 0;
int transNum = 0;
int d = 0;
int k = 0;
int dayNo = 1;
if (!in.exists()) {
System.out.println("Input file, " + in + ", does not exist.");
System.exit(0);
}
maxAccounts = scanner.nextInt();
maxTransactions = scanner.nextInt();
d = scanner.nextInt(); //representing the number of days for the simulation
k = scanner.nextInt();
it gives me this error:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at fcitsamba.FCITsamba.main(FCITsamba.java:43)
Java Result: 1
i tried putting an inputMismatchException but it didn't work i also tried putting it in an if statement as shown below:
if(scanner.hasNextInt()){
maxAccounts = scanner.nextInt();
maxTransactions = scanner.nextInt();
d = scanner.nextInt(); //representing the number of days for the simulation
k = scanner.nextInt();
}
but it didn't work as well
this is the input File :
200
10000
2
11
OPENACCOUNT 1485 Aslam Saeed 2000.0
DEPOSIT 1485 1000.0
...
When you read from a file, it won't recognize whether it is reading numbers or strings, hence everything will be treated as strings including what is shown in your data file (200, 10000, 2, 11).
Instead of writing:
d = scanner.nextInt();
Try this:
d = Integer.parseInt(scanner.nextLine());
Scanner reads 1 value at a time, so if the next value you are trying to read is not an int it will throw an error.
I used your data and the following worked for me:
public static void main(String[] args) {
//Replace FILE_PATH with your file path.
try {
Scanner reader = new Scanner(new File("FILE_PATH/fromFile.txt"));
PrintWriter writer = new PrintWriter(new File("FILE_PATH/toFile.txt"));
int maxAccounts = reader.nextInt();
int maxTransactions = reader.nextInt();
int d = reader.nextInt();
int k = reader.nextInt();
writer.println("maxAccounts: " + maxAccounts);
writer.println("maxTransactions: " + maxTransactions);
writer.println("d: " + d);
writer.println("k: " + k);
writer.close();
reader.close();
} catch (FileNotFoundException ex) {
System.out.println("Error: " + ex.getMessage());
}
}
Hy,
In the result, the number of zeros and ones isn't the same.
And i don't find where is the problem.
Can any One help me please?
//Main {
int bufferSize = 10240; //10KB
int fileSize = 10 * 1024 * 1024; //10MB
Random r = new Random();
//Writing 0 and 1 into file
File file = new File("test.txt");
FileWriter fw = new FileWriter(file, false); //this false means, every time we want to write into file, it will destructs what was before
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
for(int i=0; i<1000; i++){
for(int j=0; j<1000; j++){
if(r.nextBoolean()){
pw.write("0 ");
}else{
pw.write("1 ");
}
}
pw.write("\n");
}
System.out.println("End of writing into file : " + file.getName() + ", in : " + file.getAbsolutePath() + ", and its size : " + file.length());
pw.close();
//Read from file, and counting number of zeros and ones
System.out.println("Reading from file : Scanner method");
Scanner sc = null;
//sc = new Scanner(new BufferedReader(new FileReader(file)));
sc = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"), bufferSize));
int countZeros=0;
int countOnes=0;
StringTokenizer st = null;
String temp = null;
//Start counting time
long debut = System.nanoTime();
while(sc.hasNext()){
st = new StringTokenizer(sc.next(), " ");
while(st.hasMoreTokens() ){
temp = st.nextToken();
if(temp.compareTo("0")==0 && !Character.isSpaceChar(temp.charAt(0))){
countZeros++;
}
else if(temp.compareTo("1")==0 && !Character.isSpaceChar(temp.charAt(0))){
countOnes++;
}
}
}
//End counting time
long end = System.nanoTime() - debut;
sc.close();
System.out.println("Number of Zeros : " + countZeros);
System.out.println("Number of Ones : " + countOnes);
System.out.println("Total of zeros and Ones : " + (countZeros+countOnes));
System.out.println("Duration of counting zeros and ones : " + end/1000000 + "ms");
System.out.println("************");
System.out.println("Reading from file : BufferedReader method");
countZeros=0;
countOnes=0;
st=null;
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"), bufferSize);
String[] tempLigne = null;
//Start counting time
debut = System.nanoTime();
for(int i=0; (i=br.read())>-1;){
tempLigne = br.readLine().split(" ");
for(int j=0; j<tempLigne.length; j++){
if(tempLigne[j].equals("0")){
countZeros++;
}else if(tempLigne[j].equals("1")){
countOnes++;
}
}
}
//End counting time
end = System.nanoTime() - debut;
br.close();
System.out.println("Number of Zeros : " + countZeros);
System.out.println("Number of Ones : " + countOnes);
System.out.println("Total of zeros and Ones : " + (countZeros+countOnes));
System.out.println("Duration of counting zeros and ones : " + end/1000000 + "ms");
}
}
//Output
End of writing into file : test.txt, in : C:\Users\youness\workspace\ScannerFile\test.txt, and its size : 1990656
Reading from file : Scanner method
Number of Zeros : 499807
Number of Ones : 500193
Total of zeros and Ones : 1000000
Duration of counting zeros and ones : 1020ms
************
Reading from file : BufferedReader method
Number of Zeros : 499303
Number of Ones : 499697
Total of zeros and Ones : 999000
Duration of counting zeros and ones : 177ms
Thank you,
Best Reagrds
The problem lies in the code here:
for(int i=0; (i=br.read())>-1;){
tempLigne = br.readLine().split(" ");
for(int j=0; j<tempLigne.length; j++){
if(tempLigne[j].equals("0")){
countZeros++;
}else if(tempLigne[j].equals("1")){
countOnes++;
}
}
}
br.read() actually reads one character. Instead of processing that character, you discard the result by reading the remaining whole line by br.readline().
Since there are 1000 lines in the file and you discarded the first character of each line, you end up 1000 characters less.
You may change your for(int i=0; (i=br.read())>-1;) to while (br.ready()). When the br is empty, the loop will terminate
You're generating 0 and 1 values using Random class.
This class generates a random distribution so it doesn't ensures that the number of 0 and 1 characters generated will be the same, because it's a random generator.
Only if you generate an infinite amount of numbers then there will be the same number of 0s and 1s.
The more characters you generate, the closer the two values will be.
I am attempting to learn how to prompt users to enter a file name, rather than predefining it, so that Java can go through with the Scanner and read through it. I have written a program that does what I need it to do, but only when the file in question is predefined.
I have looked around the site for duplicate questions, and found a few, but the scope in which it was asked was a bit more advanced than where I am. Can anyone offer me a bit of guidance on how to prompt a user to enter the file he/she wants, as opposed to predefining it (as code below is set to).
Note - This was written assuming the files read in had integers < 0 and > 0, hence why the min/max functions were done in the way they were...simply trying to teach myself one step at a time.
import java.io.*;
import java.util.*;
public class ProcessNumbers {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("inputdata.txt"));
int max = 0;
int min = 0;
int sum = 0;
int count = 0;
double average = 0;
System.out.println("Enter file name: "); //currently a println for ease of reading via Run
while (input.hasNext()) {
if (input.hasNextInt()) {
int number = input.nextInt();
sum += number;
count++;
average = (double) (sum) / count;
if (number > max) {
max = number;
}
if (number < min) {
min = number;
}
} else {
input.next();
}
}
System.out.println("Maximum = " + max);
System.out.println("Minimum = " + min);
System.out.println("Sum = " + sum);
System.out.println("Count = " + count);
System.out.println("average = " + average);
}
}
Try this:
System.out.println("Enter file name: ");
Scanner fileNameScanner = new Scanner( System.in );
String fileName = "";
if ( fileNameScanner .hasNext() ) {
fileName = fileNameScanner.next();
}
...
Using the fileName string, create a File object and use as per your requirements.
Easiest way would be to replace
new File("inputdata.txt")
with
new File(args[0])
This way the first command-line argument will be treated as a filename.
You can use Scanner to read a input from user (it doesn't only read from a File):
Scanner prompt = new Scanner(System.in);
System.out.print("Enter name of the file: ");
String name = prompt.next(); // enter "inputdata.txt"
Scanner input = new Scanner(new File(name));
// ...
Another approach would be to use the Console.
You substitute your scanner to read from a File returned from a new method:
Scanner input = new Scanner(getFileFromUser());
...
private static File getFileFromUser() {
Console c = System.console();
if (c == null) {
System.err.println("No console.");
System.exit(1);
}
String filePathname = c.readLine("Enter file pathname: ");
return new File(filePathname);
}
Also don't forget to close your scanner in the end of main method to avoid resource leak:
input.close();
this code i have been doing suppose to add a counter everytime the code found a term in a file. The counter represents the number of documents containing the term.
System.out.println("Please enter the required word :");
Scanner scan2 = new Scanner(System.in);
String word2 = scan.nextLine();
String[] array2 = word2.split(" ");
for (int b = 0; b < array.length; b++) {
for (int i = 0; i < filename; i++) {
try {
BufferedReader in = new BufferedReader(new FileReader(
"C:\\Users\\user\\fypworkspace\\TextRenderer\\abc"
+ i + ".txt"));
int numDoc = 0;
int numofDoc = 0;
Scanner s2 = new Scanner(in);
{
while (s2.hasNext()) {
if (s2.next().equals(word2))
numDoc++;
}
}
if (numDoc > 0)
numofDoc++;
System.out.println("File containing the term is "
+ numofDoc);
} catch (IOException e) {
System.out.println("File not found.");
}
The output is :
Please enter the required word :
the
File containing the term is 1
File containing the term is 1
File containing the term is 1
File containing the term is 1
File containing the term is 1
File containing the term is 1
File not found
File containing the term is 1
File containing the term is 1
File containing the term is 1
File containing the term is 1
I would like the output to display the number of file containing the term is 10.
Mind to point out my mistake ? thanks..
Indent your code properly (under Eclipse, CTRL + SHIFT + F will do it for you)
Give sensible and explicit names to your variables. numDoc and numOfDoc are too close to avoid mistakes
You are outputing the counter in the inner loop, try to get your System.out.println("File containing the term is " + numofDoc); out of the second for loop (this can easily be spotted if you indent your code properly). Also check that you are outputting the right variable.
Now that you print the result in the proper place, int numofDoc = 0; shall also be outside the second for loop.
Additionally, you are using String.equals to check if the current line of the file contains the required text. Maybe you want to look for the documentation of String.contains
I guess that numDoc represents the number of occurences in the file and numofDoc reprents the number of files.
The problem is that the variable int numofDoc = 0 is set in the for loop. So for every new file the counter is reset.
Set int numDoc = 0; before the two loops.
So you're setting back the value to 0 every time the loop is executed.
declare int numDoc = 0; int numofDoc = 0; outside for loop.
whenever executing to for loop, they initialized & then incremented to 1. That's why you getting all time 1.
I think you want to do this
public static void main(String[] args)
{
System.out.println("Please enter the required word :");
Scanner scan2 = new Scanner(System.in);
String word2 = scan.nextLine();
String[] array2 = word2.split(" ");
for ( int b = 0; b < array.length; b++ )
{
**//Declare before the loop**
int numofDoc = 0;
for ( int i = 0; i < filename; i++ )
{
try
{
BufferedReader in = new BufferedReader(new FileReader(
"C:\\Users\\user\\fypworkspace\\TextRenderer\\abc" + i + ".txt"));
int matchedWord = 0;
Scanner s2 = new Scanner(in);
{
while ( s2.hasNext() )
{
if ( s2.next().equals(word2) )
matchedWord++;
}
}
if ( matchedWord > 0 )
numofDoc++;
System.out.println("File containing the term is " + numofDoc);
}
catch ( IOException e )
{
System.out.println("File not found.");
}
}
}
}