I am doing a tutorial on java and the video I am at now deals with FileReading, but it is for windows and I am on a mac. Please help
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class App {
public static void main(String[] args) throws FileNotFoundException {
String fileName = "/Users/--MyUsername--/Desktop/test.rtf";
File textFile = new File(fileName);
Scanner in = new Scanner(textFile);
int value = in.nextInt();
System.out.println("Read value: " + value);
in.nextLine();
int count = 2;
while(in.hasNextLine()){
String line = in.nextLine();
System.out.println(count + ": " + line);
count++;
}
in.close();
}
}
and this is the error that I am getting
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at L37ReadingTextFiles.App.main(App.java:17)
Please help
You are trying to read integers from the file, but the content is not integer, please use String value = in.next(); instead of int value = in.nextInt();
The problem is probably with the .rtf file. There might be a way to get that type of file to work as expected in java, but for a beginner, I would recommend making it a .txt file.
Related
I was wondering if anyone could help solve this NoSuchElements exception in my program which scans a text very large text and then is added to the ArrayList.
I have tried re-arranging the order of the code to see if that would fix it but now I don't know how to fix it.
Exception itself:
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at mainTest.main(mainTest.java:11)
mainTest class:
import java.io.*;
import java.util.*;
public class mainTest {
public static void main(String args[]) throws FileNotFoundException {
ArrayList<String> bigBoi = new ArrayList<>(500000);
Scanner scan1 = new Scanner(new File("LargeDataSet.txt"));
while (scan1.hasNextLine()) {
scan1.next();
String data = scan1.next() + " " + scan1.next();
bigBoi.add(data);
}
ArrayList<String> successful = new ArrayList<>(500000);
}
}
The unit of a .txt file :
https://drive.google.com/file/d/1MWfMKMhSvuopOt9WwquABgYBTt0M4eLA/view?usp=sharing
(sorry for needing you to download it from a google drive, the file is so long I probably would've been reported or something if I had pasted 500,000 lines)
Please check with scan1.hasNext() instead of scan1.hasNextLine():
while (scan1.hasNext()) {
scan1.next();
String data = scan1.next() + " " + scan1.next();
bigBoi.add(data);
}
There is an empty line at the end of LargeDataSet.txt which is valid for scan1.hasNextLine() check, but the scan1.next() throws NoSuchElementException as there's nothing to read.
Changing validation to scan1.hasNext() as suggested in the accepted answer, solves that problem, but the program could still crash if there are less than 3 entries on any line and accepts lines with more than 3 entries.
A better practice is to validate all externally supplied data:
while (scan1.hasNextLine()) {
String line = scan1.nextLine();
String[] tokens = line.split("\\s+"); //split by space(s)
if(tokens.length != 3) { //expect exactly 3 elements on each line
throw new IllegalArgumentException("Invalid line: " + line);
}
bigBoi.add(tokens[1] + " " + tokens[2]);
}
I have a problem and hope to find a solution.
now i have created a simple program to change password of user account using text files in java.
now i should enter username of the account then change password of that account but there it shows me an error.
here is my code:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Objects;
import java.util.Scanner;
public class Test6 {
public static void main(String[] args)throws IOException {
String newPassword=null;
boolean checked = true;
File f= new File("C:\\Users\\فاطمة\\Downloads\\accounts.txt");// path to your file
File tempFile = new File("C:\\Users\\فاطمة\\Downloads\\accounts2.txt"); // create a temp file in same path
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
Scanner sc = new Scanner(f);
System.out.println("Enter account username you want to edit password?");
Scanner sc2 = new Scanner(System.in);
String username = sc2.next();
while(sc.hasNextLine())
{
String currentLine= sc.nextLine();
String[] tokens = currentLine.split(" ");
if(Objects.equals(Integer.valueOf(tokens[0]), username) && checked)
{
sc2.nextLine();
System.out.println("New Password:");
newPassword= sc2.nextLine();
currentLine = tokens[0]+" "+newPassword;
checked = false;
}
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
sc.close();
f.delete();
boolean successful = tempFile.renameTo(f);
}
}
the error shows to me:
Exception in thread "main" java.lang.NumberFormatException: For input string: "HAMADA"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.valueOf(Integer.java:766)
at Test6.main(Test6.java:25)
the format of my text file is like that:
HAMADA 115599
JOHNY 4477100
Change Integer.valueOf(tokens[0]) on line 25 to just tokens[0].
In your code, you try to get the integer value of the username, when you should be getting its String representation. You do not need the Integer.valueOf(). (The error is thrown because you are trying to get the Integer representation of a non-integer type.)
On a side note, you should never have password-storing text files, especially when the passwords and the files are both unencrypted. Use a database instead.
The purpose is to print-out a list of names from a .txt file. The code I've used is below.
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class FileScanner3 {
public static void main(String args []) throws FileNotFoundException {
ArrayList<String> names = new ArrayList<String>();
String inName;
//Setup a scanner to read from a text file
Scanner in = new Scanner(new File("namefile.txt").getAbsoluteFile());
while (in.hasNextLine()) {
inName = in.next();
//Use next() to read string
names.add(inName);
}
//Tidy up by closing files
in.close();
//Print names ArrayList
for(int i =0; i<names.size(); i++) {
System.out.println((i + 1) + "\t" + names.get(i));
}
}
}
The error that I get is this:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at FileScanner3.main(FileScanner3.java:17)
If anyone is able to tell me what is wrong, that would be fantastic!
Edit: Spelling
Without the text file, it is hard to guess, but I suppose there is a blank line at the end of the file. You could prevent this error by chaning the inner loop to
while (in.hasNext()) {
inName = in.next();
//Use next() to read string
names.add(inName);
}
I hope it helps.
When finished output should be:
15 Michael
16 Jessica
20 Christopher
19 Ashley
etc.
I am not that good at this and would like any input whatsoever on how to get the int and strings to print line by line. I have avoided an array approach because I always have difficulty with arrays. Can anyone tell me if I am on the right track and how to properly parse or type cast the ints so they can be printed on a line to the output file? I have been working for days on this and any help would be much appreciated! Here is what I have so far.
import java.io.PrintWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class NameAgeReverse
{
public static void main (String[] args)
{
System.out.println("Programmed by J");
String InputFileName;
String OutputFileName;
Scanner keyboard = new Scanner(System.in);
System.out.print("Input file: ");
InputFileName = keyboard.nextLine();
System.out.print("Output file: ");
OutputFileName = keyboard.nextLine();
Scanner inputStream = null;
PrintWriter outputStream = null;
try
{
inputStream = new Scanner(new FileInputStream("nameAge.txt"));
outputStream =new PrintWriter(new FileOutputStream("ageName.txt"));
}
catch(FileNotFoundException e)
{
System.out.println("File nameAge.txt was not found");
System.out.println("or could not be opened.");
System.exit(0);
}
int x = 0;
String text = null;
String line = null;
while(inputStream.hasNextLine())
{
text = inputStream.nextLine();
x = Integer.parseInt(text);
outputStream.println(x + "\t" + text);
}
inputStream.close();
outputStream.close();
}
}
Here are my error messages:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Michael"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at NameAgeReverse.main(NameAgeReverse.java:52)
text = inputStream.nextLine(); will read the whole line of text with both name and age. Assuming the format of every line in your input file is age name, you can do the following parse every line of text into desirable values. Note that this won't work out of the box with the rest of your code. Just a pointer:
text = inputStream.nextLine().split(" "); // split each line on space
age = Integer.parseInt(text[0]); // age is the first string
name = text[1];
This should work:
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class ReadWriteTextFile {
final static Charset ENCODING = StandardCharsets.UTF_8;
public static void main(String... aArgs) throws IOException{
List<String> inlines = Files.readAllLines(Paths.get("/tmp/nameAge.txt"), ENCODING);
List<String> outlines = new ArrayList<String>();
for(String line : inlines){
String[] result = line.split("[ ]+");
outlines.add(result[1]+" "+result[0]);
}
Files.write(Paths.get("/tmp/ageName.txt"), outlines, ENCODING);
}
}
I've been trying to do this problem for my schoolwork and for the life of me I cannot figure it out.
The problem is: Write a program that reads in "worked_example_1/babynames.txt" and produces two files, boynames.txt and girlnames.txt, separating the data for the boys and girls.
This is the code from Worked Example 11 from wiley.com/go/javaexamples for this problem:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class BabyNames
{
public static final double LIMIT = 50;
public static void main(String[] args) throws FileNotFoundException
{
Scanner in = new Scanner(new File("babynames.txt"));
RecordReader boys = new RecordReader(LIMIT);
RecordReader girls = new RecordReader(LIMIT);
while (boys.hasMore() || girls.hasMore())
{
int rank = in.nextInt();
System.out.print(rank + " ");
boys.process(in);
girls.process(in);
System.out.println();
}
in.close();
}
}
And this:
import java.util.Scanner;
public class RecordReader
{
private double total;
private double limit;
public RecordReader(double aLimit)
{
total = 0;
limit = aLimit;
}
public void process(Scanner in)
{
String name = in.next();
int count = in.nextInt();
double percent = in.nextDouble();
if (total < limit)
{
System.out.print(name + " ");
}
total = total + percent;
}
public boolean hasMore()
{
return total < limit;
}
}
I created the babynames.txt and put in the same src folder as the .java file, it comes up with file not found, if I give the direct path to the file with
Scanner in = new Scanner(new File("C:/Users/me/SkyDrive/Schoolwork/CIS150AB/Chapter 11.1/src/babynames.txt"));
it finds the file but gives me this error:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at BabyNames.main(BabyNames.java:20)
To me it looks like this error is because of Line 20 where int rank = in.nextInt(); and its looking for a string when its looking for an int, but this is directly from Wiley website so I am not sure.
Any help with this would be appreciated, apparently I am not meant for online classes for Java. Next class I am taking in school once there is one that works around my schedule.
If this is the format of your babynames.txt, this is what'll happen (I think, didn't try it).
The scanner "in" reads the first int into "rank" (OK)
Enter into boys.process()
"in" reads the first name (Jacob)
"in" tries to read the first int (1), but finds 1.0013, which is not an int
This scenario doesn't match your error (you'd get a stacktrace from RecordReader rather than from BabyNames) but maybe the line of thinking will work for you.
Try it with a debugger. If you can't, use in.next() rather than in.nextInt() or in.nextDouble(). You can than print the value and see why it's not what you think it is.
Your question actually raises two questions. The answer to the hidden one may be:
try (InputStream inputStream = BabyNames.class.getResourceAsStream("/babynames.txt");
Scanner in = new Scanner(inputStream))
{
// do stuff with in
}