Extraction of string and integer from txt - java

I'm trying to make a simple scanner reader to read from a txt stored in C:\Users\james\Desktop\project\files\ and it's called data "data.txt", the thing is that the information stored is like this:
ASSETS 21
CHOROY 12
SHELL 9
So as you can see the spaces between the string and the integer that I want o extract are random. I was trying to make this:
public data(String s) //s is the name of the txt "data.txt"
{
if (!s.equalsIgnoreCase("Null"))
{
try {
File text = new File(s);
Scanner fileReader = new Scanner(text);
while (fileReader.hasNextLine())
{
String data = fileReader.nextLine();
String[] dataArray = data.split(" ");
String word = dataArray[0];
String number = dataArray[1];
int score = Integer.parseInt(number);
addWord(word, score);
}
fileReader.close();
}
catch (FileNotFoundException e)
{
System.out.println("File not found");
e.printStackTrace();
}
System.out.println("Reading complete");
}
But the split is only with one empty space between the string and the integer so I would like to know how can I extract that two things that are separated with any number of spaces in the same line. Example:
Line readed: HOUSE 1 -> String word = "HOUSE"; int score = "1";
Line readed: O 5 -> String word = "O"; int score = "5";

Instead of data.split(" ")
you can use
data.split("\\s+")
Also your function won't compile because it does not have any return.

Related

Read a random word from a file for user to guess - Java

I'm write a code that pulls a word from a file and guesses it. For instance the word would be "apple".
The user will see: *****
If they input 'p' as a guess they see: *pp**
So far it's working if I manually the word apple in a variable called secretPhrase, however I'm not sure how to have the program pull the word from a text file and store it into secretPhrase for the user to guess.
public static void main(String args[]) {
String secretPhrase = "apple";
String guesses = " ";
Scanner keyboard = new Scanner(System.in);
boolean notDone = true;
Scanner word = new Scanner(System.in);
System.out.print("Enter a word: ");
while(true) {
notDone = false;
for(char secretLetter : secretPhrase.toCharArray()) {
if(guesses.indexOf(secretLetter) == -1) {
System.out.print('*');
notDone = true;
} else {
System.out.print(secretLetter);
}
}
if(!notDone) {
break;
}
System.out.print("\nEnter your letter:");
String letter = keyboard.next();
guesses += letter;
}
System.out.println("Congrats");
}
You have several options. One is to do the following. It is not complete and doesn't check on border cases. But you can figure that out. It presumes the file contains one word per line.
try {
RandomAccessFile raf = new RandomAccessFile(
new File("wordfile.txt"), "r");
Random r = new Random();
// ensure the length is an int
int len = (int)(raf.length()&0x7FFFFFFF);
// randomly select a location
long loc = r.nextInt(len);
// go to that file location
raf.seek(loc);
// find start of next line
byte c = raf.readByte();
while((char)c != '\n') {
c = raf.readByte();
}
// read the line
String line = raf.readLine();
System.out.println(line);
} catch (Exception e) {
e.printStackTrace();
}
}
A much easier solution for perhaps a smaller set of words is to just read them into a List<String> and the do a Collections.shuffle() to randomize them. Then just use them in the shuffled order.

How to find a word is in which line of a text file and if the word exists in multiple line save the line number?

