Output is not coming out correctly - java

The goal of this code is to read a file and add numbers to the end of every {(curly bracket) but the file does not output each line like it does in the file but it out puts it into one entire line. where do I put a System.out.println statement. I tried every where and it keeps repeating it
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
readFile();
}
public static void readFile() { // Method to read file
Scanner inFile = null;
String out = " ";
try {
Scanner input = new Scanner(System.in);
System.out.println("enter file name");
String filename = input.next();
File in = new File(filename); // ask for the file name
inFile = new Scanner(in);
int count = 0;
while (inFile.hasNextLine()) { // reads each line
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
char ch = line.charAt(i);
out = out + ch;
if (ch == '{') {
count = count + 1;
out = out + " " + count + " ";
} else if (ch == '}') {
out = out + " " + count + " ";
if (count > 0) {
count = count - 1;
}
}
}
}
System.out.println(out);
} catch (FileNotFoundException exception) {
System.out.println("File not found.");
}
inFile.close();
}
}

where do I put a System.out.println statement
The entire output is built in a single string that is not printed until the end, so adding System.out.println statements in the line loop won't help. You can add line breaks to the string by doing:
out += "\n";
Or, at the end of the body of your line loop, print the current line, and reset the buffer for the next line:
System.out.println(out);
out = "";
Using a String for the output buffer is not efficient by the way. String is immutable, so every + statement is copying and duplicating all of the previous characters to create a new object, every time. Consider declaring out as a StringBuilder rather than a String. Then you can add to it with the .append() method and it will not copy all the text every time because a StringBuilder is mutable.

Related

Program that reads file input and displays proportion of the length of the letter and so on

I have an assignment due two days and I have been trying a lot of days to do this, but I am burned, tried to come back to it, still no progress.
THE ASSIGNMENT is the following:
Java program that computes the above statistics from
any text file. Here’s what it might look like in action:
Name of the input file: example.txt
The proportion of 1-letter words: 3.91% (74 words)
The proportion of 2-letter words: 18.52% (349 words)
The proportion of 3-letter words: 24.24% (456 words)
The proportion of 4-letter words: 19.80% (374 words)
The proportion of 5-letter words: 11.33% (212 words)
…
…
The proportion of 12-letter words: 0.45% (8 words)
Proportion of 13- (or more) letter words: 0.51% (9 words)
Now In order to do this, I thought to divide my program into three methods: Read the method, count the letters and distinguish them and finally display it as the example above. Now that I said that, here is my code right now:
/*like make smaller functions
where each function has one task
like to loop through the file and return an array of words
then use that as input to another function whose purpose is to count the
letters
and then pass that array into a function for printing that.
*/
import java.io.*;
import java.util.Scanner;
class Autorship {
public static void main(String[] args) {
try {
System.out.println("Name of input file: ");
Scanner sc1 = new Scanner(System. in );
sc1.useDelimiter("[^a-zA-Z]");
String fname = sc1.nextLine();
sc1.close();
sc1 = new Scanner(new FileReader(fname));
sc1.useDelimiter("[^a-zA-Z]");
String line;
System.out.println(WordCount(fname, sc1));
} catch (FileNotFoundException e) {
System.out.println("There was an error opening one of the files.");
}
}
public static int WordCount(String fname, Scanner sc1) {
int wordCount = 0;
int lineCount = 0;
while (sc1.hasNextLine()) {
String line;
line = sc1.nextLine();
lineCount++;
String[] strings = line.split(" ");
int[] counts = new int[14];
for (String str: strings)
if (str.length() < counts.length) counts[str.length()] += 1;
System.out.println("This is counts length: " + counts.length);
for (int i = 1; i < counts.length; i++)
System.out.println(i + " letter words: " + counts[i]);
}
return 0;
}
}
Now please I do not want the answer, as that would be plagiarism, and I am not that kind of person, I just want a bit of help to continue to progress, I'm so stuck right now, thanks ^^
Here is an adjusted and working version. I commented the lines I edited.
Your code wasn't that bad and it was working quite well. The only problem you had was that you've printed out the letter counts inside the while-loop instead of doing it outside. Therefore it repeated with every new line that was read from the file.
Please note: I strongly recommend to always use curly brackets even though Java syntax allows to not use them with if-statements and for-loops if they're followed by only one line of code to execute. But not using them makes the code harder to read and error prone.
public static void main(String[] args) {
try {
System.out.println("Name of input file: ");
Scanner sc1 = new Scanner(System. in );
sc1.useDelimiter("[^a-zA-Z]");
String fname = sc1.nextLine();
sc1.close();
sc1 = new Scanner(new FileReader(fname));
sc1.useDelimiter("[^a-zA-Z]");
String line;
System.out.println("WordCount: " + WordCount(fname, sc1)); // edited
} catch (FileNotFoundException e) {
System.out.println("There was an error opening one of the files.");
}
}
public static int WordCount(String fname, Scanner sc1) {
int wordCount = 0;
int lineCount = 0;
final int MAXIMUM_LENGTH = 14; // edited. Better use a constant here.
int[] counts = new int[MAXIMUM_LENGTH]; // edited. Constant applied
while (sc1.hasNextLine()) {
String line = sc1.nextLine();
// increment line count
lineCount++;
String[] strings = line.split(" ");
// increment word count
wordCount += strings.length; // added
// edited. curly brackets and constant MAXIMUM_LENGTH
for (String str: strings) {
if (str.length() < MAXIMUM_LENGTH) {
counts[str.length()] += 1;
}
}
}
// edited / added. finally show the results
System.out.println("maximum length: " + MAXIMUM_LENGTH);
System.out.println("line count: " + lineCount);
System.out.println("word count: " + wordCount);
// edited. moved out of the while-loop. MAXIMUM_LENGTH applied.
for (int i = 1; i < MAXIMUM_LENGTH; i++) {
System.out.println(i + " letter words: " + counts[i]);
}
// edited.
return wordCount;
}

