Need to read String and Double from file [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
I'm having some trouble trying to read a String and a Double from a txt file.
Here is my txt file:
Mike 300.50
John 260
Lisa 425.33
And here is the code I am using to read them:
reader = new Scanner();
while(reader.hasNext()){
name= reader.next();
salary = reader.nextDouble();
System.out.println(name + " " + salary + "\r\n");
}
Whenever I run this code, Exception in thread "main" java.util.InputMismatchException appears telling me the problem is in nextDouble().
Does anybody know how to solve this?

reader = new Scanner();
while(reader.hasNext()){
name= reader.next();
salary = reader.nextDouble();
System.out.println(name + " " + salary + "\r\n");
reader.nextLine();
}
Try this. What's happening is that the scanner is reading the empty line after every double, so name will be the empty line, and it will read (for example) John as the salary, and give you that exception.
So what I did was add that little line of code: reader.nextLine(); so it could skip that empty line. Hope this helps.

You could try this way:
while(reader.hasNextLine()){
String[] values = reader.nextLine().split("\\s+");
name= values[0];
salary = Double.valueOf(values[1]);
System.out.println(name + " " + salary + "\r\n");
}

you can use java.io.StreamTokenizer to read String and double.
StreamTokenizer split file into tokens with suitable datatype.
and by using some constants you can identify the token type.
like TT_NUMBER,TT_WORD
File f=new File("path of file");
StreamTokenizer st=new StreamTokenizer(new FileInputStream(file));
while(st.nextToken()!=StreamTokenizer.TT_EOF) //getting contents of file{
switch(st.ttype)
{
case StreamTokenizer.TT_EOF: break;
case StreamTokenizer.TT_NUMBER://it will read number always in double data type
no=st.nval;
break;
case StreamTokenizer.TT_WORD:
name=st.nval;
break;
}}

Related

Trying to appending a text in a new line to an existing file in Java?