I could find the occurrence of the word but couldn't locate which line numbers is the word present and any way to save the line numbers like in arraylist?
File f1=new File("input.txt")
String[] words=null; //Intialize the word Array
FileReader fr = new FileReader(f1); //Creation of File Reader object
BufferedReader br = new BufferedReader(fr);
String s;
String input="Java"; // Input word to be searched
int count=0; //Intialize the word to zero
while((s=br.readLine())!=null) //Reading Content from the file
{
words=s.split(" "); //Split the word using space
for (String word : words)
{
if (word.equals(input)) //Search for the given word
{
count++; //If Present increase the count by one
}
}
}
if(count!=0) //Check for count not equal to zero
{
System.out.println("The given word is present for "+count+ " Times in the file");
}
else
{
System.out.println("The given word is not present in the file");
}
fr.close();
}
}
Try using LineNumberReader instead of BufferedReader. It supports BufferedReader and LineNumber.
Javadocs for more information - https://docs.oracle.com/javase/8/docs/api/java/io/LineNumberReader.html.
Example -
LineNumberReader lineNumberReader =
new LineNumberReader(new FileReader("c:\\data\\input.txt"));
int data = lineNumberReader.read();
while(data != -1){
char dataChar = (char) data;
data = lineNumberReader.read();
// your word processing happens here
int lineNumber = lineNumberReader.getLineNumber();
}
lineNumberReader.close();
http://tutorials.jenkov.com/java-io/linenumberreader.html
Have a counter and count for each line.
long count = 0;
long lineNumberCounter = 0;
List<Long> lineNumbers = new ArrayList<>();
try (BufferedReader b = new BufferedReader(new java.io.FileReader(new File(fileName)))) {
String readLine = "";
System.out.println("Reading file using Buffered Reader");
while ((readLine = b.readLine()) != null) {
// Here is line number counter
lineNumberCounter++;
String[] words = readLine.split(" "); // Split the word using space
System.out.println(Arrays.toString(words));
for (String word : words) {
// Search for the given word
if (word.trim().equals(input)) {
count++; // If Present increase the count by one
System.out.println("Word " + input + " found in line " + lineNumberCounter);
lineNumbers.add(lineNumberCounter);
}
}
}
}
// Check for count not equal to zero
if (count != 0) {
System.out.println("The given word is present for " + count + " Times in the file");
} else {
System.out.println("The given word is not present in the file");
}
I think this will help.
All you have to do is track the line number and then save the line where the word is available
File f1=new File("input.txt")
String[] words=null; //Intialize the word Array
FileReader fr = new FileReader(f1); //Creation of File Reader object
BufferedReader br = new BufferedReader(fr);
String s;
String input="Java"; // Input word to be searched
int count=0; //Intialize the word to zero
// for keeping track of the line numbers
int lineNumber= 0;
//arraylist to save the numbers
List<int> lineNumberList = new ArrayList<>();
while((s=br.readLine())!=null) //Reading Content from the file
{
// increase the line number as we move on to the next line
lineNumber++;
words=s.split(" "); //Split the word using space
// this is required so that same line number won't be repeated on the arraylist
boolean flag = true;
for (String word : words)
{
if (word.equals(input)) //Search for the given word
{
count++; //If Present increase the count by one
if(flag){
lineNumberList.add(lineNumber);
flag=false;
}
}
}
}
if(count!=0) //Check for count not equal to zero
{
System.out.println("The given word is present for "+count+ " Times in the file");
}
else
{
System.out.println("The given word is not present in the file");
}
fr.close();
}
}

Scanning input into char array Java

I was trying to store input as
5
3DRP 3QEW
8AQW 9ADA
I want to read that input in as a copy paste and put it. I've tried this:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String userNumber;
userNumber = scan.nextLine();
String[] tokens = userNumber.split("[ ]");
System.out.println(tokens[1]);
for(int i = 0; i < tokens.length;i++) {
System.out.println(tokens[i]);
}
scan.close();
}
My goal is to basically read that input in as a copy paste into the IDE or through a file a .txt and then store every single character besides whitespaces into a char array that is 1d or 2d.
From what I understand, you want to read 3 lines from the console, remove all the white spaces from that text and store it as a char array.
If that is the case, here is how you could do that:
int numberOfLinesToRead = 3;
try(Scanner sc = new Scanner(System.in)){
StringBuilder buff = new StringBuilder();
while(numberOfLinesToRead-- > 0){
String line = sc.nextLine();
String noSpaces = line.replaceAll("\\s", "");
buff.append(noSpaces);
}
char[] characters = buff.toString().toCharArray();
System.out.println(Arrays.toString(characters));
}catch (Exception e) {
e.printStackTrace();
}

How to capitalize first letter in this program