Outputting to a closed stream?

So I fixed my program but the problem is that after replacing all the blank spaces with tildes i have to output the text to a file that has been closed. How would I re-open the file for output and input something in?
//Name: Allen Li
//Program file: Vowels.Java
//Purpose: Using File IO, read a file's input and output this text to a new text file
//When outputting, all blank spaces will be changed to tildes and there will be a count of each vowel(AEIOU)
import java.util.Scanner; //input
import java.io.File; //IO
import java.io.IOException; //IO exception class
import java.io.FileWriter; //file output
import java.io.FileReader; //file input
import java.io.FileNotFoundException; //if file isnt found, file not found class
public class Vowels { //class
public static void main(String[] args) { //main method
try { //try block
FileReader poetry = new FileReader("poetry.txt");
FileWriter dentist = new FileWriter(
"LI_ALLEN_dentist.txt");
int a;
while ((a = poetry.read()) != -1) {
dentist.write(a);
System.out.print((char) a); //print the file to the monitor
}
poetry.close();
dentist.close();
Scanner inFile = new Scanner(new File(
"LI_ALLEN_dentist.txt"));
int numOfVowelsA = 0; //count #s of A/E/I/O/U vowels
int numOfVowelsE = 0;
int numOfVowelsI = 0;
int numOfVowelsO = 0;
int numOfVowelsU = 0;
while (inFile.hasNext()) {
String sentence = inFile.next() /* ("\\S+") */;
for (int i = 0; i <= sentence.length() - 1; i++) {
if (sentence.toLowerCase().charAt(i) == 'a') {
numOfVowelsA++;
}
if (sentence.toLowerCase().charAt(i) == 'e') {
numOfVowelsE++;
}
if (sentence.toLowerCase().charAt(i) == 'i') {
numOfVowelsI++;
}
if (sentence.toLowerCase().charAt(i) == 'o') {
numOfVowelsO++;
}
if (sentence.toLowerCase().charAt(i) == 'u') {
numOfVowelsU++;
}
}
}
System.out.println();
System.out.println("There are " + numOfVowelsA
+ " A vowels in this file of text");
System.out.println("There are " + numOfVowelsE
+ " E vowels in this file of text.");
System.out.println("There are " + numOfVowelsI
+ " I vowels in this file of text.");
System.out.println("There are " + numOfVowelsO
+ " O vowels in this file of text.");
System.out.println("There are " + numOfVowelsU
+ " U vowels in this file of text. ");
Scanner tildes = new Scanner(new File(
"LI_ALLEN_dentist.txt"));
while (tildes.hasNext()) {
String replace = tildes.nextLine();
replace = replace.replaceAll(" ", "~");
System.out.println();
System.out.print(replace);
}
} catch (FileNotFoundException i) {
System.out.println("The file you are trying to use as input is not found. " + i);
} catch (IOException i) {
System.out.println("There is an issue with the input or output file. " + i);
}
}
}
You didn't close inFile. Close inFile first and then you are able to open it again in tildes.
Close it before Scanner tildes = new Scanner(...); line.

Error: The local variable jars may not have been initialized

