using string splits as arguments to another method - java

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());
}

Related

search for multiple strings from a text file in java

I'm trying to search of multiple words given from a user ( i used array to store them in ) from one txt file , and then if that word presented once in the file it will be displayed and if it's not it won't.
also for the words itself , if it's duplicated it will search it once.
the problem now when i search for only one it worked , but with multiple words it keeps repeated that the word isn't present even if it's there.
i would like to know where should i put the for loop and what's the possible changes.
package search;
import java.io.*;
import java.util.Scanner;
public class Read {
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
String[] words=null;
FileReader fr = new FileReader("java.txt");
BufferedReader br = new BufferedReader(fr);
String s;
System.out.println("Enter the number of words:");
Integer n = sc.nextInt();
String wordsArray[] = new String[n];
System.out.println("Enter words:");
for(int i=0; i<n; i++)
{
wordsArray[i]=sc.next();
}
for (int i = 0; i <n; i++) {
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(wordsArray[i])) //Search for the given word
{
count++; //If Present increase the count by one
}
}
if(count == 1)
{
System.out.println(wordsArray[i] + " is unique in file ");
}
else if (count == 0)
{
System.out.println("The given word is not present in the file");
}
else
{
System.out.println("The given word is present in the file more than 1 time");
}
}
}
}
fr.close();
}
}
The code which you wrote is error prone and remember always there should be proper break condition when you use while loop.
Try the following code:
public class Read {
public static void main(String[] args)
{
// Declaring the String
String paragraph = "These words can be searched";
// Declaring a HashMap of <String, Integer>
Map<String, Integer> hashMap = new HashMap<>();
// Splitting the words of string
// and storing them in the array.
String[] words = new String[]{"These", "can", "searched"};
for (String word : words) {
// Asking whether the HashMap contains the
// key or not. Will return null if not.
Integer integer = hashMap.get(word);
if (integer == null)
// Storing the word as key and its
// occurrence as value in the HashMap.
hashMap.put(word, 1);
else {
// Incrementing the value if the word
// is already present in the HashMap.
hashMap.put(word, integer + 1);
}
}
System.out.println(hashMap);
}
}
I've tried by hard coding the values, you can take words and paragraph from the file and console.
The 'proper' class to use for extracting words from text is java.text.BreakIterator
You can try the following (reading line-wise in case of large files)
import java.text.BreakIterator;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import java.nio.file.Files;
import java.nio.file.Paths;
public class WordFinder {
public static void main(String[] args) {
try {
if (args.length < 2) {
WordFinder.usage();
System.exit(1);
}
ArrayList<String> argv = new ArrayList<>(Arrays.asList(args));
String path = argv.remove(0);
List<String> found = WordFinder.findWords(Files.lines(Paths.get(path)), argv);
System.out.printf("Found the following word(s) in file at %s%n", path);
System.out.println(found);
} catch (Throwable t) {
t.printStackTrace();
}
}
public static List<String> findWords(Stream<String> lines, ArrayList<String> searchWords) {
List<String> result = new ArrayList<>();
BreakIterator boundary = BreakIterator.getWordInstance();
lines.forEach(line -> {
boundary.setText(line);
int start = boundary.first();
for (int end = boundary.next(); end != BreakIterator.DONE; start = end, end = boundary.next()) {
String candidate = line.substring(start, end);
if (searchWords.contains(candidate)) {
result.add(candidate);
searchWords.remove(candidate);
}
}
});
return result;
}
private static void usage() {
System.err.println("Usage: java WordFinder <Path to input file> <Word 1> [<Word 2> <Word 3>...]");
}
}
Sample run:
goose#t410:/tmp$ echo 'the quick brown fox jumps over the lazy dog' >quick.txt
goose#t410:/tmp$ java WordFinder quick.txt dog goose the did quick over
Found the following word(s) in file at quick.txt
[the, quick, over, dog]
goose#t410:/tmp$

String Sorter Returing Exit Code 0 instead of the Strings

I am trying to make a string sorter that takes user input and puts it into alphabetical order. My code looks like this:
public class StringSorter {
public static void main(String[] argv) throws IOException {
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in), 1);
System.out.println("How many strings do you want to sort?");
int numStrings = Integer.parseInt(stdin.readLine());
System.out.println("Input Strings Here:");
String[] stringsToSort = new String[numStrings];
for (int i = 0; i < numStrings; i++) {
String s = stdin.readLine();
stringsToSort[i] = s;
}
int comparison = (stringsToSort[0].compareToIgnoreCase(stringsToSort[1]));
if (stringsToSort[0].compareToIgnoreCase(stringsToSort[1]) < 0) {
System.out.println("Alphabetical Order: " + Integer.toString(comparison));
}
}
}
How do I make it print the strings instead of "Exit Code 0"?
I forgot to add that I cannot use java.util.Arrays or java.util.Vector for this assignment
Right now you are printing the result of a comparison and not the string and you're only sorting the two first strings.
You call Array.sort() first and then you print the array. Replace your comparison and print with
Arrays.sort(stringsToSort);
for (String string : stringsToSort) {
System.out.println(string);
}
The code is going to print 1, if the first String is alphabetically smaller than the second String otherwise it will do nothing and return 0 exit code.
If you intend to do is print the array, you should iterate using a for loop on the elements of the array and print the element.
For sorting the array, you could use any of the sorting algos. Selection sort is the simplest to understand. Following is a link for sorting a String array.
http://web.cs.iastate.edu/~smkautz/cs227f12/examples/week11/SelectionSortExamples.java
You can use a custom sorting like this for your one,
public class A {
public static void main(String[] args) throws IOException {
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in), 1);
System.out.println("How many strings do you want to sort?");
int numStrings = Integer.parseInt(stdin.readLine());
System.out.println("Input Strings Here:");
String[] stringsToSort = new String[numStrings];
for (int i = 0; i < numStrings; i++) {
String s = stdin.readLine();
stringsToSort[i] = s;
}
Arrays.sort(stringsToSort, new Comparator<String>() {
#Override
public int compare(String s1, String s2) {
return s1.compareToIgnoreCase(s2);
}
});
for (int i = 0; i < stringsToSort.length; i++) {
System.out.println(stringsToSort[i]);
}
}
}

