regext copying second, third and fourth word - java

I am trying to get the 2nd, 3rd, and 4th word from a file into another file, so far I know how to read a file and I have been trying different things but I don't get it right the code to get the words. This program will read the file.
import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
class PrintLines{
public static void main(String[] args) throws FileNotFoundException {
Scanner me = new Scanner(System.in);
System.out.print("File Name: ");
String s = me.next();
File inFile = new File(s);
Scanner in = new Scanner(inFile);
while(in.hasNextLine()){
String line = in.nextLine();
System.out.print(line + "\n");
}
in.close();
}
}
I have tried:
int i=0;
while(!Character.isDigit(in.charAt(i))){
i++;
}
to skip the first numbers, and then get the next three words, but I don't get it right:
986 Nasir 829 0.0040 Janine 1352 0.0069
I would appreciate any advice. Thank you

You can use String.split method
String[] split = line.split(" "); // split by space
System.out.println(split[1] + split[2] + split[3]); // watch out for the array's bounds

Related

Printer Writer making me input twice to loop once

I know this is going to be stupid easy to fix but I've been battling it for an hour. I need to keep getting words from the user until they type "quit" and write them to a file in the process. But here's the problem, it comes up with the "Enter Word: " but then I type it and hit enter it doesnt take it until I write something a SECOND time then it works and uses the second one.
//#Author: Tyler Cage
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class week12Program1 {
public static void main(String[] args) throws FileNotFoundException, IOException{
//declaring the writer and initlizing it
FileOutputStream fileByteStream = new FileOutputStream("C:/Users/tyl3r/Desktop/test.txt");
PrintWriter outFS = new PrintWriter(fileByteStream);
Scanner scnr = new Scanner(System.in);
//declainrg ints
int i = 0;
//open file and print
while(i<1){
System.out.println("Enter word: ");
outFS.println(scnr.next());
outFS.flush();
if(scnr.next().equalsIgnoreCase("quit")){
System.out.println("Shutting down...");
fileByteStream.close();
i++;
}
}
}
}
The problem in this section of code:
while(i<1){
System.out.println("Enter word: ");
outFS.println(scnr.next()); // first time scanning input
outFS.flush();
if(scnr.next().equalsIgnoreCase("quit")){ // second time scanning input
System.out.println("Shutting down...");
fileByteStream.close();
i++;
}
Actually you are reading the inputs 2 times so you need to enter the word another time to get the expected result.
To solve the problem you only need to declare variable to save input in it and then check the variable content at if condition:
while(i<1){
System.out.println("Enter word: ");
String word = scnr.next();
outFS.println(word);
outFS.flush();
if(word.equalsIgnoreCase("quit")){
System.out.println("Shutting down...");
fileByteStream.close();
i++;
}

How to print a specific word in a text file in Java

so as you can see i have a text file that goes like this one:
unbelievable, un, believe, able
mistreatment, mis, treat, ment
understandable, understand, able
I need to get the morphemes or each word like for example if I typed in the word MISTREATMENT, the output would be MIS, TREAT, MENT and the root word is TREAT.
Here's my code so far:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class morph {
public static void main(String[] args) throws IOException {
System.out.println("Enter a word: ");
Scanner sc = new Scanner (System.in);
sc.nextLine();
BufferedReader br = new BufferedReader(new FileReader("C:/Users/xxxx/Desktop/morphemes.txt"));
String line = null;
while ((line = br.readLine()) != null) {
//i'm stuck
System.out.println("The morpheme words are: "); // EG: mis , treat, ment
System.out.println("The Root word is: "); // EG: treat
}
}
}
The output should be:
Enter a word: mistreatment
The morpheme words: mis, treat, ment
The root word is: treat
The question is how do i print a specific data in the text file. I don't know i am gonna use an if else statement or a dictionary. If you're gonna tell me that it should be a dictionary please help me out. This is an NLP topic btw
I guess the method String.split() can help you here.
public String[] words = line.split(String ",");
// Check if first word in the line equals to the input
if (words != null && !words.isEmpty() && words[0].equals(sc.toString()))
{
System.out.println("The morpheme words are: "+words[1]+words[2]);
System.out.println("The Root word is: "+words[2]);
}

Reading data from a table & parsing it

My code is designed to read the contents of a text file and check if the contents are entered in a format that is as follows:
john : martin : 2 : 1
and if that format is followed then it will output it in the format:
john [2] | martin [1]
or else it will be counted as an invalid result and the total numbers will not be added to it whereas if the results are in the format then they will get added to the total so with the example it would display the number of vaild results as 1, invalid as 0 and total number as 3.
My question is that my code doesn't work properly as I get this error:
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 reader.main(reader.java:33)
So how would I go about fixing this and reading and displaying the data in thee way that I want? Thanks in advance.
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Locale;
import java.util.Scanner;
public class reader {
/**
* #param args
* #throws FileNotFoundException
* #throws FileNotFoundException
* #throws FileNotFoundException when the file cannot be loaded
*/
public static void main(String[] args) throws FileNotFoundException {
String hteam;
String ateam;
int hscore;
int ascore;
Scanner s = new Scanner(new BufferedReader(new FileReader("results2.txt"))).useDelimiter(":");
// create a scanner which scans from a file and splits at each colon
while ( s.hasNext() ) {
hteam = s.next(); // read the home team from the file
ateam = s.next(); // read the away team from the file
hscore = s.nextInt(); //read the home team score from the file
ascore = s.nextInt(); //read the away team score from the file
System.out.print(hteam); // output the line of text to the console
System.out.print(hscore);
System.out.print(ateam);
System.out.println(ascore);
}
System.out.println("\nEOF"); // Output and End Of File message.
}
}
You're looking for s.next() instead of s.nextLine().
hteam = s.nextLine() reads the entire line "john : martin : 2 : 1", leaving nothing left for ateam.
Edit:
As you've said this still isn't working, I'd guess that you have an extra newline at the end of your input file, which is causing s.hasNext() to evaluate to true. This would cause the Scanner to trip up when it's getting the next input line.
Try Scanner s = new Scanner(System.in).useDelimiter("\\s*:\\s*|\\s*\\n\\s*"); to read multiple lines.
See implementation: http://ideone.com/yfiR2S
To verify that a line is in the correct format, I'd (with inspiration from osoblanco's answer) check that there are 4 words and that the last two are integers:
public static boolean verifyFormat(String[] words) {
// see endnote for isInteger()
return words.length == 4 && /*isInteger(words[2]) && isInteger(words[3])*/;
}
public static void main(String[] args) throws FileNotFoundException {
String hteam;
String ateam;
int hscore;
int ascore;
Scanner s = new Scanner(new BufferedReader(
new FileReader("results2.txt"))).useDelimiter("\\s*:\\s*|\\s*\\n\\s*");
while (s.hasNext()) {
String line = s.nextLine();
String[] words = line.split("\\s*:\\s*");
if(verifyFormat(words)) {
hteam = words[0]; // read the home team
ateam = words[1]; // read the away team
hscore = Integer.parseInt(words[2]); //read the home team score
ascore = Integer.parseInt(words[3]); //read the away team score
System.out.print(hteam); // output the line of text to the console
System.out.print(hscore);
System.out.print(ateam);
System.out.println(ascore);
}
}
System.out.println("EOF");
}
isInteger() can be found here.
I think scanning isn't quite what you want here. I would just use a BufferedReader and do ReadLine to handle 1 line each time through the for loop.
Then verify each line by the following:
1) String.split(":") and verify 4 pieces.
String [] linePieces = nextLine.split(":");
if(linePieces.length!=4)
{
//mark invalid, continue loop
}
2) Trim each piece
for(int i =0; i<4; i++)
linePieces[i] = linePieces[i].trim();
3) Verify piece 3 and piece 4 are numbers, Integer.parseInt with try/catch. In the catch block, count that the line is invalid.
try
{
name1=linePieces[0];
name2=linePieces[1];
score1=Integer.parseInt(linePieces[2]);
score2=Integer.parseInt(linePieces[3]);
//count as success and do logic
}catch(NumberFormatException e){
//invalid line
}

