I have a text file, and I want to find the middle word of the whole file and print the number of characters it has. I can do this for one line:
System.out.println("'" + str[tok / 2] + "'");
But I don't know how to point to a certain line. Here is all of my code:
import java.io.*;
import java.text.*;
import java.util.*;
public class AmendClassify {
public static void main(String[] args) {
try {
System.out.println("Please enter the file name:");
Scanner sc = new Scanner(System.in);
String file = sc.next();
file = file + ".txt";
Scanner s = new Scanner(new FileReader(file));
System.out.println("You are scanning '" + file + "'");
PrintWriter output = new PrintWriter(new FileOutputStream("output.txt"));
double lineNum = 0;
double wordCount = 0;
double charCount = 0;
int tok = 0;
String str[] = null;
DecimalFormat df = new DecimalFormat("#.#");
String line = null;
while (s.hasNextLine()) {
line = s.nextLine();
lineNum++;
str = line.split((" "));
tok = str.length;
for (int i = 0; i < str.length; i++) {
if (str[i].length() > 0) {
wordCount++;
}
}
charCount += (line.length());
}
double density = (charCount / wordCount);
System.out.println("'" + str[tok / 2] + "'"); // middle word of the 1st/last line
gap();
System.out.println("Number of lines: " + lineNum);
System.out.println("Number of words: " + wordCount);
System.out.println("Number of characters: " + charCount);
gap();
System.out.println("The DENSITY of the text is: " + df.format(density));
System.out.println();
int critical;
System.out.println("Do you want to alter the critical value(Y/N)");
String answer = sc.next();
if (answer.equals("y") || answer.equals("Y")) {
System.out.println("Please enter a value: ");
critical = sc.nextInt();
} else {
critical = 6;
}
//So...
if (density > critical) {
System.out.println("NAME: '" + file + "'" + ", DENSITY: " + df.format(density) + ", TYPE: " + "Heavy");
} else {
System.out.println("NAME: '" + file + "'" + ", DENSITY: " + df.format(density) + ", TYPE: " + "Light");
}
System.out.print("--FINISHED--");
s.close();
output.close();
sc.close();
} //end of try
catch (FileNotFoundException e) {
System.out.println("Please enter a valid file name");
}
} // end of main
public static void gap() {
System.out.println("------------------------------");
}
}
A text file I have used to test is
Hello my name is Harry. This line contains 83 characters, 15 words, and 1 line(s).
This is the second line.
This is the third line.
This is the fourth line.
Since this looks like a homework assignment I'd recommend reading the entire file into a String and then removing all new-line characters with replaceAll() if need be (depending how you read the entire file into a String). You then would effectively have a single line ... so your existing code would work (taking into account that the middle word would actually be the word to the left of the middle if the file has an even number of words).
Note that this is not an optimal solution though. Don't use it at work.
Related
So for this assignment, it asks the user to enter a phone number, then it splits the number up into a category of each set of integers. What I'm attempting to do is to throw a simple exception that if they do not enter the parenthesis for the area code that it throws the exception but doesn't crash the program and asks them to re-enter using the correct format
public class App{
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
String inputNum;
String token1[];
String token2[];
String areaCode;
String preFix;
String lineNum;
String fullNum;
System.out.print("Enter a phone number in (123) 123-4567 format: ");
inputNum = input.nextLine();
System.out.println();
token1 = inputNum.split(" ");
areaCode = token1[0].substring(1, 4);
if (token1[0].substring(0, 3) != "()"){
throw new Exception("Enter a phone number in (123) 123-4567 format: ");
}
token2 = token1[1].split("-");
preFix = token2[0];
lineNum = token2[1];
fullNum = "(" + areaCode + ")" + " " + preFix + "-" + lineNum ;
System.out.print("Area code: " + areaCode + "\n");
System.out.print("Prefix: " + preFix + "\n");
System.out.print("Line number: " + lineNum + "\n");
System.out.print("Full number: " + fullNum);
}
}
No need to throw. Just keep asking in a loop.
String areaCode;
String preFix;
String lineNum;
while (true) {
System.out.print("Enter a phone number in (123) 123-4567 format: ");
String inputNum = input.nextLine();
System.out.println();
String [] token1 = inputNum.split(" ");
if (token1.length == 2 && token1[0].length() == 5
&& token1[0].charAt(0) == '(' && token1[0].charAt(4) == ')') {
areaCode = token1[0].substring(1, 4);
String [] token2 = token1[1].split("-");
if (token2.length == 2 && token2[0].length() == 3 && token2[1].length() == 4) {
preFix = token2[0];
lineNum = token2[1];
// If we reach this line all is ok. Exit the loop.
break;
}
}
}
String fullNum = "(" + areaCode + ")" + " " + preFix + "-" + lineNum ;
System.out.print("Area code: " + areaCode + "\n");
System.out.print("Prefix: " + preFix + "\n");
System.out.print("Line number: " + lineNum + "\n");
System.out.print("Full number: " + fullNum);
Whenever I put inputs into this loop, no matter how many it will only write my final input to the file
Here's the code:
import java.util.Scanner;
import java.io.IOException;
import java.io.*;
class lista {
public static void main(String[] args) throws IOException {
Scanner n = new Scanner(System.in);
int x = 0;
File productList = new File("productList.txt");
FileWriter fr = new FileWriter("productList.txt", true);
/// While Loop Start
while (x == 0) {
System.out.println("Enter the product:");
String product = n.nextLine();
System.out.println("");
System.out.println("Enter the price:");
String price = n.nextLine();
System.out.println("");
System.out.println("Enter the type of product, e.g. Movie, Bluray, etc...");
String type = n.nextLine();
System.out.println("");
System.out.println(product + " - " + "$" + price + " (" + type + ")" + "\n\n");
try {
fr.write((product + " - " + "$" + price + " (" + type + ")" + "\n\n"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Type \"0\" if you would like to stop, type \"1\" if you would like to continue.");
int y = n.nextInt();
n.nextLine();
if (y == 1) {
x = 0;
} else {
x = 1;
fr.close();
}
}
/// While Loop Ends
}
}
I can input something like,
1,1,1,1
2,2,2,1
3,3,3,0
, and it will only print:
3 - $3 (3)
Thanks.
This is a possible duplicate of Trouble with filewriter overwriting files instead of appending to the end.
However you seem to have found the solution yourself already (the true parameter when creating the FileWriter). This should append to the file instead of overwriting it. If this does not work, then you might have a problem with the file or the OS. In any case, your code is not fundamentally wrong and should work.
Some suggestions for readability and ease of use on the code itself (just minor details).
Scanner in = new Scanner(System.in);
PrintStream out = System.out;
try (FileWriter writer = new FileWriter("productList.txt", true)) {
INPUT_LOOP:
while (true) {
out.println("Enter the product:");
String product = in.nextLine();
out.println();
out.println("Enter the price:");
String price = in.nextLine();
out.println();
out.println("Enter the type of product, e.g. Movie, Bluray, etc...");
String type = in.nextLine();
out.println();
String entry = product + " - " + "$" + price + " (" + type + ")" + "\n\n";
out.println(entry);
writer.append(entry);
out.println("Type \"exit\" if you would like to stop, any other input will continue.");
if (in.nextLine().trim().toLowerCase().equals("exit")) {
break INPUT_LOOP;
}
}
} catch (IOException e) {
e.printStackTrace();
}
My code pulls from three text files in order to identify the date/time of the highest value in a list (and display the prior and following five values). Unfortunately, after exporting it as a runnable JAR from Eclipse (I'm including all three text files in the export), it produces absolutely no output. I tried Google and Stack Overflow, but can't seem to find the source of the error. Do you think it's more likely to be an issue with my code, or something I'm doing in Eclipse (e.g. when exporting the file)?
Here is how I'm exporting this as a Runnable Jar File
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
public class FindTheMaxGeiger {
public static void main (String[] args) {
String [] dateStamp = getDate("4_22_18_dates.txt");
String [] timeStamp = getTime("4_22_18_times.txt");
try {
Scanner scanner1 = new Scanner(new File("4_22_18_radiation.txt"));
int radCtr = 0;
while (scanner1.hasNextLine()) {
radCtr++;
scanner1.nextLine();
}
Scanner scanner2 = new Scanner(new File("4_22_18_radiation.txt"));
int [] radiation = new int [radCtr]; //create the radiation array
int i = 0;
while(scanner2.hasNextLine()){
radiation[i++] = scanner2.nextInt();
}
int max = getMax(radiation);
System.out.println("Date Counts per Minute");
System.out.println("-------------------------------");
System.out.println(dateStamp[max-5]+ " " + timeStamp[max-5] + " " + radiation[max-5]);
System.out.println(dateStamp[max-4]+ " " + timeStamp[max-4] + " " + radiation[max-4]);
System.out.println(dateStamp[max-3]+ " " + timeStamp[max-3] + " " + radiation[max-3]);
System.out.println(dateStamp[max-2]+ " " + timeStamp[max-2] + " " + radiation[max-2]);
System.out.println(dateStamp[max-1]+ " " + timeStamp[max-1] + " " + radiation[max-1]);
System.out.println(dateStamp[max]+ " " + timeStamp[max] + " " + radiation[max] + "(This is the max)");
System.out.println(dateStamp[max+1]+ " " + timeStamp[max+1] + " " + radiation[max+1]);
System.out.println(dateStamp[max+2]+ " " + timeStamp[max+2] + " " + radiation[max+2]);
System.out.println(dateStamp[max+3]+ " " + timeStamp[max+3] + " " + radiation[max+3]);
System.out.println(dateStamp[max+4]+ " " + timeStamp[max+4] + " " + radiation[max+4]);
System.out.println(dateStamp[max+5]+ " " + timeStamp[max+5] + " " + radiation[max+5]);
}
catch (FileNotFoundException e){
}
}
//here we call the method to find the max
public static String[] getDate(String file) {
//step 1:
// count the number of lines in the file
//step 2 - create the array and copy the elements in
int ctr = 0;
try {
Scanner s3 = new Scanner(new File(file));
while (s3.hasNextLine()) {
ctr++;
s3.nextLine();
}
String[] dateStamp = new String[ctr]; //creation
Scanner s4 = new Scanner(new File(file));
for (int i = 0; i < ctr; i++) {
dateStamp[i] = s4.next();
}
return dateStamp;
}
catch (FileNotFoundException e){
}
return null;
}
//get time
public static String[] getTime(String file) {
//step 1:
// count the number of lines in the file
//step 2 - create the array and copy the elements in
int ctr = 0;
try {
Scanner s5 = new Scanner(new File(file));
while (s5.hasNextLine()) {
ctr++;
s5.nextLine();
}
String[] timeStamp = new String[ctr]; //creation
Scanner s6 = new Scanner(new File(file));
for (int i = 0; i < ctr; i++) {
timeStamp[i] = s6.next();
}
return timeStamp;
}
catch (FileNotFoundException e){
}
return null;
}
public static int getMax(int[] inputArray){
int maxValue = inputArray[0];
int maxLoc = 0;
for(int i=1;i < inputArray.length;i++){
if(inputArray[i] > maxValue){
maxValue = inputArray[i];
maxLoc = i;
}
}
return maxLoc;}}
as mentioned the files are now compressed and inside the jar and don't live on the file system
use something like InputStream in = this.getClass().getClassLoader().getResourceAsStream("SomeTextFile.txt");
look here for how to convert the inputStream to a String. or it seems that you can use a Scanner directly on the stream. you will need to know the char encoding
I need help, obviously. Our assignment is to retrieve a file and categorize it and display it in another file. Last name first name then grade. I am having trouble with getting a loop going because of the error "java.util.NoSuchElementException" This only happens when I change the currently existing while I loop I have. I also have a problem of displaying the result. The result I display is all in one line, which I can't let happen. We are not allowed to use arraylist, just Bufferedreader, scanner, and what i already have. Here is my code so far:
import java.util.;
import java.util.StringTokenizer;
import java.io.;
import javax.swing.*;
import java.text.DecimalFormat;
/*************************************
Program Name: Grade
Name: Dennis Liang
Due Date: 3/31/11
Program Description: Write a program
which reads from a file a list of
students with their Grade. Also display
last name, first name, then grade.
************************************/
import java.util.*;
import java.util.StringTokenizer;
import java.io.*;
import javax.swing.*;
import java.text.DecimalFormat;
class Grade {
public static void main(String [] args)throws IOException {
//declaring
String line = "";
StringTokenizer st;
String delim = " \t\n\r,-";
String token;
String firstname;
String lastname;
String grade;
String S69andbelow="Students with 69 or below\n";
String S70to79 ="Students with 70 to 79\n";
String S80to89= "Students with 80 to 89\n";
String S90to100= "Students with 90 to 100\n";
int gradeint;
double gradeavg = 0;
int count = 0;
File inputFile = new File("input.txt");
File outputFile = new File("output.txt");
FileInputStream finput = new FileInputStream(inputFile);
FileOutputStream foutput = new FileOutputStream(outputFile);
FileReader reader = new FileReader(inputFile);
BufferedReader in = new BufferedReader(reader);
Scanner std = new Scanner(new File("input.txt"));
Scanner scanner = new Scanner(inputFile);
BufferedWriter out = new BufferedWriter(new FileWriter(outputFile));
Scanner scan = new Scanner(S69andbelow);
//reading linev
line = scanner.nextLine();
st = new StringTokenizer(line, delim);
//avoiding selected characters
try {
while(st.hasMoreTokens()) {
firstname = st.nextToken();
lastname = st.nextToken();
grade = st.nextToken();
//storing tokens into their properties
gradeint = Integer.parseInt(grade);
//converting token to int
gradeavg = gradeavg + gradeint;
//calculating avg
count++;
//recording number of entries
if (gradeint <=69) {
S69andbelow = S69andbelow + lastname + " "
+ firstname + " " + "\t" + grade + "\n";
} // saving data by grades
else if (gradeint >= 70 && gradeint <= 79) {
S70to79 = S70to79 + lastname + " " + firstname
+ " " + "\t" + grade + "\n";
} // saving data by grades
else if (gradeint >= 80 && gradeint <=89) {
S80to89 = S80to89 + lastname + " " + firstname
+ " " + "\t" + grade + "\n";
} // saving data by grades
else {
S90to100 = S90to100 + lastname + " " + firstname
+ " " + "\t" + grade + "\n";
} // saving data by grades
}//end while
System.out.println(S69andbelow + "\n" + S70to79 + "\n"
+ S80to89 + "\n" + S90to100);
//caterorizing the grades
gradeavg = gradeavg / count;
//calculating average
DecimalFormat df = new DecimalFormat("#0.00");
out.write("The average grade is: "
+ df.format(gradeavg));
System.out.println("The average grade is: "
+ df.format(gradeavg));
Writer output = null;
output = new BufferedWriter(new FileWriter(outputFile));
// scanner.nextLine(S69andbelow);
//output.write(S69andbelow + "\n" + S70to79 + "\n"
// + S80to89 + "\n" + S90to100);
// output.close();
}
catch( Exception e ) {
System.out.println(e.toString() );
}
// Close the stream
try {
if(std != null )
std.close( );
}
catch( Exception e ) {
System.out.println(e.toString());
}
}
}
my input file looks like this:
Bill Clinton 85 (enter)
Al Gore 100 (enter)
George Bush 95 (enter)
Hillery Clinton 83(enter)
John McCain 72(enter)
Danna Green 87(enter)
Steve Delaney 76(enter)
John Smith(enter)
Beth Bills 60(enter)
It would help to point things out just in case I don't follow you all the way through.
An easy way of finding a problem in this would be to comment out most of the code and find out each step at a time. So start with being able to read the file. Then print to the screen. Then print the organized data to the screen. Finally print the organized data to the file.
This should be a fairly simple
// Calculating term frequency
System.out.println("Please enter the required word :");
Scanner scan = new Scanner(System.in);
String word = scan.nextLine();
String[] array = word.split(" ");
int filename = 11;
String[] fileName = new String[filename];
int a = 0;
for (a = 0; a < filename; a++) {
try {
System.out.println("The word inputted is " + word);
File file = new File(
"C:\\Users\\user\\fypworkspace\\TextRenderer\\abc" + a
+ ".txt");
System.out.println(" _________________");
System.out.print("| File = abc" + a + ".txt | \t\t \n");
for (int i = 0; i < array.length; i++) {
int totalCount = 0;
int wordCount = 0;
Scanner s = new Scanner(file);
{
while (s.hasNext()) {
totalCount++;
if (s.next().equals(array[i]))
wordCount++;
}
System.out.print(array[i] + " ---> Word count = "
+ "\t\t " + "|" + wordCount + "|");
System.out.print(" Total count = " + "\t\t " + "|"
+ totalCount + "|");
System.out.printf(" Term Frequency = | %8.4f |",
(double) wordCount / totalCount);
System.out.println("\t ");
}
}
} catch (FileNotFoundException e) {
System.out.println("File is not found");
}
}
This is my code to calculate the word count, total words and the term frequency of a text file containing text. The problem is i need to access the variable wordcount and totalcount outside of the for loop. But changing the place to declare the variable wordcount and totalcount changes the results too making it not accurate. Can someone help me on the variables so that i can get accurate results and also access the variables outside of the for loop ?
Simply declare them outside the loop, but keep assigning them to 0 inside the loop:
int totalCount;
int wordCount;
for ( ... ) {
totalCount = 0;
wordCount = 0;
...
}
// some code which uses totalCount and wordCount