This is the question from my assignment that I am unsure of:
The class is to contain a public method nextWord(). When a new line is read, use the String method .split("\s+") to create an array of the words that are on the line. Each call to the nextWord() method is to return the next word in the array. When all of the words in the array have been processed, read the next line in the file. The nextWord()method returns the value null when the end of the file is reached.
I have read the file, and stored each individual string in an array called tokenz.
I'm not sure how I can have a method called "nextWord" which returns each individual word from tokenz one at a time. Maybe I don't understand the question?
The last part of the question is:
In your main class, write a method named processWords() which instantiates the MyReader class (using the String "A2Q2in.txt"). Then write a loop that obtains one word at a time from the MyReader class using the nextWord() method and prints each word on a new line.
I've thought of ways to do this but I'm not sure how to return each word from the nextWord method i'm supposed to write. I can't increase a count because after the String is returned, anything after the return statement cannot be reached because the method is done processing.
Any help would be appreciated, maybe I'm going about this the wrong way?
Can't use array lists or anything like that.
Here is my code.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class A2Q2
{
public static void main (String [] args)
{
processWords();
}
public static void processWords()
{
MyReader reader = new MyReader("A2Q2.txt");
String[] words = new String[174];
words[0] = reader.nextWord();
System.out.println(words[0]);
}
}
class MyReader
{
static String name;
static BufferedReader fileIn;
static String inputLine;
static int tokensLength = 0;
static String[] tokens;
static int counter = 0;
// constructor.
public MyReader(String name)
{
this.name = name;
}
public static String[] readFile()
{
String[] tokenz = new String[174];
int tokensLength = 0;
try
{
fileIn = new BufferedReader (new FileReader(name));
inputLine = fileIn.readLine();
while(inputLine !=null)
{
tokens = inputLine.split("\\s+");
for (int i = 0 ; i < tokens.length; i++)
{
int j = i + tokensLength;
tokenz[j] = tokens[i];
}
tokensLength = tokensLength + tokens.length;
inputLine = fileIn.readLine();
}
fileIn.close();
}
catch (IOException ioe)
{
System.out.println(ioe.getMessage());
ioe.printStackTrace();
}
//FULL ARRAY OF STRINGS IN TOKENZ
return tokenz;
}
public static String nextWord()
{
String[] tokenzz = readFile();
//????
return tokenzz[0];
}
}
Here's a conceptual model for you.
Keep track of your MyReader's state to know which value to return next.
the following example uses tokenIndex to decide where to read at next.
class MyReader
{
String[] tokens;
int tokenIndex = 0;
public String nextWord()
{
if(tokens == null || tokens.length <= tokenIndex)
{
// feel free to replace this line with whatever logic you want to
// use to fill in a new line.
tokens = readNextLine();
tokenIndex = 0;
}
String retVal = tokens[tokenIndex];
tokenIndex++;
return retval;
}
}
Mind you, this isn't a complete solution(it doesn't check for the end of file for instance), only a demonstration of the concept. You might have to elaborate a bit.
Use a loop and process each element in the array, printing them one at a time?
Related
I have a file reader that reads the text
(a,b) (b,c) (c,d) (f,g) (c,g) (c,t) (h,i) (j,y)
and displays
a,b
b,c ....
is there a way to use these indexes as arguments for a method I call right after i'm done reading it? so far I seem to only effect the string split while i'm inside my While loop, is there a way to take value a and use it for method like
add.edge("argument0","argument1") where 0 is a, and 1 is b?
Code:
import java.io.*;
class reader{
public static void main(String[] args)throws Exception{
File file = new File("test.txt");
BufferedReader fi = new BufferedReader(new FileReader(file));
String num;
int count = 0;
while ((num = fi.readLine()) !=null) {
String [] add = num.split(" ");
for(int i=0; i<add.length;i++){
String [] add2 =add[i].split("[)(]+");
for (String val: add2){
System.out.println(val);
}
}
}
}
}
i think you are trying to achieve some thing like following :D
i changed your code a little bit i used sub string instead of regular expression
import java.io.*;
class reader{
public static void main(String[] args)throws Exception{
File file = new File("test.txt");
BufferedReader fi = new BufferedReader(new FileReader(file));
String num;
int count = 0;
while ((num = fi.readLine()) !=null) {
String [] add = num.split(" ");
for(int i=0; i<add.length;i++){
String pair = add[i].substring(1, 4);
someFunction(pair.split(","));
}
}
}
public static void someFunction(String[] args)
{
if(args.length > 0)
System.out.println(args[0] + " and " + args[1]);
}
}
If you want to use the result of the split function outside the while loop you need to save the results to a variable that is defined before the while loop. This is because currently the scope of the add2 variable in inside the for loop and thus you will only be able to use it inside the for loop. If you want to save pairs of Strings then I suggest creating a helper class Pair:
class Pair {
private String el1;
private String el2;
public Pair(String el1, String el2) {
this.el1 = el1;
this.el2 = el2;
}
// getters
}
and make a list of pairs defined before the while loop:
List<Pair> pairs = new ArrayList<>();
and in your for loop, add new pairs to the list:
pairs.add(new Pair(add2[0], add[1])));
Then you can access the list elements outside the while loop like so:
for (Pair pair : pairs) {
add.edge(pair.getEl1(), pair.getEl2());
}
I'm working on a project for university and I'm having some problems when it comes to understand how does a class with a method to read given by our professor works.
We are supposed to be able to use that method to read words in lines from a text file. However, I don't really understand how it works. If anyone could help me, as well as explaining to me how can I use it to read the files, I'd be so grateful.
Here's the class with the method called read() as well as the methods and variables used by it :
public static final char blank = ' ';
public static final char endOfSequence = '\n'; //the lines in the file end with '\n'
private static final int MAX = 20;
public static char[] letters;
public static int length;
private static char letter = ' ';
private static char[] phrase = null;
private static int index;
public Word() {
letters = new char[MAX];
length = 0;
}
public static Word read() {
Word wd = new Word();
jumpBlanks();
while ((letter != endOfSequence) && // Sequence hasn't finished
(letter != blank)) {
wd.letters[wd.length] = letter;
letter = readCharKeyB();
}
return wd;
}
public static void jumpBlanks() { //reading blanks until finding a word
while (letter == blank) {
letter = readCharKeyB();
}
}
static public char readCharKeyB() {
char res = '.';
if (phrase != null) {
res = phrase[index++];
}
return res;
}
I have to use it, as I said, to read lines from a file that looks like this:
t1 #n name #d address
t2 #n name #d address
...
I have to check first how the line starts (t1, t2, t3) then I have to read the name, between #n and #d, and then the address, between #d and \n. And I have to use that class above with those methods.
This is what I have so far, but doesn't work:
public static void generador_de_cartas() throws Exception {
FileReader fr = new FileReader("datos_clientes.txt");
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
char [] linea = line.toCharArray();
while (line != null){
linea=Word.leer(); //I don't know how to use it properly
line=br.readLine();
}
br.close();
fr.close();
}
Please, could someone explain to me how the method works and how can I make it work for reading a file so I can figure out how to use it?
Thanks!
This is my method for adding each line of code:
public static void String(){
File f = new File("src/testClass.java");
try {
Scanner s = new Scanner(f);
s.useDelimiter("\\n");
while(s.hasNextLine()){
String st = s.next();
if(!st.equals("\\p{Space}")) System.out.println(st);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Here is the testClass.java
public class testClass {
public static void main (String[] args){
int someNum = 1; //comment
String someStr = "haha";
/* final double pi = 3.14159;
*
*/
}
public static void uselessMethod(int someNum){
boolean isUseless1 = true;
}
}
When I use this class to test my parser, it doesn't skip over the blank space after the brace underneath the closing bracket for main. What needs to be done to not get it to be stored? What is the more appropriate if statement to get it to not store that blank line, while acknowledging that it is a line rather than skipping over it completely? I want to keep track of the line number while not storing the blank lines.
You want to use the matches() method instead of equals():
if(!st.matches("^\\p{Space}*$")) System.out.println(st);
I've also modified your regular expression a little bit. It should now exclude all lines that are empty or contain only whitespace.
I usually just skip empty line:
public static List<String> fileToList(String patch) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(patch));
String line ="";
List<String> result = new ArrayList<>();
while ((line = br.readLine()) != null) {
/*
* Just skip empty line
*/
if (line.isEmpty()) {
continue;
} else {
result.add(line);
}
}
return result;
}
I am writing a Java program. I need help with the input of the program, that is a sequence of lines containing two tokens separated by one or more spaces.
import java.util.Scanner;
class ArrayCustomer {
public static void main(String[] args) {
Customer[] array = new Customer[5];
Scanner aScanner = new Scanner(System.in);
int index = readInput(aScanner, array);
}
}
It is better to use value.trim().length()
The trim() method will remove extra spaces if any.
Also String is assigned to Customer you will need to create a object out of the String of type Customer before assigning it.
Try this code... You can put the file you want to read from where "stuff.txt" currently is. This code uses the split() method from the String class to tokenize each line of text until the end of the file. In the code the split() method splits each line based on a space. This method takes a regex such as the empty space in this code to determine how to tokenize.
import java.io.*;
import java.util.ArrayList;
public class ReadFile {
static ArrayList<String> AL = new ArrayList<String>();
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("stuff.txt"));
String datLine;
while((datLine = br.readLine()) != null) {
AL.add(datLine); // add line of text to ArrayList
System.out.println(datLine); //print line
}
System.out.println("tokenizing...");
//loop through String array
for(String x: AL) {
//split each line into 2 segments based on the space between them
String[] tokens = x.split(" ");
//loop through the tokens array
for(int j=0; j<tokens.length; j++) {
//only print if j is a multiple of two and j+1 is not greater or equal to the length of the tokens array to preven ArrayIndexOutOfBoundsException
if ( j % 2 ==0 && (j+1) < tokens.length) {
System.out.println(tokens[j] + " " + tokens[j+1]);
}
}
}
} catch(IOException ioe) {
System.out.println("this was thrown: " + ioe);
}
}
}
I created two arrays and assigned states to one array and capitals to the other array that I got from a text file. The text file is formatted like this:
Colorado,Denver,
Wisconsin,Madison,
..........etc
My code is as follows:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class StatesAndCapitals {
public static void main(String[] args) throws FileNotFoundException {
FileInputStream is = new FileInputStream("capitals.txt");
Scanner input = new Scanner(is);
String[] states = new String[50];
String[] capitals = new String[50];
for (int i = 0; i < states.length; i++){
String currentLine = input.nextLine();
int a = currentLine.indexOf(",");
String states1 = currentLine.substring(0, a);
states[i] = states1;
int b = currentLine.lastIndexOf(",");
String capitals1 = currentLine.substring(a+1, b);
capitals[i] = capitals1;
}//end for loop
}
}
The point of my program is to ask "What is the capital of (blank)?"
Then I need to tell the person if they are correct or not. The problem I'm having is that I don't know how to check if, for example, Madison is the capital of Wisconsin. Any help would be appreciated.
public static void main(String[] args) {
Scanner userInput = null;
Scanner scanner = null;
try {
userInput = new Scanner(System.in);
scanner = new Scanner(new File("capitals.txt"));
while (scanner.hasNext()) {
String[] stateAndCapital = scanner.next().split(",");
System.out.println(String.format("What is the capital of %s?",
stateAndCapital[0]));
System.out.println(userInput.next().equals(stateAndCapital[1]));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
scanner.close();
userInput.close();
}
}
output:
What is the capital of Colorado?
dunno
false
What is the capital of Wisconsin?
Madison
true
Try using this:
public boolean isCapitalOfState(String capital, String state) {
for (int i = 0; i < state.length; i++) {
if (state[i].equals(state) && capitals[i].equals(capital)) {
return true;
}
}
return false;
}
It loops through the array of states and once it has found the match, it will check if the capital matches, if so return true. If it has not found anything it will by default return false.
Note though that there are a lot of easier ways to achieve your behaviour. Generally, Lists are superior to Arrays.
EDIT: I see your question asks for a bit more, we here cannot give you a full program to do it. However do keep in mind that when you've already obtained an index in state, that you can check the result way easier than this.
These are setup like parallel arrays correct? Meaning for example states[0] = colorado, and capitals[0] = denver, it looks this way but if it is indeed setup like this use the index of the state as the index for the capital and compare the input against that.
For example,
System.out.println("What is the capital of " + states[i]);
capital = input.nextLine();
if(capital.equals(capitals[i]){
return true;
}
else{
return false;
}