I've written majority of this. I just can't figure out how to capitalize the first letter of each line. the problem is:
Write a program that checks a text file for several formatting and punctuation matters. The program asks for the names of both an input file and an output file. It then copies all the text from the input file to the output file, but with the following two changes (1) Any string of two or more blank characters is replaced by a single blank; (2) all sentences start with an uppercase letter. All sentences after the first one begin after either a period, a question mark, or an exclamation mark that is followed by one or more whitespace characters.
I've written most of the code. I just need help with the capitalization of the first letter of each sentence. Here's my code:
import java.io.*;
import java.util.Scanner;
public class TextFileProcessor
{
public static void textFile()
{
Scanner keyboard = new Scanner(System.in);
String inputSent;
String oldText;
String newText;
System.out.print("Enter the name of the file that you want to test: ");
oldText = keyboard.next();
System.out.print("Enter the name of your output file:");
newText = keyboard.next();
System.out.println("\n");
try
{
BufferedReader inputStream = new BufferedReader(new FileReader(oldText));
PrintWriter outputStream = new PrintWriter(new FileOutputStream(newText));
inputSent = inputStream.readLine();
inputSent = inputSent.replaceAll("\\s+", " ").trim();
inputSent = inputSent.substring(0,1).toUpperCase() + inputSent.substring(1);
inputSent = inputSent.replace("?", "?\n").replace("!", "!\n").replace(".", ".\n");
//Find a way to make the first letter capitalized
while(inputSent != null)
{
outputStream.println(inputSent);
System.out.println(inputSent);
inputSent = inputStream.readLine();
}
inputStream.close();
outputStream.close();
}
catch(FileNotFoundException e)
{
System.out.println("File" + oldText + " could not be located.");
}
catch(IOException e)
{
System.out.println("There was an error in file" + oldText);
}
}
}
import java.util.Scanner;
import java.io.*;
public class TextFileProcessorDemo
{
public static void main(String[] args)
{
String inputName;
String result;
String sentence;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the name of your input file: ");
inputName = keyboard.nextLine();
File input = new File(inputName);
PrintWriter outputStream = null;
try
{
outputStream = new PrintWriter(input);
}
catch(FileNotFoundException e)
{
System.out.println("There was an error opening the file. Goodbye!" + input);
System.exit(0);
}
System.out.println("Enter a line of text:");
sentence = keyboard.nextLine();
outputStream.println(sentence);
outputStream.close();
System.out.println("This line was written to:" + " " + input);
System.out.println("\n");
}
}
Since your code already contains inputSent = inputSent.substring(0,1).toUpperCase() + inputSent.substring(1); I assume that inputSent can contain more than one sentence or might just represent a line of the file with parts of sentences.
Thus I'd suggest you first read the entire file into a string (if it's not too large) and then use split() on that string to break it into individual sentences, capitalize the first character and join them again.
Example:
String[] sentences = fileContent.split("(?<=[?!.])\\s*");
StringBuilder result = new StringBuilder();
for( String sentence : sentences) {
//append the first character as upper case
result.append( Character.toUpperCase( sentence.charAt(0) ) );
//add the rest of the sentence
result.append( sentence.substring(1) );
//add a newline
result.append("\n");
}
//I'd not replace the input, but to be consistent with your code
fileContent = result.toString();
The easiest way is maybe using WordUtil from Apache commons-langs.
You should use the capitalise method with the delimiters as parameter.
You can try the following regular expression:
(\S)([^.!?]*[.!?]( |$))
Code:
public static void main(String[] args) {
String inputSent = "hi! how are you? fine, thanks.";
inputSent = inputSent.replaceAll("\\s+", " ").trim();
Matcher m = Pattern.compile("(\\S)([^.!?]*[.!?]( |$))").matcher(inputSent);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, m.group(1).toUpperCase() + m.group(2) + "\n");
}
m.appendTail(sb);
System.out.println(sb);
}
See a demo online.
Output:
Hi!
How are you?
Fine, thanks.
In the ASCII table lower and upper case are just integers that are 32 positions away from each other...
try something like this:
String inputSent = .... //where ever it does come from...
System.out.println(inputSent.replace(inputSent.charAt(0), (char) (inputSent.charAt(0) - 32)));
or use some kind of APACHE libs like WordUtils.
I would change the textFile() to the below:
public static void textFile()
{
Scanner keyboard = new Scanner(System.in);
String inputSent;
String oldText;
String newText;
System.out.print("Enter the name of the file that you want to test: ");
oldText = keyboard.next();
System.out.print("Enter the name of your output file:");
newText = keyboard.next();
System.out.println("\n");
try
{
BufferedReader inputStream = new BufferedReader(new FileReader(oldText));
PrintWriter outputStream = new PrintWriter(new FileOutputStream(newText));
while ((inputSent = inputStream.readLine()) != null) {
char[] chars = inputSent.toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
inputSent = new String(chars);
inputSent = inputSent.replaceAll("\\s+", " ").trim();
inputSent = inputSent.substring(0,1).toUpperCase() + inputSent.substring(1);
inputSent = inputSent.replace("?", "?\n").replace("!", "!\n").replace(".", ".\n");
System.out.println("-> " + inputSent);
outputStream.println(inputSent);
}
inputStream.close();
outputStream.close();
}
catch(FileNotFoundException e)
{
System.out.println("File" + oldText + " could not be located.");
}
catch(IOException e)
{
System.out.println("There was an error in file" + oldText);
}
}
This will read the text file line by line.
Upper the first char
Do this in a while loop
The problem with your original textFile() is that it only applies uppercase first char, blank space etc on the very first line it reads.

