Use delimiter to separate a pattern - java

I have a text file where I am trying to read string and integer input using a Scanner. I need to separate the data using a comma and there is also the issue of newline character. Here is the text file contents:
John T Smith, 90
Eric K Jones, 85
My code:
public class ReadData {
public static void main(String[] args) throws Exception {
java.io.File file = new java.io.File("scores.txt");
Scanner input = new Scanner(file);
input.useDelimiter(",");
while (input.hasNext()) {
String name1 = input.next();
int score1 = input.nextInt();
System.out.println(name1+" "+score1);
}
input.close();
}
}
Exception:
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 ReadData.main(ReadData.java:10)

Setting the delimiter for class java.util.Scanner to comma (,) means that each call to method next() will read all the data up to the next comma, including newlines. Hence the call to nextInt reads the score plus the name on the next line and that isn't an int. Hence the InputMismatchException.
Just read the entire line and split it on the comma (,).
(Note: Below code uses try-with-resources)
public class ReadData {
public static void main(String[] args) throws Exception {
java.io.File file = new java.io.File("scores.txt");
try (Scanner input = new Scanner(file)) {
// input.useDelimiter(","); <- not required
while (input.hasNextLine()) {
String line = input.nextLine();
String[] parts = line.split(",");
String name1 = parts[0];
int score1 = Integer.parseInt(parts[1].trim());
System.out.println(name1+" "+score1);
}
}
}
}

Use ",|\\n" RegExp delimiter:
public class ReadData {
public static void main(String[] args) throws Exception {
java.io.File file = new java.io.File("scores.txt");
Scanner input = new Scanner(file);
input.useDelimiter(",|\\n");
while (input.hasNext()) {
String name1 = input.next();
int score1 = Integer.parseInt(input.next().trim());
System.out.println(name1+" "+score1);
}
input.close();
}
}

Try this.
String text = "John T Smith, 90\r\n"
+ "Eric K Jones, 85";
Scanner input = new Scanner(text);
input.useDelimiter(",\\s*|\\R");
while (input.hasNext()) {
String name1 = input.next();
int score1 = input.nextInt();
System.out.println(name1+" "+score1);
}
input.close();
output:
John T Smith 90
Eric K Jones 85

Related

Writing a program in Java to read in multiple strings from user and compare to text file

