I am trying to calculate the number of lines in a file using a Scanner in the below code but for some reason I am stuck in an infinite loop.
import java.util.*;
import java.io.*;
public class FileCount{
File fileCount;
public FileCount(String name_of_file){
fileCount = new File(name_of_file);
}
public static void main(String args[]) throws FileNotFoundException{
FileCount f = new FileCount("test.txt");
System.out.println(f.num_of_records());
}
public int num_of_records() throws FileNotFoundException{
Scanner handler = new Scanner(this.fileCount);
int num_of_lines = 0;
for(int i=0; handler.hasNextLine(); i++){
num_of_lines = i;
}
handler.close();
return num_of_lines;
}
}
You check that it has a next line, but then you never tell it to do anything with that line. Something like this should work.
for(int i=0; handler.hasNextLine(); i++){
handler.nextLine();
num_of_lines = i;
}
As an alternative to Scanner, you may consider using BufferedReader instead:
BufferedReader reader = new BufferedReader(new FileReader("your_file_name"));
int num_of_lines;
for (num_of_lines=0; reader.readLine()!=null; num_of_lines++) {}
You don't need a Scanner or a BufferedReader either. You can do it in about three lines with a LineNumberReader. First seek to the file size, then get the current line number.
Related
Whenever I run my code, it says Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0. I make sure that my I value isn't exceeded but it still says it. Can you guys help me?
I made sure that nothing in my for loop exceeded my I value but it seems to be something else that is triggering the problem.
And by the way, sorry if my formatting is incorrect. This is my first time using stack overflow.
One more thing, my compiler says that the error is in line 17(inside my for loop).
Here's my code:
import java.io.*;
public class Main {
public static int length1;
public static String numbers;
public static String str;
public static void main(String[] args)throws IOException{
System.out.println("");
System.out.println("Hello world!");
char[] nums = new char[length1];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Type in numbers with spaces in them.");
numbers = br.readLine();
System.out.println("");
for(int i = 0; i < numbers.length(); i++){
nums[i] = numbers.charAt(i);
System.out.println(numbers.charAt(i));
}
length1 = numbers.length();
}
}
so your problem is at this line...
char[] nums = new char[length1];
length1 is does not have a value.
Try This...
import java.io.*;
public class Main {
public static int length1;
public static String numbers;
public static String str;
public static void main(String[] args) throws IOException {
System.out.println("");
System.out.println("Hello world!");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Type in numbers with spaces in them.");
numbers = br.readLine();
char[] nums = new char[numbers.length()];
System.out.println("");
for (int i = 0; i < numbers.length(); i++) {
nums[i] = numbers.charAt(i);
System.out.println(numbers.charAt(i));
}
}
}
The code is supposed to read an array of strings from a file then print it out. I'm not sure what is wrong with the code.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class program2 {
public static void main(String[] args) throws IOException {
//PriorityQueue<String> q = new PriorityQueue<String>();
//file that contains strings
File file = new File("infix.txt");
Scanner scnf = new Scanner(file);
// array count
int arycnt = 0;
// gets the count of the array in the file
while(scnf.hasNextLine()){
arycnt++;
scnf.next();
}
// creates array
String[] letter = new String[arycnt];
//reads in array from file
Scanner scnf2 = new Scanner(file);
for(int i = 0; i<arycnt ;i++){
letter[i] = scnf2.next();
}
// suppose to print all of the array
for (int i = 0;i < letter.length;i++){
System.out.println(letter[i]);
}
}
}
You are mixing up between nextLine and next. Replace your hasNextLine() with hasNext() and you should be OK.
So I was solving this Question on HackerRank (Project Euler Q1) link here, and have used the following code to solve it
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) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
int T = 0;
ArrayList<Integer> N = new ArrayList<Integer>();
String[] Input = args;
if (args.length>1){
T = Integer.parseInt(args[0]);
if(T<1||T>Math.pow(10,6))
System.exit(0);
}
if (args.length-1 == T){
for (int i=1;i<args.length;i++){
N.add(Integer.parseInt(args[i]));
int sum3=0,sum5=0,sum15=0;
int count=0;
while (count<N.get(i-1)){
sum3+=count;
count+=3;
}
count =0;
while (count<N.get(i-1)){
sum5+=count;
count+=5;
}
count =0;
while (count<N.get(i-1)){
sum15+=count;
count+=15;
}
N.set(i-1,(sum3+sum5-sum15));
}
}
for(int j=0;j<N.size();j++)
System.out.println(N.get(j));
}
}
This gives me the following output on an IDE :
23
2318
While Inputting :
2
10
100
And this matches the expected output on HackerRank, but however When I use this code on the website, It says :
Input (stdin)
2
10
100
Your Output (stdout)
~ no response on stdout ~
Expected Output
23
2318
Compiler Message
Wrong Answer
One thing I could observe was I couldn't print anything from inside a loop on HackerRank. What would the solution to this be?
You're not reading from STDIN the way HackerRank wants you to. Instead of getting your input from args, you should be doing this kind of thing:
Scanner sc = new Scanner(System.in);
int numberOfTestCases = sc.nextInt();
and so on.
I just ran this code, compiled fine and submitted it.
import java.io.*;
public class Solution{
public static void main(String[] args) throws IOException
{
//Input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
int[] N = new int[T];
for(int t = 0; t < T; N[t++] = Integer.parseInt(br.readLine())){
}
br.close();
br = null;
//Solve
long[] V = new long[T];
for(int t = 0; t < T; ++t){
int n = N[t] - 1;
V[t] = 3*nSum(n/3) + 5*nSum(n/5) - 15*nSum(n/15);
}
//Print
StringBuilder sb = new StringBuilder();
for(int t = 0; t < T; sb.append(V[t++]).append("\n")){
}
System.out.print(sb);
}
public static long nSum(int n){
long v = n;
return (v*v + v) >> 1;
}
}
I had the same problem with a php code and I used return instead of echoing for your case replace sout with return
import java.io.*;
import java.util.*;
import java.text.*;
public class textFile {
public static void main(String args[]) throws IOException {
Scanner sf = new Scanner(new File("C:\\temp_Name\\DataGym.in.txt"));
int maxIndx = -1;
String text[] = new String[1000];
while (sf.hasNext()) {
maxIndx++;
text[maxIndx] = sf.nextLine();
}
sf.close();
double average[] = new double[100];
for (int j = 0; j <= maxIndx; j++) {
Scanner sc = new Scanner(text[j]);
int k = 0;
while (k <= 10) { //attempt to store all the values of text file (DataGym.in.txt) into the array average[] using Scanner
average[k] = sc.nextDouble();
k++;
}
}
}
}
My code doesn't work and keeps giving me this error at the place where I store sc.nextDouble() into the k element of the array:
java.util.NoSuchElementException:
null (in java.util.Scanner)
You should check out the Scanner API. It is suspicious that you have a call to Scanner.hasNext() with a following call to Scanner.nextLine(). There are complimentary calls to check and then get from a Scanner. For instance if you really want the next line then you should check if Scanner.hasNextLine() before calling Scanner.nextLine(). Similarly you call Scanner.nextDouble() without preceding it with a call to Scanner.hasNextDouble().
Also like some of the comments mention you should use a debugger or print statements to see if you are getting what you expect you should be getting. Steps like this are necessary to debugging.
For instance after sf.close you could use System.out.println(Arrays.toString(text)) and judge if the array contains what you expect.
Hope this helps your debugging.
This has been troubling me for a while now. I normally don't tend to ask help and do my research, but I couldn't find an answer.
How do I write a program that reads a text file, and calculate how many times a certain number shows up?
I'm a huge beginner in Java, and also programming in general.
Here's my code.
This code generates a text file that has 100 random numbers
import java.io.*;
public class Rolling
{
public static void main (String[] args) throws IOException
{
int randomNum;
PrintWriter fileout = new PrintWriter (new FileWriter ("randumnums.txt"));
for (int i= 0; i < 101; i++)
{
randomNum = (int) (Math.random() * 100);
fileout.println (randomNum);
}
fileout.close();
}
}
Now the trouble I'm having is that I need to read the file and write a code saying X number was rolled 3 times. e.g the number 4 appeared 5 times in the text file, so I would need it to print "the number 4 was rolled 5 times".
import java.io.*;
public class Reading
{
public static void main (String[] args) throws IOException
{
BufferedReader readFile = new BufferedReader (new FileReader ("randumnums.txt"));
int number = 0;
int inMarks [] = new int [100];
for (int i = 0; i < 100; i++)
{
inMarks [i] = Integer.parseInt(readFile.readLine());
}
}
}
You're actually pretty close. It's clear that you're going to have to keep track of your counts in some kind of list, and an array will do quite nicely here.
First, after instantiating inMarks, initialize every value in it to 0:
int inMarks [] = new int [100];
for (int i = 0; i < 100; i++)
{
inMarks [i] = 0;
}
Then change the loop below to this:
String nextLine = null;
while ((nextLine = readFile.readLine()) != null)
{
int thisInt = Integer.parseInt(nextLine);
inMarks[thisInt] = inMarks[thisInt] + 1;
}
inMarks now perfectly tracks how many times each distinct int was rolled in the file. I'm going to let you implement the print-out part of the assignment, since that will give you a better understanding of how this solution works.
I have the feeling you are looking for something like this (I haven't tested this code)
import java.io.*;
public class Reading {
public static void main (String[] args) throws IOException {
BufferedReader readFile = new BufferedReader (new FileReader("randumnums.txt"));
int number = 0;
int inMarks [] = new int [100];
String readNumber = "";
while ((readNumber = readFile.readline()) != null) {
number = Integer.parseInt(readNumber);
inMarks[number]++;
}
}
}
The code above basically has an array of 100 integers. We then start reading the file until nothing can be read anymore. Everytime we read a line, we parse into an integer (which normally you should wrap around a try...catch). We then increase by 1 the number of times we have read this number by increasing the corresponding index in the array. So if you want to know how many times the number '32' appeared, you would do System.print.out(inMarks[32]);