Infinite loop with integer text file reading in Java - java

Hi I have a fairly simple program but I am having trouble understanding why I have an inifite loop when I am running it. The file I am reading from has 10 integers in it. I am using Eclipse Juno and the output in the console is counting by 1 starting at 281363 infinitely. How can I fix this? Thanks in advance.
import java.util.*;
import java.io.*;
public class TestScoreAnalyzer
{
public static void main(String[] args) throws FileNotFoundException
{
int arraySize = 0;
File file = new File("C:\\Users\\Quinn\\workspace\\CPS121\\src\\
additionalAssignments\\scoresSample.txt");
Scanner inputFile = new Scanner(file);
while(inputFile.hasNextInt())
{
arraySize++;
System.out.println(arraySize);
}
inputFile.close();
}
}

You're never calling inputFile.nextInt() - you're only calling hasNextInt(), which doesn't actually advance the location in the file. You probably want:
while (inputFile.hasNextInt())
{
arraySize++;
System.out.println(arraySize);
int value = inputFile.nextInt();
// Do something with the value?
}

http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html#hasNextInt()
Scanner isnt moving on - its just saying the next one is an int (looks at the same one each time)

Related

How to solve NoSuchElement in java?

It works well on Intellij.
However, NoSuchElement appears on the algorithmic solution site.
I know that NoSuchElement is a problem caused by trying to receive it even though there is no value entered.
But I wrote it so that the problem of NoSuchElement doesn't occur.
Because given str, the for statement executes. Given "END", the if statement is executed. And because it ends with "break;".
I don't know what the problem is.
Algorithm problem: Arrange the reverse sentence correctly.
My code for algorithmic problems
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
while(true) {
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
if(str.equals("END")){
break;
}
for (int i = str.length()-1; i >=0; i--) {
System.out.print(str.charAt(i));
}
System.out.println();
}
}
}
Output
!edoc doog a tahW
erafraw enirambus detcirtsernu yraurbeF fo tsrif eht no nigeb ot dnetni eW
END
Expected
What a good code!
We intend to begin on the first of February unrestricted submarine warfare
This happens when there is no input at all, for example when you hit Ctrl + d or run your code like echo "" | java Main.java.
To avoid this, check that the Scanner actually has input before trying to grab the next line. Pull scan out of the loop, there is no point to create a new Scanner for each line anyway. Then use hasNext to see if there is input.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
String str = scan.nextLine();
if(str.equals("END")){
break;
}
for (int i = str.length()-1; i >=0; i--) {
System.out.print(str.charAt(i));
}
System.out.println();
}
}
}

Using BufferedWriter to get input from the user and write it to a file

I just started using Java, so sorry if I ask some very simple questions. I basically have to get the user to continuously integers, and once they enter a negative number, the loop will exit. The code I have written so far does not seem to be able to write the input I get from the user to the file I created, morescores. When I try opening the file or calling it from the main method, it's blank. I've tried searching it up on google, youtube, and on stackoverflow but nothing seems to be working. I"ll appreciate any help I can get :)
package bufferedreader;
import java.io.*;
import java.util.Scanner;
public class BufferedReader {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
writeToFile("morescores");
processFile("morescores");
}
public static void writeToFile (String filename) throws IOException {
BufferedWriter outputWriter = new BufferedWriter (new FileWriter ("morescores.txt"));
int score = 1;
while (true) {
Scanner reader = new Scanner(System.in);
System.out.print ("Enter a number: ");
score = reader.nextInt();
if (score < 0) {
break;
} else {
outputWriter.write(score);
outputWriter.newLine();
}
}
outputWriter.flush();
outputWriter.close();
}
public static void processFile2 (String filename) throws IOException {
java.io.BufferedReader inputReader = new java.io.BufferedReader(new InputStreamReader (new FileInputStream ("morescores.txt")));
String line;
while ((line = inputReader.readLine()) != null) {
System.out.println (line);
}
inputReader.close();
}
}
UPDATE: I fixed the problem haha turns out I was trying to print an integer when it could only be a string. I actually have a followup question, I also need to find the average of all the numbers the user inputs. How would I do that? How can I write a code so that the program knows how many times the user inputs a value I actually have a followup question, I also need to find the average of all the numbers the user inputs. How would I do that? How can I write a code so that the program knows how many times the user inputs a value
Convert your int to a String before writing to your file so
outputWriter.write(score);
would be:
outputWriter.write(String.valueOf(score));
if you are wondering why it has to be converted first look at the doc:
https://docs.oracle.com/javase/7/docs/api/java/io/Writer.html#write(int)
you'll see that it doesn't write the int but the character represented by the int
If you pass int value to the write method of BufferedWriter class, then it will be consider as character instead of number, therefore with the current code you have written whatever positive number you are providing will get converted to valid char value and then it will be written into the file.
In order to achieve what you are asking for you need to convert your int value to string before writing it to file and to do that you can use any of the below methods :
String.valueOf(score)
Integer.toString(score)

Java Program that reads survey results from a txt file and outputs the frequency of each survey answer