I am attempting to write a program that will take user input ( a long message of characters), store the message and search a text file to see if those words occur in the text file. The problem I am having is that I am only ever able to read in the first string of the message and compare it to the text file. For instance if I type in "learning"; a word in the text file, I will get a result showing that is is found in the file. However if I type "learning is" It will still only return learning as a word found in the file even though "is" is also a word in the text file. My program seems to not be able to read past the blank space. So I suppose my questions is, how do I augment my program to do this and read every word in the file? Would it also be possible for my program to read every word, with or without spaces, in the original message taken from the user, and compare that to the text file?
Thank you
import java.io.*;
import java.util.Scanner;
public class Affine_English2
{
public static void main(String[] args) throws IOException
{
String message = "";
String name = "";
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
System.out.println("Please enter in a message: ");
message = scan.next();
Scanner file = new Scanner(new File("example.txt"));
while(file.hasNextLine())
{
String line = file.nextLine();
for(int i = 0; i < message.length(); i++)
{
if(line.indexOf(message) != -1)
{
System.out.println(message + " is an English word ");
break;
}
}
}
}
}
I recommend you first process the file and build a set of legal English words:
public static void main(String[] args) throws IOException {
Set<String> legalEnglishWords = new HashSet<String>();
Scanner file = new Scanner(new File("example.txt"));
while (file.hasNextLine()) {
String line = file.nextLine();
for (String word : line.split(" ")) {
legalEnglishWords.add(word);
}
}
file.close();
Next, get input from the user:
Scanner input = new Scanner(System.in);
System.out.println("Please enter in a message: ");
String message = input.nextLine();
input.close();
Finally, split the user's input to tokens and check each one if it is a legal word:
for (String userToken : message.split(" ")) {
if (legalEnglishWords.contains(userToken)) {
System.out.println(userToken + " is an English word ");
}
}
}
}
You may try with this. With this solution you can find each word entered by the user in your example.txt file:
public static void main(String[] args) throws IOException
{
String message = "";
String name = "";
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
System.out.println("Please enter in a message: ");
message = scan.nextLine();
Scanner file = new Scanner(new File("example.txt"));
while (file.hasNextLine())
{
String line = file.nextLine();
for (String word : message.split(" "))
{
if (line.contains(word))
{
System.out.println(word + " is an English word ");
}
}
}
}
As Mark pointed out in the comment, change
scan.next();
To:
scan.nextLine();
should work, i tried and works for me.
If you can use Java 8 and Streams API
public static void main(String[] args) throws Exception{ // You need to handle this exception
String message = "";
Scanner input = new Scanner(System.in);
System.out.println("Please enter in a message: ");
message = input.nextLine();
List<String> messageParts = Arrays.stream(message.split(" ")).collect(Collectors.toList());
BufferedReader reader = new BufferedReader(new FileReader("example.txt"));
reader.lines()
.filter( line -> !messageParts.contains(line))
.forEach(System.out::println);
}
You have many solution, but when it comes to find matches I suggest you to take a look to the Pattern and Matcher and use Regular Expression
I haven't fully understood your question, but you could do add something like this (I did not tested the code but the idea should work fine):
public static void main(String[] args) throws IOException{
String message = "";
String name = "";
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
System.out.println("Please enter in a message: ");
message = scan.next();
Scanner file = new Scanner(new File("example.txt"));
String pattern = "";
for(String word : input.split(" ")){
pattern += "(\\b" + word + "\\b)";
}
Pattern r = Pattern.compile(pattern);
while(file.hasNextLine())
{
String line = file.nextLine();
Matcher m = r.matcher(line);
if(m.matches()) {
System.out.println("Word found in: " + line);
}
}
}

How to use split() and read the first character of a string of a file?