Error using Substring : String Index out of range : -1 *Java*

In this program I am just getting input from a file and trying to get the boys name and the girls name out of it, and also put them in separate files. I have done everything just as the book has stated. And I've also searched everywhere online for help with this but cant seem to find anyone with the same problem. Ive seen problems where its not -1 but a positive number because they went to far out of the string calling a substring over the strings length. But cant seem to figure out this giving me -1 since i's value is 1.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.ArrayList;
public class Homework_11_1 {
public static void main(String[] args)throws FileNotFoundException
{
File inputFile = new File("babynames.txt");
Scanner in = new Scanner(inputFile);
PrintWriter outBoys = new PrintWriter("boys.txt");
PrintWriter outGirls = new PrintWriter("girls.txt");
while (in.hasNextLine()){
String line = in.nextLine();
int i = 0;
int b = 0;
int g = 0;
while(!Character.isWhitespace(line.charAt(i))){ i++; }
while(Character.isLetter(line.charAt(b))){ b++; }
while(Character.isLetter(line.charAt(g))){ g++; }
String rank = line.substring(i);
String boysNames = line.substring(i, b);
String girlsNames = line.substring(b, g);
outBoys.println(boysNames);
outGirls.println(girlsNames);
}
in.close();
outBoys.close();
outGirls.close();
System.out.println("Done");
}
}
Here is the txt file
1 Jacob Sophia
2 Mason Emma
3 Ethan Isabella
4 Noah Olivia
5 William Ava
6 Liam Emily
7 Jayden Abigail
8 Michael Mia
9 Alexander Madison
10 Aiden Elizabeth
I would have written it an other way, using split.
public static void main(String[] args)throws FileNotFoundException
{
File inputFile = new File("babynames.txt");
Scanner in = new Scanner(inputFile);
PrintWriter outBoys = new PrintWriter("boys.txt");
PrintWriter outGirls = new PrintWriter("girls.txt");
while (in.hasNextLine()){
String line = in.nextLine();
String[] names = line.split(" "); // wile give you [nbr][boyName][GirlName]
String boysNames = names[1];
String girlsNames = names[2];
outBoys.println(boysNames);
outGirls.println(girlsNames);
}
in.close();
outBoys.close();
outGirls.close();
System.out.println("Done");
}
Rather than fuss with loops and substring(), I'd just use String.split(" "). Of course, the assignment may not permit you to do this.
But anyway, without giving you the answer to the assignment, I can tell you that your logic is wrong. Walk through it and find out why. If you try running this code on just the first line of the input file, you'll get these values: i=1, b=0, and g=0. Calling line.substring(1,0) is obviously not going to work.

