Why does this code trigger an infinite loop? - java

I am writing some simple code to parse a file and return the number of lines but the little red box in eclipse won't go off so I assume I am triggering an infinite loop. Th Text file i am reading has only 10 lines...here's the code: What am I doing wrong?
import java.io.*;
import java.util.Scanner;
public class TestParse {
private int noLines = 0;
public static void main (String[]args) throws IOException {
Scanner defaultFR = new Scanner (new FileReader ("C:\\workspace\\Recommender\\src\\IMDBTop10.txt"));
TestParse demo = new TestParse();
demo.nLines (defaultFR);
int x = demo.getNoLines ();
System.out.println (x);
}
public TestParse() throws IOException
{
noLines = 0;
}
public void nLines (Scanner s) {
try {
while (s.hasNextLine ())
noLines++;
}
finally {
if (s!=null) s.close ();
}
}
public int getNoLines () {
return noLines;
}
}

You're not calling s.nextLine() in the while-loop:
should be:
while(s.hasNextLine()){
s.nextLine(); // <<<
noLines++;
}

You only check hasNextLine within your loop. This checks if another line is present but does not read it. Let it follow by nextLine and your code will work.
while(s.hasNextLine()){
s.nextLine();
noLines++;
}

Related

Catching results from a void method into an output file