I have to code two programs. The first program outputs a survey where the user must input a rating between 1-5 (1 being a low grade and 5 being the highest) and then their name. The program then sends whatever the user typed to a txt file called responses.txt.
The second program (the one I'm having trouble with) is supposed to read the data from the text file then output a table that shows the frequency that each rating was typed. For example:
Rating Frequency
1 7
2 4
3 2
4 0
5 0
The way I set it up is I have 2 files, 1 java file that's supposed to do everything I mentioned above. The second java file is just used to test the program by calling all the methods from the fore mentioned first java file.
I have no problems compiling any of the files, so I'm good in terms of that.
However, when I try to run the test file, I get the following error:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.utiol.Scanner.nextInt(Scanner.java:2076)
at ReadResonseFile.readRecords(ReadResponseFile.java:43)
at ReadResponseFileTest.main(ReadResponseFileTest.java:8)
From what I can see, the problem seems to be with the readRecords method. My question is what can I do to fix this and if I'm leaving anything out that needs to be in the code, what is it? Any help would very much be appreciated!
Here's what I have so far
ReadResponseFile.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadResponseFile {
private Scanner input;
int[] frequency= new int[5];
public void openFile()
{
try {
input = new Scanner(new File("responses.txt"));
}//end try
catch (FileNotFoundException fileNotFoundException) {
System.err.println("Error opening file.");
System.exit(1);
}//end catch
}//end method openFile
public void readRecords()
{
SurveyResponseRecord record = new SurveyResponseRecord();
System.out.printf("%-10s%-12s\n", "Rating", "Frequency");
while (input.hasNext()) {
record.setRating(input.nextInt());
frequency[0] = 0;
frequency[1] = 0;
frequency[2] = 0;
frequency[3] = 0;
frequency[4] = 0;
System.out.printf("%-10s\n", record.getRating());
}//end while
}//end method readRecords
public void closeFile()
{
if (input != null)
input.close();
}//end method closeFile
}//end class ReadResponseFile`
ReadResponseFileTest.java
public class ReadResponseFileTest
{
public static void main( String[] args)
{
ReadResponseFile application = new ReadResponseFile();
application.openFile();
application.readRecords();
application.closeFile();
}//end main
}//end class ReadResponseFileTest
For input values while executing your Java-programm, please use a GUI or use the System.in Scanner.
If you only want to read the TXT File, use a BufferedReader and read the File line by line by using
while((yourStringName=bufferedReader.readLine)!=null) {
System.out.println(yourStringName);
//What you wanna do
}

Why Does the following program terminate without an error

Why the following program terminate without producing any thing? MyData.txt file is saved in the same directory.
import java.util.Scanner;
import java.io.*;
public class MyIO
{
public static void main (String[] args) throws IOException
{
int num, square;
Scanner scan = new Scanner( "MyData.txt"); // connect a Scanner to the file
try{
while(scan.hasNextInt()) // is there more data to process?
{
num = scan.nextInt();
square = num*num ;
System.out.println("The square of " + num + " is " + square);
}
} finally{
scan.close();
}
}
}
Are you expecting integers from your MyData.txt file only? If the first value of the file isn't an integer, this will not enter the while loop.
It may be possible that you've skipped a line in your code or something. Can we have a look at your MyData.txt file? (or at least an example)
Additionally, you do not need to declare the fields 'num' and 'square' outside of your loop, if you want to do some cleaning up, unless you plan on reusing them later..?

Debugging using console Input

How one would be able to debug the Java program using ecllipse IDE which takes the input using scanner. I have search this on google but doesn't find any appropriate solution. The problem is that I was stuck into an null pointer exception while reading the input , so I want to debug my program.
This is my program...
package p;
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int T = in.nextInt();
int[][] ar = new int[T][];
for(int i=0;i<T;i++){
int n;
{
n = in.nextInt();
}
for(int j=0;j<n;j++)
{
ar[i][j]=in.nextInt(); /*null pointer exception occurs here*/
}
}
for(int i=0;i<T;i++)
{ int count=0,i1,k;
for(int j=1;j<ar[i].length;j++)
{
k=ar[i][j];
for(i1=j-1; i1>=0 && k<ar[i][i1]; i--)
ar[i][i1+1]=ar[i][i1];
ar[i][i1+1]=k;
count++;
}
System.out.println(count);
}
}
}
You never say(by initializing) how many cols will ar[i][j] will have (so accessing those uninitialized memory block surely gives NullPointerException
do this for all i rows
ar[i] = new int[colSize]
check this link as well
Check out a tutorial on debugging using eclipse.
You need to enter debugging mode after setting some break points. Break points are spots in your code you want the debugger to stop so you can view what's currently stored in various variables, etc.
Check the javadoc for Scanner and use the hasNext() methods to make sure it has the input you expect
Just put a break point where you want, then run it with Debug .It does not matter programme step contains Scanner or not. Even if you come across scanner statemenet, you just type a line on concole input, then enter. Programme will continue.

Categories