I am reading a file using a delimiter with a scanner. When I get to the last entry of the file it says I am out of bounds. If I count correctly I am in bounds though.
Here is the code and it is throwing an input mismatch error. Any help is appreciated. Thanks.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws IOException {
String personName = null;
double score = 0;
File myFile = new File("twogrades.dat");
try {
Scanner scan = new Scanner(myFile).useDelimiter(",");
while (scan.hasNext()) {
personName = scan.next();
for (int i = 0; i <= 5; i++) {
score += ((scan.nextDouble() / 50) * 0.03);
}
for (int i = 6; i <= 11; i++) {
score += ((scan.nextDouble() / 10) * 0.02);
}
score += ((scan.nextDouble()) * 0.20);
score += ((scan.nextDouble()) * 0.50);
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter("grades.dat", true)));
out.println(personName + " " + score);
out.close();
score = 0;
scan.nextLine();
}
scan.close();
} catch (InputMismatchException e) {
System.out.println(e.getMessage()
+ " You entered a wrong data type");
} catch (NoSuchElementException e) {
System.out.println(e.getMessage()
+ " There are no more elements left in the file");
} catch (IllegalStateException e) {
System.out.println(e.getMessage());
}
}
}
Here is the file
Yuri Allen,5,26,16,22,18,3,0,4,4,2,10,2,54,89
I am able to reproduce the error, but only if there is more than one line in the input file. The problem is the delimiter. You only use the comma ",". Thus, the scanner tries to read the new line character with the last entry of the line: "89\n". Since this is not a valid double, you get the exception.
You can solve this by adding the new line character as a delimiter: ",|\\r\\n|\\r|\\n"
I run it and the result is: No line found There are no more elements left in the file and the output Yuri Allen 55.398. Possibly you can clean, rebuild your project and change:
while (scan.hasNext()) {
to this
while (scan.hasNextLine()) {
Related
I'm trying to make a program that checks an ArrayList and makes sure that each index includes only 2 integers per line, and doesn't include any doubles or strings.
If the arraylist is:
0 1
2 34
32 51 32
it would pull up an error message for the third line for having 3 integers. The program needs to check that it has only two integers per line, is only 12 lines long, and doesn't include any doubles or strings. This is what I have so far:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
public class TextFileReader {
public static void main(String[] args) {
int fileCount = 0;
ArrayList<String> inputFile = new ArrayList<String>(20);
try (Scanner fileScanner = new Scanner(new File("perfect_file.txt"))) {
while (fileScanner.hasNext()) {
inputFile.add(fileScanner.nextLine());
}
} catch (FileNotFoundException e) {
System.out.println("Error reading generic answers, program ending.");
System.exit(1);
}
if (inputFile.size() > 12) {
System.out.println("Error: Lines exceed 12");
}
if (inputFile.size() < 12) {
System.out.println("Error: Not enough lines");
}
}
}
I would really appreciate any help on this. Thank you!
Use String split, it's look like
try (Scanner fileScanner = new Scanner(new File("perfect_file.txt"));) {
while (fileScanner.hasNextLine()) {
String[] line = fileScanner.nextLine().split("\\s+");
if (line.length == 2) {
// Ok, do something
// System.out.println("First: " + line[0] + ", Second: " + line[1]);
} else {
// Wrong
System.out.println("The number of line " + line.length);
}
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I have a problem with where I am getting a NullPointerException on line 59 of my code.
The program's purpose is to prompt the user for the file location (which has the digits of PI). The program should then accept any number of digits (say k digits) via the Scanner class. Then, the program must read k digits of PI from the file. Using the Scanner class, the program should then obtain a number for 0-9 from a user and print the first and last position in which it appears and also the number of times it appears. Only digits after the decimal point are to be considered. The program should be able to accept 100,000 digits of PI.
The sample output of the code is below:
Give the location of the file:
C:\Users\Joe\Desktop\pi.txt
Number of digits of PI to parse:
10
Give any number between 0-9:
1
1 appears 2 times
First position in which appears: 1
Last position in which appears: 3
Any help would be much appreciated.
Below is my code:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
import java.util.ArrayList;
public class Problem2 {
#SuppressWarnings("null")
public static void main(String[] args) throws Exception {
FileInputStream inputstream = null;
BufferedReader reader = null;
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
try {
System.out.println("Give the location of the file (example: C:\\Users\\Joe\\Desktop\\pi.txt):");
String fileloc = input.nextLine();
inputstream = new FileInputStream(fileloc);
reader = new BufferedReader(new InputStreamReader(inputstream));
String stringinput;
System.out.println("Number of digits of PI to parse: ");
int parsenum = input.nextInt() + 2;
String[] stringarray = new String[parsenum];
while((stringinput = reader.readLine()) != null) {
stringinput = stringinput.substring(2, parsenum);
for(int i = 0; i < stringinput.length(); i++) {
stringarray = stringinput.split("");
}
}
System.out.println("Give any number between 0-9: ");
String searchnum = input.next();
int count = 0;
for(int i = 1; i < parsenum - 1; i++) {
if(searchnum == stringarray[i]) {
count++;
}
else count++;
}
System.out.println(searchnum + " appears " + count + " time(s)");
for(int i = 1; i < parsenum - 1; i++) {
System.out.print(stringarray[i]);
}
System.out.println();
System.out.println("First position in which " + searchnum + " appears: " + stringinput.indexOf(searchnum));
System.out.println("Second position in which " + searchnum + " appears: " + stringinput.lastIndexOf(searchnum));
}
catch (FileNotFoundException exception) {
System.err.println("File not found, please try again");
main(null);
}
catch (Exception e) {
System.err.println("Invalid input entered");
e.printStackTrace();
System.exit(0);
}
finally {
reader.close();
}
}
}
while((stringinput = reader.readLine()) != null)
The above while loop will run untill reader.readLine is null and so will be stringinput.
Now after the while loop your using stringinput:
stringinput.indexOf(searchnum)
stringinput.lastIndexOf(searchnum)
and thus getting the NullPointerException.
I am currently trying to create a Java program that allows a scanner to read 100 integers from a .txt file and then for the program to output the average of the 100 numbers. It must also check for errors whilst reading from the code. E.G (there is a letter in .txt file, instead of an integer).
Here is the code I have so far:
package NumFile;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Scanner;
public class NumFile {
public static void main (String [] args) throws FileNotFoundException {
try {
int counter = 0; // Counter for number of numbers in the txt file
double sum = 0; // Sum of all digits in the txt file
String line = null; // The line that is read in the txt file
Scanner userIn = new Scanner(System.in);
System.out.println("Type the name of the file located");
String fileName = userIn.nextLine();
BufferedReader in = new BufferedReader(new FileReader(Workbook1.txt));
Object input;
while(in.hasNextLine() && !((input = in.nextLine()).equals(""))) {
counter++;
sum += Double.parseDouble(line);
}
double average = sum/counter;
System.out.println("The average of the numbers is: " + format(average));
System.out.println("The sum of the numbers is: " + sum);
System.out.println("The number of digits is " + counter);
}
catch (IOException e) {
System.out.println("Input/Output exception");
}
}
public static String format(double number) {
DecimalFormat d = new DecimalFormat("0.00");
return d.format(number);
}
}
With this code, I am having a few errors.
Here are the errors that display:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Workbook1 cannot be resolved to a variable
The method hasNextLine() is undefined for the type BufferedReader
The method nextLine() is undefined for the type BufferedReader
at NumFile.NumFile.main(NumFile.java:27)
If I remove:
Object input;
// Loop until the end of the file
while(in.hasNextLine() && !((input = in.nextLine()).equals(""))){
then the program starts to run, however it cannot find the .txt file containing the integers!
You can do something like this:
Scanner in = new Scanner(new File(fileName));
String input = "";
while(in.hasNextLine() && !((input = in.nextLine()).equals(""))) {
//code here
}
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.
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.