How do I achieve the following results using the PrinterWriter class from a text file?

My application here prompts the user for a text file, mixed.txt which contains
12.2 Andrew
22 Simon
Sophie 33.33
10 Fred
21.21 Hank
Candice 12.2222
Next, the application is to PrintWrite to all text files namely result.txt and errorlog.txt. Each line from mixed.txt should begin with a number first followed by a name. However, certain lines may contain the other way round meaning to say name then followed by a number. Those which begins with a number shall be added to a sum variable and written to the result.txt file while those lines which begin with the name along with the number shall be written to the errorlog.txt file.
Therefore, on the MS-DOS console the results are as follow:
type result.txt
Total: 65.41
type errorlog.txt
Error at line 3 - Sophie 33.33
Error at line 6 - Candice 12.2222
Ok here's my problem. I only managed to get up to the stage whereby I have had all numbers added to result.txt and names to errorlog.txt files and I have no idea how to continue from there onwards. So could you guys give me some advice or help on how to achieve the results I need?
Below will be my code:
import java.util.*;
import java.io.*;
class FileReadingExercise3 {
public static void main(String[] args) throws FileNotFoundException
{
Scanner userInput = new Scanner(System.in);
Scanner fileInput = null;
String a = null;
int sum = 0;
do {
try
{
System.out.println("Please enter the name of a file or type QUIT to finish");
a = userInput.nextLine();
if (a.equals("QUIT"))
{
System.exit(0);
}
fileInput = new Scanner(new File(a));
}
catch (FileNotFoundException e)
{
System.out.println("Error " + a + " does not exist.");
}
} while (fileInput == null);
PrintWriter output = null;
PrintWriter output2 = null;
try
{
output = new PrintWriter(new File("result.txt")); //writes all double values to the file
output2 = new PrintWriter(new File("errorlog.txt")); //writes all string values to the file
}
catch (IOException g)
{
System.out.println("Error");
System.exit(0);
}
while (fileInput.hasNext())
{
if (fileInput.hasNextDouble())
{
double num = fileInput.nextDouble();
String str = Double.toString(num);
output.println(str);
} else
{
output2.println(fileInput.next());
fileInput.next();
}
}
fileInput.close();
output.close();
output2.close();
}
}
This is the screenshot of the mixed.txt file:
You can change your while loop like this:
int lineNumber = 1;
while (fileInput.hasNextLine()) {
String line = fileInput.nextLine();
String[] data = line.split(" ");
try {
sum+= Double.valueOf(data[0]);
} catch (Exception ex) {
output2.println("Error at line "+lineNumber+ " - "+line);
}
lineNumber++;
}
output.println("Total: "+sum);
Here you can go through each line of the mixed.txt and check if it starts with a double or not. If it is double you can just add it to sum or else you can add the String to errorlog.txt. Finaly you can add the sum to result.txt
you should accumulate the result and after the loop write the summation, also you can count the lines for error using normal counter variable. for example:
double mSums =0d;
int lineCount = 1;
while (fileInput.hasNext())
{
String line = fileInput.nextLine();
String part1 = line.split(" ")[0];
if ( isNumeric(part1) ) {
mSums += Double.valueOf(part1);
}
else {
output2.println("Error at line " + lineCount + " - " + line);
}
lineCount++;
}
output.println("Totals: " + mSums);
// one way to know if this string is number or not
// http://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-a-numeric-type-in-java
public static boolean isNumeric(String str)
{
try
{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
this will give you the result you want in error files:
Error at line 3 - Sophie 33.33
Error at line 6 - Candice 12.2222

Categories