How to append text to an existing file in Java?
I am using the method mentioned in the solution and i am taking user input.
But the text is appending with the last word. is there any way to add an new line there?
Scanner sc= new Scanner(System.in);
System.out.print("Enter a string: ");
String str= sc.nextLine();
try {
Files.write(Paths.get("C:\\Users\\souravpal\\Documents\\Bandicam\\buddy.txt"), str.getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
You must use the new line character \n in your str variable if you want to move to the next line.
String str = "\n" + sc.nextLine();
You also should put it before the input becouse you will append it at the end of the file.
use the System.lineSeparator() constant that applies at runtime and compatible with all OS.
Files.write(Paths.get("C:\\Users\\souravpal\\Documents\\Bandicam\\buddy.txt"),
(System.lineSeparator() + str).getBytes(),StandardOpenOption.APPEND);

Why doesnt this code store multiple inputs - currently stores only one that gets overwritten upon new input

Hey guys any help would be appreciated.
I've created some code that allows me to take user input from terminal, and saves it into a txt file in the same directory. The issue is that only 1 name and surname is stored each time. when i open a new client and type a different name, it will just overwrite the original one. not sure what is the cause as i was under the impression that the out.newline would solve this issue.
public void userinput()
{
try
{
out = new BufferedWriter(new FileWriter("TESTING.txt"/*,true*/));
//
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
//ask for first name
System.out.println("Please enter your first name: ");
Name = input.nextLine();
//ask for surname
System.out.println("Please enter your last name: ");
Surname = input.nextLine();
//write names into txt file
out.write(Name + " - " + Surname);
//print welcome message with names into console for user
System.out.println("Welcome " + Name + Surname);
out.newLine();
out.close();
}
catch(IOException e)
{
System.out.println("There was a problem:" + e);
}
}
}
thanks for the help!
This is happening simply because you didn't open your FileWriter in the append mode, so it doesn't overwrite the file every time. To do this, you have to call the constructor as new FileWriter("TESTING.txt", true). Just uncomment the true and it'll work. I'm guessing at some point you accidentally commented that out.

Reading from inFile - Java

I am attempting to read from a file - my code is below:
try
{
Scanner inFile = new Scanner (new FileReader("input.txt"));
while(inFile.hasNextLine())
{
first = inFile.next();
second = inFile.next();
System.out.println("first: " + first);
System.out.println("second: " + second);
}
inFile.close();
}
catch(FileNotFoundException exception)
{
System.out.println("Unable to locate file");
}
The file text is:
Fred 10
John 13
Bob
Jill 43
Because some lines do not contain any text the program crashes. For example, this program crashes when it tries to give "second" a value in the third line - the one containing Bob.
How can I create an if value exists? Or ignore if no value?
You can use useDelimiter function and iterate the line again
while(inFile.hasNextLine())
{
Scanner sc = new Scanner(inFile.nextLine());
sc.useDelimeter(" ");
while(sc.hasNext())
System.out.println(sc.next());
}
Your program is (incorrectly) assuming that there are two values per line always. If that's not true, you'll need to consider that case. A way could be (untested):
while(inFile.hasNextLine()) {
first = inFile.next();
if (!inFile.hasNext()) {
continue; // ignore this line
}
second = inFile.next();
...
}
Unrelated to your question: you are incorrectly closing inFile. This info may come in handy.

whole text file to string and count (nullpointerexception error) [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
**
I want to get text from the user and find the number of words in the text according to the word searched. BufferedReader sets the readLine method to get all rows with while, but the program gives a null pointer exception error
.
The program worked fine when I used a single readline.
I think the problem is in the while loop but I do not understand the problem.**
Please Write Path : C:\Users\Soul Collector\Desktop\yazi okuma
Please Write the Name of Text : buffer
Text File :
hi hello my name is suat
hello there
Hello
Write the key word :
hi
Exception in thread "main" java.lang.NullPointerException
at project2.Count.SingleWord(Count.java:83)
at project2.Project2.main(Project2.java:45)
C:\Users\Soul Collector\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 18 seconds)
if(press == 2 )
{
System.out.print("Please Write Path : ");
scan.nextLine();
path = scan.nextLine();
System.out.print("Please Write the Name of Text : ");
txtname = "\\"+ scan.nextLine() + ".txt";
finalpath = path + txtname;
File dosya = new File(finalpath);
FileReader fr = new FileReader(dosya);
BufferedReader br = new BufferedReader(fr);
String dizi;
while((dizi = br.readLine()) != null){
System.out.println(dizi);
}
br.close();
/* StringTokenizer st = new StringTokenizer(dizi);
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
}*/
String search=null;
System.out.println("Write the key word : ");
search = scan.nextLine();
Scanner s = new Scanner(dizi.toLowerCase());
while (s.hasNext()) {
toplamkelime++;
if (s.next().equals(search))
kelime ++;
}
System.out.println("Key Word : " + search);
System.out.println("Count of key word : " + kelime);
System.out.println("\n\n\n Total Count of Words : " + toplamkelime );
}
You are assigning value to 'dizi' within while conditions, so it was overwritten everytime. When there is something to read, 'dizi' has a value and get printed inside the while loop.
When nothing else to read 'dizi' is then has null value. So when you call 'dizi.toLowerCase()' later down the line, you get null pointer exception.
To fix the issue you need to keep track of all read dizi by using List or append them to another String.

Randomly search a text file for keyword using fastest & efficient string-search method

I've got a text file with one customer record per line. Each record is formatted as "ID num, first name, last name, dollar amount". I need to read a line of this text file based on the ID number entered by the user.
I've been following a Java ebook that does this by using the length of a single record and multiplying it by the ID number entered. The problem is, that only works if every record has the exact same length. My records do not truncate or pad out the first and last name, and the dollar amount ranges from two to five characters in length which means that the method that the book uses won't work.
Is there any way to read a specific line in a text file without requiring all the records to be the exact same length? I'd have thought that there would be a way to use the line separator character to do it.
For reference I'll put up the code that doesn't work due to my varying record sizes, in case it helps.
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
Path filepath = Paths.get("U:\\Programming\\Java\\Chapter 13\\customersdata.txt");
String s = " , , , 00.00" + System.getProperty("line.separator");
final int RECSIZE = s.length();
byte[] data = s.getBytes();
ByteBuffer buffer = ByteBuffer.wrap(data);
FileChannel fc = null;
try {
fc = (FileChannel)Files.newByteChannel(filepath, READ, WRITE);
System.out.println("Enter an ID number to display the customer details for that ID. Or \"quit\".");
String idString = keyboard.nextLine();
while(!idString.equals("quit")) {
int id = Integer.parseInt(idString);
buffer = ByteBuffer.wrap(data);
fc.position(id * RECSIZE);
fc.read(buffer);
s = new String(data);
System.out.println("ID #" + id + " " + s);
System.out.println("Enter an ID number to display the customer details for that ID. Or \"quit\".");
idString = keyboard.nextLine();
}
fc.close();
}catch(Exception e) {
System.out.println("Error message: " + e);
}
}
EDIT: As the text file being read from could hypothetically contain tens of thousands of records, I can't use Sequential Access, if the ID number I need is near the bottom of the file, it would take an unacceptable amount of time to read them all, as such, the solution must be Random Access.
I've got a text file with one customer record per line. Each record is
formatted as "ID num, first name, last name, dollar amount". I need to
read a line of this text file based on the ID number entered by the
user.
and
Is there any way to read a specific line in a text file without
requiring all the records to be the exact same length?
In the main method at readData("33"), i hardcoded the id string. You can change it according to your data.txt and get the data.
data.txt
1 harry singh 456
2 lauren dat 25
33 pingle pooh 8797
10002 yogeshvari bahman 897461
parseTxt.java
import java.io.File;
import java.util.Scanner;
public class parseTxt {
private static Scanner fileReader ;
public static void main(String[] args)
{
try{
readData("33");
} catch(Exception e){
System.out.println("Exception : " + e);
}
}
private static void readData(String id) throws Exception{
fileReader = new Scanner(new File("E://data.txt"));
String cusId, fname, lname, dollar;
while(fileReader.hasNextLine()){
String line = fileReader.nextLine();
String[] lineParts = line.split(" ");
if(lineParts[0].equals(id)){ // lineParts[0] is ID NUMBER
cusId = lineParts[0];
fname = lineParts[1];
lname = lineParts[2];
dollar = lineParts[3];
System.out.println("Customer ID : #" + cusId);
System.out.println("First Name : " + fname);
System.out.println("Last Name : " + lname);
System.out.println("Dollar Amount : $" + dollar);
break;
} else {
System.out.println("This ID:" + id + " does not exist");
}
}
}
}
For Edited Question (search while keeping good performance)
source-1:
try (SeekableByteChannel ch = Files.newByteChannel(Paths.get("test.txt"))) {
ByteBuffer bb = ByteBuffer.allocateDirect(1000);
for(;;) {
StringBuilder line = new StringBuilder();
int n = ch.read(bb);
// add chars to line
// ... don't forget to break
}
}
It requires a bit of coding but it can be really faster because of ByteBuffer.allocateDirect. It allows OS to read bytes from file to ByteBuffer directly, without copying
source-2: Every answer on this link adds bits of information
Convert the search string ('are') to a byte-array in the same
encoding as the file.
Open a memory-mapped byte-buffer from a File-Channel on the file.
Scan the ByteBuffer, looking for matches to the search byte-array
count the newlines as you go.
close the ByteBuffer
source-3:
A simple technique that could well be considerably faster than indexOf() is to use a Scanner, with the method findWithinHorizon(). If you use a constructor that takes a File object, Scanner will internally make a FileChannel to read the file. And for pattern matching it will end up using a Boyer-Moore algorithm for efficient string searching.
source-4: Implementation of Boyer-Moore's String Search algorithm
I am sorry but I will leave the researching to you. If you ask my suggestion, I think GNU-Grep is faster of them all because it, too, uses Boyer-Moore's string search algorithm.
Hope this helps! correct me if i misunderstood your problem.

Categories