Trying to read from text file - java

I am trying to read the following from a text file:
12
650 64 1
16 1024 2
My attempt:
import java.util.Scanner;
import java.io.*;
class Test{
public static void main(String[] args){
String filnavn = "regneklynge.txt";
Scanner innFil = null;
try {
File fil = new File(filnavn);
innFil = new Scanner(fil);
while (innFil.hasNextLine()) {
String linje = innFil.nextLine();
int tall = Integer.parseInt(linje);
System.out.println(tall);
}
} catch(FileNotFoundException e) {
System.out.println("Filen kunne ikke finnes");
}
}
}
The first number(12) Works fine, but then I get this
Exception in thread "main" java.lang.NumberFormatException: For input string: "650 64 1"

Suggestions:
You need two while loops, one nested inside of the other
the first one, the outer loop, you loop while (innFile.hasNextLine()) {...}
inside this loop you call String linje = innFile.nextLine(); once
Then create a 2nd Scanner object, Scanner lineScanner = new Scanner(linje);
and create a 2nd inner while loop that loops while (lineScanner.hasNextInt() {...}
inside of this loop, extract a single int via int tall = lineScanner.nextInt();
and put it into your ArrayList.
Be sure to call lineScanner.close(); after exiting the inner while loop and before exiting the outer loop.

As long as you are reading the full line:
String linje = innFil.nextLine();
You can't treat them as an Integer because it's already a String
int tall = Integer.parseInt(linje);
// linje now has this = "650 64 1"
So that provokes the Exception:
java.lang.NumberFormatException
Here is an approach to print the numbers:
import java.util.Scanner;
import java.io.*;
class Test{
public static void main(String[] args){
String filnavn = "regneklynge.txt";
Scanner innFil = null;
try {
File fil = new File(filnavn);
innFil = new Scanner(fil);
while (innFil.hasNextLine()) {
if (innFil.hasNextInt()) {
System.out.println(innFil.nextInt());
} else {
innFil.next();
}
}
} catch(FileNotFoundException e) {
System.out.println("Filen kunne ikke finnes");
}
}
}

Related

InputMismatch error trying to take integer as user input

I am trying to take an integer as user input and store it in a list until the user hits 'q'. At the moment the user inputs 'q', the loop gets terminated.
The code is showing an InputMismatch error:
import java.util.*;
public class SampleArrayList {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s;
int n;
List<Integer> array = new ArrayList();
while (true) {
n = sc.nextInt();
s = sc.nextLine();
if (s.equals("q")) {
break;
} else {
array.add(n);
}
}
Collections.sort(array);
System.out.println(array);
}
}
Just try this,
Inside your while loop to get input for a string use,
s = sc.next();
Instead of sc.nextLine();.
Are you trying to implement it like the example below?
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s;
List<Integer> array = new ArrayList();
while (true) {
s = sc.nextLine();
if (s.equalsIgnoreCase("q")) {
break;
}
int num = Integer.parseInt(s);
array.add(num);
}
Collections.sort(array);
System.out.println(array);
}
}
Looks like q is trying to be stored as an int, so this should work:
All numbers stored as a String can be parsed as an int with the parseInt() method.
s = sc.nextLine();
if (!s.equals("q"))
{
array.add(Integer.parseInt(s));
}
else
{
break;
}

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 ");
}

How do I read and process a file in a separate method and call it in the main method in Java?

I have this code i'm working on to compute the ARI of a given text read from the a .txt file. This code works perfectly but I want to put in fewer things in my main method. How is it able to put my try and catch block in a new method and then call it to my main method instead of having everything mashed together? I have tried some few ways but i'm not getting the usual output.
Here is my main class:
public class MyClass {
public static void main(String[] args){
String EachSentence;
int wordCount;
List<Sentence> sentences = new ArrayList<>();
List<Integer> EachWordCount = new ArrayList<>();
List<Integer> EachLetterCounted= new ArrayList<>();
try{
File file = new File("a2b.txt");
Scanner scanner = new Scanner(file);
scanner.useDelimiter("[.?!]");
int SentenceCount =0;
while(scanner.hasNext()){
SentenceCount++;
EachSentence = scanner.next();
EachSentence = EachSentence.replaceAll("\\r?\\n", " ");
EachSentence = EachSentence.trim();
if (sentences.add(new Sentence(EachSentence)) && sentences.size() > 1){
System.out.println("(" + SentenceCount + ") " + EachSentence);
}
StringTokenizer tokenizer = new StringTokenizer(EachSentence, " ");
wordCount = tokenizer.countTokens();
if(EachWordCount.add(wordCount)&& EachWordCount.size() > 1){
//I removed the element at position 0 so as to correlate with EachSentence then added the counts to the arrayList
//to prepare them for addition
EachWordCount.remove(0);
EachWordCount.add(wordCount);
}
int LetterCount=1;
for(int i=1; i<EachSentence.length(); i++){
char currentChar = EachSentence.charAt(i);
if(currentChar != ' '&& currentChar!='('&&currentChar!=')'&&currentChar!=','&& currentChar!='.'){
EachLetterCounted.add(LetterCount);
LetterCount++;
}
}
}
scanner.close();
}catch (IOException ex){
System.out.println(ex.getMessage());
}
//Computes the ARI of the total sentences
double lettersCounted = (double) lettersCounted(EachLetterCounted);
double wordsCounted = (double) sum(EachWordCount);
double sentencesCounted = (double) SentencesCounted(EachWordCount);
double AutomatedReadabilityIndex= 4.71*(lettersCounted/wordsCounted) + 0.5 * (wordsCounted/sentencesCounted) -21.43;
System.out.println("\nSummary statistics: ");
System.out.println("Letters: "+lettersCounted(EachLetterCounted));
System.out.println("Words: "+ sum(EachWordCount));
System.out.println("Sentences: " + SentencesCounted(EachWordCount));
DecimalFormat df = new DecimalFormat("#.##");
System.out.println("readability: "+ df.format(AutomatedReadabilityIndex));
}
contributions would be great!
Second time answering my question.(For anyone having the same problem) I achieved this by simply putting everything I had in the main method in a ...static void ReadFile() method and calling only `ReadFile in the main method. It may not be the best way but it was what I was looking for :)
public static void main(String[] args) {
ReadFile();
}
public static void ReadFile() {
//insert all what is in main method, the exceptions were handled
//here also. So there was no need for the throws IOException that
//should've followed.
}
OR
public static void main(String[] args) {
ReadFile(//insert name of file to be read here);
}
public static void ReadFile(String filename) {
//insert all what is in main method, the exceptions were handled
//here also. So there was no need for the throws IOException that
//should've followed.
}

Why does this code trigger an infinite loop?

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++;
}

Categories

Resources