Further down it keeps saying the tow local variable cant be initialized when they are. Cant seem to find the problem
import java.io.*;
import java.util.Scanner; //Scanner method
public class Popcorn1 {
public static void main(String args[]) throws FileNotFoundException{
printHeader();
File file;
do {
Scanner in = new Scanner (System.in);
System.out.println("Enter the the file name");
String filename = in.next();
file = new File(filename);
} while(!file.exists());
FileReader inputFile = new FileReader (file);
Scanner inFile = new Scanner(inputFile);
System.out.println(" PopCorn Co-op");
System.out.println(" Production in Hundreds");
System.out.println(" of Pint Jars Per Acre");
System.out.println(" 1 2 3 4 5 6");
System.out.println("Farm Name ---|---|---|---|---|---|");
System.out.println();
// Printing out title and table header for reader to easily read data
String errorMSG = " ";
while (inFile.hasNextLine()) {
String inputLine = inFile.nextLine();
//System.out.print(inputLine);
int position;
String name;
int jars;
double acres;
position = inputLine.indexOf(','); //Get the Location of the comma to use as a delimiter
name = inputLine.substring(0,position); //Everything to the left of the comma is the farm name
System.out.printf("%-31s", name);
inputLine = inputLine.substring(position + 2,inputLine.length()); //rest of the string
Scanner line = new Scanner(inputLine);
if(line.hasNextDouble())
acres = line.nextDouble();
else
errorMSG += "There is missing data";
if(line.hasNextInt())
jars = line.nextInt();
else
errorMSG += "There is missing data";
int starsConversion =(int)(jars/acres/25); **<-------- problem is here**
for (int i = 1; i < starsConversion; i++) {
if( i == 20)
System.out.print("#");
else
System.out.print("*");
}
if (starsConversion < 20) {
for (int i = 1; i < (21 - starsConversion); i++) {
System.out.print(" ");
}
System.out.print("|");}
System.out.println(); //go to the next line
}
System.out.println(errorMSG);
}
}
There is an execution path where jars was never initialized, specifically, if line.hasNextInt() is false.
To use it, you must make sure jars is always initialized to something. You can initialize it to say 0 before the if.
What happens if if(line.hasNextInt()) is false on the first run?

storing a sentence from a file to a string java

How can I store a sentence from a file to a string, and then store the next line, which is made up of numbers, to a string?
When I use hasNextline or nextLine, none of it works. I am so confused.
Scanner kb = new Scanner(System.in);
String secretMessage = null;
String message, number = null;
File file = new File(System.in);
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext())
{
message = inputFile.nextLine();
number = inputFile.nextLine();
}
System.out.println(number + "and " + message);
You're looping over the entire file, overwriting your message and number variables, and then just printing them once at the end. Move your print statement inside the loop like this so it will print every line.
while(inputFile.hasNext())
{
message = inputFile.nextLine();
number = inputFile.nextLine();
System.out.println(number + "and " + message);
}
One suggestion I would have for reading lines from a file would be to use the Files.readAllLines() method.
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class Display_Summary_Text {
public static void main(String[] args)
{
String fileName = "//file_path/TestFile.txt";
try
{
List<String> lines = Files.readAllLines(Paths.get(fileName), Charset.defaultCharset());
String eol = System.getProperty("line.separator");
for (int i = 0; i <lines.size(); i+=2)
{
System.out.println(lines.get(i).toString() + "and" + lines.get(i+1) + eol);
}
}catch(IOException io)
{
io.printStackTrace();
}
}
}
Using this set up, you can also create a stringBuilder and Writer to save the output to a file very simply if needed.

How to resolve '.class' expected error? [duplicate]

This question already has an answer here:
What does "error: '.class' expected" mean and how do I fix it
(1 answer)
Closed 3 years ago.
Currently I have an error - '.class' expected - on line 40. Any help is hugely appreciated.
import java.io.*; // For File class and FileNotFoundException
import java.util.Scanner; //For the Scanner class
import javax.swing.JOptionPane; // For the JOptionPane class
/**
* Write a description of class PartB here.
*
* #Hubble, Kieran
* #Version 0.1
*/
public class PartB
{
public static void main(String[] args) throws FileNotFoundException
{
File file; //for file input
Scanner inputFile; //for file input
String fileName; //to hold a file name
String paragraph; //to extract the letter frequencies
//get a file name from the user.
fileName = JOptionPane.showInputDialog("enter " + " the name of the file");
//attempt to open the file.
try
{
file = new File(fileName);
inputFile = new Scanner(file);
JOptionPane.showMessageDialog(null, "the file was found.");
// read the input file, processing data one line at a time
while(inputFile.hasNext())
{
String str = inputFile.nextLine();
System.out.println(str);
}
//create an Output file
PrintWriter outputFile = new PrintWriter("crackedcode.txt");
while(paragraph.length() > 0)
// error is occurring on the next line (line 40)
int[]; letterCount = new int[26];
for (int count = 0; count < paragraph.length; count++) {
String current = paragraph[count];
char[] letters = current.toCharArray();
}
for (int count2 = 0; count2 < letters.length; count2++) { char lett = letters[count2]; if ( (lett >= 'A') & (lett <= 'Z') ) {
letterCount[lett - 'A']++;
}
}
for (char count = 'A'; count <= 'Z'; count++) {
System.out.print(count + ": " +
letterCount[count - 'A'] +
" ");
}
System.out.println();
// close the input file
inputFile.close();
}
catch (FileNotFoundException e)
{
JOptionPane.showMessageDialog(null, "file not found.");
}
JOptionPane.showMessageDialog(null, "done.");
System.exit(0); //terminate program
}
}
Remove the semicolon
int[]; letterCount = new int[26];
should be
int[] letterCount = new int[26];
Also, You need to wrap the block of the while (from the line above it) with {}

Categories

Resources