I am new at Java so thank you for helping!
public static int convert (String value) {
int temp_convert = 0;
// Setting up new Scanner to read the User-input string
Scanner token = new Scanner(value);
// Take out the word "CONVERT"
String fnc = token.next();
// Get the temperature that needs to be converted
int temp = token.nextInt();
// Current unit of temperature
String type = token.next().toLowerCase();
if (type.equals("f")) {
temp_convert = (int) Math.round((temp - 32)/1.8);
System.out.println(temp_convert + "C");
} else if (type.equals("c")) {
temp_convert = (int) Math.round(1.8 * temp + 32);
System.out.println(temp_convert + "F");
}
return temp_convert;
}
I am trying to get the print result from this method into an output file using PrintStream. I need whatever is lines printed in this method to be print out into the output file. How can I do this? This is the code I have so far but it doesn't produce anything in the .txt file yet.
public static void readFile (Scanner console, String file_input) throws FileNotFoundException {
// Setting up new Scanner to scan the file
Scanner input = new Scanner (file_input);
// Prompt user for output file's name
System.out.print("Output file name: ");
String name_output = console.next();
PrintStream file_output = new PrintStream(new File(name_output));
System.out.println("YazLang program interpreted and output to .txt file!");
System.out.println();
while (input.hasNext()) {
String value = input.nextLine().toLowerCase();
if (value.startsWith("convert")) {
int concert_temp = convert(value);
file_output.println(concert_temp);
} else if (value.startsWith("range")) {
range(value);
} else if (value.startsWith("repeat")) {
repeat(value);
}
}
}
Why don't you change signature of convert method to return int?
public static int convert (String value) {
Scanner token = new Scanner(value);
// ...
return value;
}
And then write result to file in readFile method like this:
public static void readFile (Scanner console, String file_input) throws FileNotFoundException {
// omitted..
while (input.hasNext()) {
String value = input.nextLine().toLowerCase();
if (value.startsWith("convert")) {
int concert_temp = convert(value);
file_output.println(concert_temp);
} else if (value.startsWith("range")) {
// here
int concert_temp = range(value);
file_output.println(concert_temp);
} else if (value.startsWith("repeat")) {
repeat(value);
}
}
}
you can use System.setOut() (https://www.tutorialspoint.com/java/lang/system_setout.htm)
Insert this line after line 7 in your readFile method:
System.setOut(file_output);
There are two options:
Define the PrintStream in the outer most function, then pass it to whichever function you need. Proceed to write to file using PrintStream::print... method.
Define a wrapper class that will write to both stream:
public class DuplexPrinter {
private final PrintStream printStream;
public DuplexPrinter(PrintStream printStream) {
this.printStream = printStream;
}
public void println(String line) {
System.out.println(line);
printStream.println(line);
}
public void close() {
printStream.close();;
}
}
Init printer:
DuplexPrinter printer = new DuplexPrinter(file_output);
Now replace every call to System.out.println with:
printer.println()
Using third party library. For example TeeOutputStream

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();

buffered reader input into char array

I want to take an input from a txt file and put all the characters to the array so I can perform on it some regex functions. But when I try to read the array with a single loop to check it, nothing appears. What is wrong here?
import java.io.BufferedReader;
import java.io.FileReader;
public class Main
{
public static void main(String[] args)
{
try
{
Task2.doTask2();
}catch(Exception e){};
}
}
class Task2
{
public static void doTask2() throws Exception
{
FileReader fr = new FileReader("F:\\Filip\\TextTask2.txt");
BufferedReader br = new BufferedReader(fr);
char[] sentence = null;
int i;
int j = 0;
while((i = br.read()) != -1)
{
sentence[j] = (char)i;
j++;
}
for(int g = 0; g < sentence.length; g++)
{
System.out.print(sentence[g]);
}
br.close();
fr.close();
}
}
You can read a file simply using File.readAllBytes. Then it's not necessary to create separate readers.
String text = new String(
Files.readAllBytes(Paths.get("F:\\Filip\\TextTask2.txt"))
);
In the original snippet, the file reading function is throwing a NullPointerException because sentence was initialized to null and then dereferenced: sentence[j] = (char)i;
The exception was swallowed by the calling function and not printed, which is why you're not seeing it when you run the program: }catch(Exception e){};
Instead of swallowing the exception declare the calling function as throwing the appropriate checked exception. That way you'll see the stack trace when you run it: public static void main(String[] args) throws IOException {
You are using wrong index , use "g" instead of "i" here.:
System.out.println(sentence[g]);
Also, the best and simplest way to do this is:
package io;
import java.nio.file.*;;
public class ReadTextAsString
{
public static String readFileAsString(String fileName)throws Exception
{
return new String(Files.readAllBytes(Paths.get(fileName)));
}
public static void main(String[] args) throws Exception
{
String data = readFileAsString("F:\\Filip\\TextTask2.txt");
System.out.println(data); //or iterate through data if you want to print each character.
}
}

How read and print a two column text file containing integers and look for a specific value in the first column?

I'm new to Java and would appreciate any assistance to solve the following problem.
I would like the java program to read and print a two column (integer or double) text file and search for a value in the first column that matches with another parameter within the java code. If the match is found, to print out the corresponding value on the second column. I wrote the following code which can read and print the data in console but I'm unable to use this data in the next code to search for a value in the first column that matches with another parameter. please help,here is my code:
import java.io.File;
import java.util.Scanner;
public class readfile {
private Scanner s;
public static void main(String[] args) {
readfile r = new readfile();
r.openFile();
r.readFile();
r.closeFile();
}
public void openFile() {
try {
s = new Scanner (new File("filename.txt"));
}catch(Exception e) {
System.out.println("file not found ");
}
}
public void readFile() {
while(s.hasNext()) {
String a = s.next();
String b = s.next();
System.out.printf("%s %s\n",a, b);
}
}
public void closeFile() {
s.close();
}
}
// here is the problem!
double a = 0;
double b = 0;
if (para == a[i]) {
System.out.println("param =" + a[j]);
}else {
System.out.println("It is out of range ");
}

Printing a returning value

I've just started with Java, and so far been only playing around solving problems online, where you're not supposed to write the whole functional of a program, but only adjust a few lines of code to the already organized code.
However, I'm still struggling to organize my code in a compiling program in IntelliJ Idea, getting confused at,e.g. how methods invocations must be properly written.
Here's what I'm getting stuck with: an example from codingbat.com:
- Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo".
I've come up with a solution online, but now I wanna run it in Idea, with main method, with Scanner/BufferedReader input from console etc. Looks like I'm missing something...
import java.util.Scanner;
public class Bat
{
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
printString();
}
public String stringBits(String str) {
String result = "";
for (int i = 0; i<str.length();i += 2) {
result += str.substring(i, i+1);
}
return result;
}
public static void printString () {
System.out.println(result);
}
}
I ask your help to solve it out. What to do to make it:
Read a word from a console;
create a new string;
print it out.
Two alternatives:
make stringBits static
create an instance of the class Bat and invoke the member method
First solution - easy, not much to change
import java.util.Scanner;
public class Bat {
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
printString(stringBits(str));
}
public static String stringBits(String str) {
String result = "";
for (int i = 0; i < str.length();i += 2) {
result += str.substring(i, i + 1);
}
return result;
}
public static void printString (String string) {
System.out.println(string);
}
}
Second solution - a bit more advances
import java.util.Scanner;
public class Bat {
private String string;
public Bat(String string) {
this.string = string;
}
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
Bat bat = new Bat(str);
bat.printStringBits();
}
private String stringBits() {
String result = "";
for (int i = 0; i < string.length(); i += 2) {
result += string.substring(i, i + 1);
}
return result;
}
public void printStringBits() {
System.out.println(stringBits());
}
}
Your result variable is only accessible from within the "stringBits" method. Since the method returns a string you can do the following to print it:
System.out.println(stringBits(string)); //Call in main method in place of printString();
Edited: My code wasn't a working example. Note that stringBits has to be a static method in order to work.

Categories

Resources