For example, I want to split the commas of this file and read the first character of each line. Based on the first character (#,*,#), I want to create an object using the data after each character(Steve Davis 2000).
4
#Steve,Davis,2000
*John,Kanet,800,7000,0.10
#Thomas,Hill,20,50
*Lisa,Green,800,6000,0.10
The 4 is used as a size for my array
So far this is my code:
import java.util.Scanner;
import java.io.*;
public class PayRoll3{
public static void main(String[] args) throws FileNotFoundException{
Scanner input=new Scanner(new File(args[0]));
int size=input.nextInt();
input.nextLine();
Employee[] employees = new Employee[size];
int index = 0;
while(input.hasNext()){
String tmp= input.next();
String[] commas = tmp.split(",");
if(tmp.substring(0,1).equals("#")){
employees[index++]=new Manager2(input.next(), input.next(), input.nextDouble() );
}
else if(tmp.substring(0,1).equals("*")){
employees[index++]=new CommissionEmployee2(input.next(), input.next(), input.nextDouble(), input.nextDouble(), input.nextDouble());
}
else if(tmp.substring(0,1).equals("#")){
employees[index++]=new HourlyWorker2(input.next(), input.next(), input.nextDouble(), input.nextDouble());
}
}
input.close();
for ( Employee currentEmployee : employees ){
System.out.println( currentEmployee );
}
}
When i run the code i get
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.nextDouble(Unknown Source)
at PayRoll3.main(PayRoll3.java:19)
Use charAt() instead to get first character of a String to decide which object you want to create.
Use nextLine() instead of next() to get the whole line, then use split method to split that whole line by comma.
Use substring(1) to get rid of the first character. This will assume that you want the whole string character by character starting from the second index (which is 1) to the end of the string which gives you eventually the string you want with out the first character of it.
import java.util.Scanner;
import java.io.*;
public class PayRoll3{
public static void main(String[] args) throws FileNotFoundException{
Scanner input=new Scanner(new File(args[0]));
int size=input.nextInt();
input.nextLine();
Employee[] employees = new Employee[size];
int index = 0;
while(input.hasNext()){
String tmp= input.nextLine();
String[] commas = tmp.split(",");
if(commas[0].charAt(0) == '#'){
employes[index++] = new Manager2(commas[0].substring(1), commas[1], Double.parseDouble(commas[2]));
}
else if (commas[0].charAt(0) == '*'){
employes[index++] = new ComissionEmployee2(commas[0].substring(1), commas[1], Double.parseDouble(commas[2]), Double.parseDouble(commas[3]), Double.parseDouble(commas[4]));
}
else if (commas[0].charAt(0) == '#'){
employes[index++] = new HourlyWorkey2(commas[0].substring(1), commas[1], Double.parseDouble(commas[2]), Double.parseDouble(commas[3]));
}
}
input.close();
for (Employee currentEmployee : employees ){
System.out.println( currentEmployee );
}

Updating an old line inside a text file

Okay, so i have an issue trying to update a line or sentence in a text file.
The way my program works is this: If a user enters a question the program searches the text file for that exact question(lets say is n). The answer to the question would be on the following line(n + 1). My issue is trying to update the following line(n + 1) to some new line entered by the user.
I keep getting a Exception in thread "main" java.util.NoSuchElementException: No line found when i try to update the line in the text file. my removedata() is where i am trying to update the line of text.
Here is my code
public static void removedata(String s) throws IOException {
File f = new File("data.txt");
File f1 = new File("data2.txt");
BufferedReader input = new BufferedReader(new InputStreamReader(
System.in));
BufferedReader br = new BufferedReader(new FileReader(f));
PrintWriter pr = new PrintWriter(f1);
String line;
while ((line = br.readLine()) != null) {
if (line.contains(s)) {
System.out.println("Enter new Text :");
String newText = input.readLine();
line = newText;
System.out.println("Thank you, Have a good Day!");
}
pr.println(line);
}
br.close();
pr.close();
input.close();
Files.move(f1.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
public static void parseFile(String s) throws IOException {
File file = new File("data.txt");
Scanner scanner = new Scanner(file);
Scanner forget = new Scanner(System.in);
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
System.out.println(scanner.nextLine());
System.out
.println(" Would you like to update this information ? ");
String yellow = forget.nextLine();
if (yellow.equals("yes")) {
removedata(scanner.nextLine()); // NoSuchElementException
// error
} else if (yellow.equals("no")) {
System.out.println("Have a good day");
// break;
}
}
}
}
public static void getinput() throws IOException {
Scanner scanner = new Scanner(System.in);
String input = null;
/* End Initialization */
System.out.println("Welcome ");
System.out.println("What would you like to know?");
System.out.print("> ");
input = scanner.nextLine().toLowerCase();
parseFile(input);
}
public static void main(String args[]) throws ParseException, IOException {
/* Initialization */
getinput();
}
My text file is :
what is the textbook name?
the textbook name is Java
how is the major?
the major is difficult
how much did the shoes cost?
the shoes cost ten dollars
Can someone help me solve this issue?
Change the code in the if block in parsefile to
String temp = scanner.nextLine();
System.out.println(temp);
System.out
.println(" Would you like to update this information ? ");
String yellow = forget.nextLine();
if (yellow.equals("yes")) {
removedata(temp); // NoSuchElementException
// error
} else if (yellow.equals("no")) {
System.out.println("Have a good day");
// break;
}
for an explanation why this works, look at Nick L.s answer.
The problem is here:
while (scanner.hasNextLine()) { //(1)
final String lineFromFile = scanner.nextLine(); //(2)
if (lineFromFile.contains(s)) { //(3)
System.out.println(scanner.nextLine()); //(4)
//....
String yellow = forget.nextLine(); //(5)
if (yellow.equals("yes")) {
removedata(scanner.nextLine()); //(6)
}
}
//....
}
First of all, you are correctly iterating the scanner lines checking whether there is a line (1). Now, you are getting the first line of the scanner on (2), but if the condition (3) succeeds, you are retrieving the next line again at (4) inside System.out.println(....). Same thing applies to (5) and (6) accordingly.
Now, imagine that you have reached the end of file at (2) and the condition at (3) succeeds. You will receive an exception of no such line, as you logically have. The same can happen at (5) and (6).
Each call of the nextLine(), will get the next line of the file opened on the stream.
I suggest that you do one readline inside the loop, then apply the received string when needed.

How can I display file with line numbers in my Java program?

I want my program to display the contents of the file the user inputs with each line preceded with a line number followed by a colon. The line numbering should start at 1.
This is my program so far:
import java.util.*;
import java.io.*;
public class USERTEST {
public static void main(String[] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a file name: ");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
String line = inputFile.nextLine();
while (inputFile.hasNext()){
String name = inputFile.nextLine();
System.out.println(name);
}
inputFile.close();
}
}
I can display the contents of the file so far, but I don't know how to display the contents with the line numbers.
Integer i = 0;
while (inputFile.hasNext()) {
i++;
String line = inputFile.nextLine();
System.out.println(i.toString() + ": " + line);
}
You just need to concat an index to your output string.
int i=1;
while (inputFile.hasNext()){
String name = inputFile.nextLine();
System.out.println(i+ ","+name);
i++;
}
int lineNumber=0;
while (inputFile.hasNext()){
String name = inputFile.nextLine();
`System.out.println(lineNumber+ ":"+name);`
linenumber++;
}
Use an int initialized to 1 and increment it every time you read a line, then just output it before the line contents.
What about creating a numerical counter (increased every time you read a line) ... and putting that in front of the string that you are printing?

Writing integers to a file errors

Here's my code:
public static void main(String[] args) throws IOException {
writeToFile ("c:\\scores.txt");
processFile("c:\\scores.txt");
}
public static void writeToFile (String filename) throws IOException {
BufferedWriter outputWriter = new BufferedWriter(new FileWriter(filename));
Scanner reader = new Scanner (System.in);
int Num;
System.out.println ("Please enter 7 scores");
for (int i = 0; i < 7; i++) {
Num= reader.nextInt ();
outputWriter.write(Num);
if(i!=6) {
outputWriter.newLine();
}
}
outputWriter.flush();
outputWriter.close();
}
public static void processFile (String filename) throws IOException, FileNotFoundException
{
double sum=0.00;
double number;
double average;
int count = 0;
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream(filename)));
String line;
while((line = inputReader.readLine()) != null)
{
number= Double.parseDouble(line);
System.out.println(number);
count ++;
sum += (number);
System.out.print ("Total Sum: ");
System.out.println(sum);
System.out.print("Average of Scores: ");
average=sum/count;
System.out.println(average);
}
inputReader.close();
}
This is what my output is.
Please enter 7 scores
2
3
5
6
8
9
1
Exception in thread "main" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1011)
at java.lang.Double.parseDouble(Double.java:540)
at writefile.Writefile.processFile(Writefile.java:52)
at writefile.Writefile.main(Writefile.java:19)
Java Result: 1
I do not know how to fix this. I'm not sure how to fiz the floating decimal or empty string error.The file has weird symbols in it, no integers. How do I fix this? Please be specific please as I'm only a beginner at Java.
outputWriter.write(1); does not mean outputWriter.write("1");
you need change outputWriter.write(Num); to outputWriter.write(""+Num);
please refer outputstream.write(int)
The error happens because line is an empty string at some point, test for this before parsing the string:
while ((line = inputReader.readLine()) != null) {
if (line.trim().length() > 0) {
number = Double.parseDouble(line);
// rest of loop
}
}
That is, assuming that the line contains only numbers. If there are other characters, you'll have to perform a more careful validation before parsing the line.
The file has weird symbols in it, no integers.
From BufferedWriter#write(int):
Writes a single character.
So it's not writing the int value you're sending to it, instead its character representation.
It would be better if you just write the numeric value as String and then retrieve it as String and parse it. In your writeToFile method, modify this part
for (int i = 0; i < 7; i++) {
Num = reader.nextInt ();
outputWriter.write(Integer.toString(Num));
if(i!=6) {
outputWriter.newLine();
}
}

Categories