Java Beginning Scanner

I am a novice programmer and I am trying to do projects that I find fun to help me learn more about the language then my school classes have been able to provide. I have wanted to try reversing a string but instead of having the string defined in a string I have added a scanner to be able to allow a user to input what they want. After searching for any help I haven't been able to find my issue that I am having. So far I have this:
import java.util.ArrayList;
import java.util.Scanner;
public class Reverse {
static ArrayList<String> newString = new ArrayList();
static int inputLength = 0;
static String PlaceHolder = null;
static String beReturned = null;
static int lengthArray = 0;
static String ToBeReversed;
static String hold = null;
public static void reversal(){
inputLength = ToBeReversed.length();
for (int e = 0; e <= inputLength; e++)
{
PlaceHolder = ToBeReversed.substring(inputLength -1, inputLength);
newString.add(PlaceHolder);
}
}
public static String putTogether()
{
int lengthcounter = 0;
lengthArray = newString.size();
for (int i = 0; i < lengthArray; i++)
{
beReturned = beReturned + newString.get(lengthcounter);
if (lengthcounter < lengthArray)
{
lengthcounter++;
}
}
return beReturned;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in); //create a new scanner
ToBeReversed = input.nextLine();
Reverse.reversal();
Reverse.putTogether();
}
}
For any input that I input there is no result. I don't get an Error Message or any form of return... The output is blank. I am just wondering if I made a mistake with the scanner or if it is how I am trying to store the characters/access them from the ArrayList I created. I am trying to not have others give me the answer completely with all the fixes, I hope I can just get a pointer or a hint to where I am messing up. Thank you for your time and help.
You need to print the output, for example
public static void main(String[] args) {
Scanner input = new Scanner(System.in); //create a new scanner
ToBeReversed = input.nextLine();
System.out.println("ToBeReversed = " + ToBeReversed);
Reverse.reversal();
System.out.println("newString = " + newString);
System.out.println(Reverse.putTogether());
}
I don't want to give a complete answer, as that would spoil your fun (and steal an opportunity for your to get started with using a debugger), but here are some hints...
You can use String#charAt to get an individual character from a String at a given index
Java is generally 0 indexed, that means that things like arrays, String, List start at index 0 and go through to length - 1
null + String = nullString ;)
You can run a loop backwards. for-loop doesn't have to run from 0-x in ascending order, they can run x-0 in descending order ;)

Using a method to call individual strings from an array (looping)

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?

read from .txt file and convert in to List<Map>

i have heavy .txt file. it contains a format Like this:
0 1 2 3 4 5 6 7 ... n
0 A, B, c, D, E, F, G, H,
1 AA, BB, CC, DD, EE, FF, GG, HH,
2
3
.
.
n
i want to save each row in Map.
for example in first row: map<0,A> . map<1,B>, Map<2,C>,...
then i want to save this maps in List. for example i want to save 100 rows in List.
for example if i write this function: "" list.get(1).get(4); "" i recived "EE"
it means first i have to go in 1 row, then i go to 4 and recive "EE".
could you please guidance me how to solve this problem?
i read some article about "spring batch" .and it related what i want
could you please help me how can i fix this problem?
public class spliter {
static int w=0;
private static HashMap<Integer,String> map = new HashMap<Integer,String>();
private static List<Map<Integer, String>> list=new ArrayList<Map<Integer,String>>();
public static void main(String[] args) throws IOException{
String string = null;
try {
BufferedReader reader = new BufferedReader(new FileReader("C:\\test.txt"));
while( (string = reader.readLine()) != null ) {
String[] parts = string.split(",");
int i=parts.length;
for(int j=0; j<i; j++){
map.put(j, parts[j]);
}
list.add(map);
w++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Something this simple can be solved using a Scanner to read each line and then String.split(...) to split each line. Something like:
while line exists
read line into String using Scanner
split String using String#split(...)
use array from split to create a list
add above list to master list
end while
Note that you can contain this in a list of lists, without the need of a Map, at all. List<List<String>> should do it for you.
I think that it would be more instructive to you for us to give you general advice like this, and then to see what you can do with it.
I have made into a Community Wiki, so all might contribute easily to this answer and so no-one will get reputation for up-votes.
I needed the same, i did it with yours in mind
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class Spliter {
private static List<Map<String, Object>> list = new ArrayList<> ();
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\829784\\Desktop\\Repo\\Documentacion Repositorio\\test.txt"));
String line = "";
String firstline = reader.readLine();
while ((line = reader.readLine()) != null) {
Map < String, Object > map = new TreeMap < > ();
String[] partsfirstline = firstline.split(";");
String[] parts = line.split(";");
int i = parts.length;
for (int j = 0; j < i; j++) {
map.put(partsfirstline[j], parts[j]);
}
list.add(map);
}
System.out.println(list.get(0).values());
System.out.println(list.get(1).values());
}
}
you could us something like this
public class ArrayReader {
public static void main(String[] args) {
List<List<String >> array = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"));){
String line;
while ((line=br.readLine())!=null)
array.add(Arrays.asList(line.split(",")));
} catch (IOException e) {
e.printStackTrace();
}
}
}

Categories