Adding new objects to a list; (For loop not working properly)

So I'm trying to add a names to a new list from a file called directory.txt that has 1000 objects that contain a first name, last name, and a phone number; something like this (Dodge, Nick 765-123-2312). When I run the program below without a "for loop" I can add the first object off the .txt file successfully and it prints it out. However when I add a for loop like, for(int i =0; i < 1000; i++), it for some reason jumps to the end off the list and inputs the 1000 object in the first spot and skips the rest. I can't figure this out! Thanks for the help.
new code;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import bsu.edu.cs121.names.Names;
import bsu.edu.cs121.quickSort.QuickSort;
public class NameTester {
public static void main(String[] args)throws FileNotFoundException {
ArrayList<Names> namelist= new ArrayList<Names>();
Scanner file = new Scanner(System.in);
System.out.println("Please enter the name of the phone book file: ");
String newFile = file.next();
File inputFile = new File("/Users/Latif/Desktop/workspace/CS121 Project4/src/" + newFile);
Scanner readFile = new Scanner(inputFile);
while (readFile.hasNextLine()){ //start while
String lastName = readFile.next();
String firstName = readFile.nextLine();
String phoneNumber = readFile.nextLine();
namelist.add(new Names(firstName, lastName, phoneNumber));
}
QuickSort newSort = new QuickSort(namelist);
System.out.println(namelist.get(1) + " " + namelist.get(2));
}
}
Because you are inserting the name data into index [0] of your nameslist array every time, so every loop you are replacing your previous data and at the very end you end up with one item that equals your last entry. You need to assign the proper array index to each.
nameslist[i] = new Names(first, last, number);

Categories