I have a txt file containing words and their abbreviations that looks like this
one,1
two,2
you,u
probably,prob
...
I have read the txt file into a string splitting it and replacing the commas with spaces like so..
public String shortenWord( String inWord ) {
word = inWord;
String text = "";
try {
Scanner sc = new Scanner(new File("abbreviations.txt"));
while (sc.hasNextLine()) {
text = text + sc.next().replace(",", " ") + " ";
}
// System.out.println(text);
//System.out.println(word);
if (text.contains(word)) {
System.out.println(word);
}
else {
System.out.println("nope");
}
}
catch ( FileNotFoundException e ) {
System.out.println( e );
}
return text;
}
The user must input a word that they want abbreviated and it will return the abbreviated version of the word.
class testit{
public static void main(String[] args){
Shortener sh = new Shortener();
sh.shortenWord("you");
}
}
I have it returning the word they entered if it is found but i want it to return the word next to it in the file which would be the abbreviated version.
eg. printed string 'text' looks like ..
one 1 two 2 three 3 you u probably prob hello lo
I want them to be able to enter 'you' the program find 'you' and then prints 'u' which is the next string over separated by a space
Removing the comma achieves nothing, so don't do it.
I would first split:
String[] text = sc.next().split(",");
Then compare with the first part of the split:
if (text[0].equals(word))
and if true, return the second part of the split:
return text[1];
Part of the logic looks like below:
Map<String,String> myShortHand = new HashMap<String, String>();
Scanner sc = new Scanner(new File("abbreviations.txt"));
while (sc.hasNextLine()) {
String text[] = sc.next().split(",");
myShortHand.put(text[0],text[1]);
}
Now get the details from map like
myShortHand.get("one");
Related
I want to read from .txt file, but I want to save each string when an empty line occurs, for instance:
All
Of
This
Is
One
String
But
Here
Is A
Second One
Every word from All to String will be saved as one String, while every word from But and forward will be saved as another. This is my current code:
public static String getFile(String namn) {
String userHomeFolder = System.getProperty("user.home");
String filnamn = userHomeFolder + "/Desktop/" + namn + ".txt";
int counter = 0;
Scanner inFil = new Scanner(new File(filnamn));
while (inFil.hasNext()) {
String fråga = inFil.next();
question.add(fråga);
}
inFil.close();
}
What and how should I adjust it? Currently, it saves each line as a single String. Thanks in advance.
I assume your question is regarding java.
As you can see I changed return type of your method to List because returning single String doesn't make sense when splitting full text into multiple Strings.
I also don't know what question variable so I switched it with allParts being list of sentences separated by empty line(variable part).
public static List<String> getFile(String namn) throws FileNotFoundException {
String userHomeFolder = System.getProperty("user.home");
String filnamn = userHomeFolder + "/Desktop/" + namn + ".txt";
int counter = 0;
// this list will keep all sentence
List<String> allParts = new ArrayList<String>(); s
Scanner inFil = new Scanner(new File(filnamn));
// part keeps single sentence temporarily
String part = "";
while (inFil.hasNextLine()) {
String fråga = inFil.nextLine(); //reads next line
if(!fråga.equals("")) { // if line is not empty then
part += " " + fråga; // add it to current sentence
} else { // else
allParts.add(part); // save current sentence
part = ""; // clear temporary sentence
}
}
inFil.close();
return allParts;
}
The scanner reads the wrong data, the text file format is:
111,Smith,Sam, 40,10.50
330,Jones,Jennifer,30,10.00
The program is:
public class P3 {
public static void main(String[] args) {
String file=args[0];
File fileName = new File(file);
try {
Scanner sc = new Scanner(fileName).useDelimiter(", ");
while (sc.hasNextLine()) {
if (sc.hasNextInt( ) ){ int id = sc.nextInt();}
String lastName = sc.next();
String firstName = sc.next();
if (sc.hasNextInt( ) ){ int hours = sc.nextInt(); }
if (sc.hasNextFloat()){ float payRate=sc.nextFloat(); }
System.out.println(firstName);
}
sc.close();
} catch(FileNotFoundException e) {
System.out.println("Can't open file "
+ fileName + " ");
}
}
}
The output is:
40,10.50
330,Jones,Jennifer,30,10.00
It is supposed to be:
Sam
Jennifer
How do I fix it?
The problem is that your data isn't just delimited by commas. It is also delimited by line-endings, and also by Unicode character U+FF0C (FULLWIDTH COMMA).
I took your code, replaced the line
Scanner sc = new Scanner(fileName).useDelimiter(", ");
with
Scanner sc = new Scanner(fileName, "UTF-8").useDelimiter(", |\r\n|\n|\uff0c");
and then ran it. It produced the output it was supposed to.
The text , |\r\n|\n|\uff0c is a regular expression that matches either:
a comma followed by a space,
a carriage-return (\r) followed by a newline (\n),
a newline on its own,
a Unicode full-width comma (\uff0c).
These are the characters we want to delimit the text by. I've specified both types of line-ending as I'm not sure which line-endings your file uses.
I've also set the scanner to use the UTF-8 encoding when reading from the file. I don't know whether that will make a difference for you, but on my system UTF-8 isn't the default encoding so I needed to specify it.
First, please swap fileName and file. Next, I suggest you use a try-with-resources. Your variables need to be at a common scope if you intend to use them. Finally, when using hasNextLine() I would then call nextLine and you can split on optional white space and comma. That could look something like
String fileName = // ...
File file = new File(fileName);
try (Scanner sc = new Scanner(file)) {
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] arr = line.split("\\s*,\\s*");
int id = Integer.parseInt(arr[0]);
String lastName = arr[1];
String firstName = arr[2];
int hours = Integer.parseInt(arr[3]);
float payRate = Float.parseFloat(arr[4]);
System.out.println(firstName);
}
} catch (FileNotFoundException e) {
System.out.println("Can't open file " + fileName + " ");
e.printStackTrace();
}
I want to find matching string from .text file.
but using this code I can only get the matching string of the first line of the text file. it does not run to the other lines of the text file
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println("Inside next line");
String line = scanner.nextLine();
System.out.println(line);
String[] tokenarray = line.split(":");
if (tokenarray[0].equals(id)) {
System.out.println("match found");
System.out.println(tokenarray[0]);
customer = new Customer(tokenarray[0], tokenarray[1],
tokenarray[2], tokenarray[3], tokenarray[4],
tokenarray[5], tokenarray[6], tokenarray[7],
tokenarray[8]);
break;
}
}
This code works only when is input id as tokenarray[0] value of the first line of the document. I want to search whole text document. not only the first line.
It seems like when you will remove the break it will solve your problem.
String line = "hello:world:hello:up";
String[] tokenarray = line.split(":");
for (String s : tokenarray) {
System.out.print((s.contains("hello") ? "match" : "no match"));
System.out.print(", ");
}
output:
match, no match, match, no match,
I am having some problems with this code. I need to write a code where it says SwapField to display columns from a text file and swaps column 2 to be column 1.
public static void main(String[] args) {
int lineNum = 0;
String delimiter = " ";
if (args.length != 3) {
System.out.println("USAGE: java SwapColumn fileName column# column#");
System.exit(-1);
}
String dataFileName = args[0];
String columnAText = args[1];
String columnBText = args[2];
int columnA = Integer.parseInt(columnAText);
int columnB = Integer.parseInt(columnBText);
File dataFile = new File(dataFileName);
Scanner input;
String outputText = null;
System.out.printf("dataFileName=%s, columnA=%d, columnB=%d\n",
dataFileName, columnA, columnB);
try {
input = new Scanner(dataFile);
while (input.hasNextLine()) {
String inputText = input.nextLine();
lineNum++;
outputText = swapFields(inputText, columnA, columnB, delimiter);
System.out.printf("%d: %s\n", lineNum, outputText);
}
} catch (FileNotFoundException FNF) {
System.out.printf("file not found: %s\n", dataFileName);
}
}
static String swapFields(String input, int fieldA, int fieldB, String delim) {
String outputBuffer = "";
//code needed here
return outputBuffer;
}
OK, so you want the method to take in a String input delimited by delim, and swap fields fieldA and fieldB?
static String swapFields(String input, int fieldA, int fieldB, String delim) {
String[] bits = input.split(delim);
String temp = bits[fieldA];
bits[fieldA] = bits[fieldB];
bits[fieldB] = temp;
return String.join(delim, bits);
}
In this code, the .split() method breaks the input up into an array, using delim as the separator (interpreted as a regular expression; see below for the assumptions regarding this). The two relevant (zero-indexed) fields are then swapped, and the String is reconstructed using .join().
Note that the last line (the .join()) requires Java 8. If you don't have Java 8 then you can use StringUtils.join from Apache Commons Lang.
I am also assuming here that your delim is in the right format for the .split() method, which is to say that it's a string literal that doesn't contain escapes and other regex characters. This seems like a plausible enough assumption if it's a delimiter in a text file (usually a comma, space or tab). It further assumes that the delimiter doesn't occur elsewhere in the input, within quotes or something. You haven't mentioned anything about quotes; you'd need to add something to clarify if you wanted to be able to handle such things.
I have the following text file (answers.txt):
Problem A: 23|47|32|20
Problem B: 40|50|30|45
Problem C: 5|8|11|14
Problem D: 20|23|25|30
What I need is something that will read the problem that I tell it(Problem A, Problem B), then read the numbers after it, which are separated by the lines, and print it out like this:
Answers for Problem A: a.23 b.47 c.32 d.20
Does anyone know how this can be done? I've been stuck on it for a while.
Read the lines one by one, split the lines at " " first. The you will get an array with three parts "Problem", "A:" and "23|47|32|20". Then split the third part at "|" so you will get a second array with four parts "23,"47","32","20".
Combine all to get the output you want.
If you want info on how to read lines from a file, or spilt strings then there are billions of tutorials online on how to do that so I wont go into detail on how its done. IM sure you can find them.
Check out this code!
It assumes that you have such file format:
Problem A:
23|7|32|20
Problem B:
40|50|30|45
Problem C:
5|8|11|14
Problem D:
20|23|25|30
because you wrote "numbers after it, which are separated by the lines"
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
public class Demo {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File("answers.txt"));
List<String> dataList = new ArrayList<String>();
while(sc.hasNextLine()){
dataList.add(sc.nextLine());
}
System.out.println(dataList);
Map<String,String> map = new HashMap<String,String>();
for(int i=0;i<dataList.size();i=i+2){
map.put(dataList.get(i),dataList.get(i+1));
}
for(Entry<String,String> en:map.entrySet()){
System.out.println(en.getKey()+" : "+en.getValue());
}
String problemC = map.get("Problem C:");
String splitted[] = problemC.split("\\|");
System.out.println("Get me problem C: "+String.format("a:%s, b:%s, c:%s, d:%s",splitted[0],splitted[1],splitted[2],splitted[3]));
}
}
Hope this helps!
public static void main(String args[])
{
BufferedReader br = new BufferedReader(new FileReader(new File("answers.txt")));
String lineRead = null;
String problem = "Problem A";//Get this from user Input
List<String> numberData = new ArrayList<String>();
while((lineRead = br.readLine())!=null)
{
if(lineRead.contains(problem))
{
StringTokenizer st = new StringTokenizer(lineRead,":");
String problemPart = st.nextToken();
String numbersPart = st.nextToken();
st = new StringTokenizer(lineRead,"|");
while(st.hasMoreTokens())
{
String number = st.nextToken();
System.out.println("Number is: " + number);
numberData.add(number);
}
break;
}
}
System.out.println("Answers for " + problem + " : " + numberData );
}
Read the lines one by one, split the lines with :. The you will get an array with two parts "Problem A:" and "23|47|32|20". Then split the second part at "|" so you will get a second array with four parts "23,"47","32","20".
Combining all this you will get the output you want.
Cheers!
Use java.util.Scanner and you can filter the integers in the file.
Scanner s = new Scanner (new File ("answers.txt")).useDelimiter("\\s+");
while (s.hasNext()) {
if (s.hasNextInt()) { // check if next token is integer
System.out.print(s.nextInt());
} else {
s.next(); // else read the next token
}
}
Do you know how to read line by line ? If not , chect it How to read a large text file line by line in java?
To sub your string data there have many ways to do. You can sub as you wish. Here for my code..
String data = yourReader.readLine();
String problem = data.substring("Problem".length(), data.indexOf(":"));
System.err.println("Problem is " + problem);
data = data.substring(data.indexOf(":") + 2, data.length());
String[] temp = data.split("\\|");
for (String result : temp) {
System.out.println(result);
}
Assuming there are always four possible answers as in your Example:
// read complete file in fileAsString
String regex = "^(Problem \\w+): (\\d+)\\|(\\d+)\\|(\\d+)\\|(\\d+)$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(fileAsString);
//and so on, read all the Problems using matcher.find() and matcher.group(int) to get the parts
// put in a Map maybe?
// output the one you want...
I might suggest creating a simple data type for the purpose of organization:
public class ProblemAnswer {
private final String problem;
private final String[] answers;
public ProblemAnswer(String problem, String[] answers) {
this.problem = problem;
this.answers = new String[answers.length];
for (int i = 0; i < answers.length; i++) {
this.answers[i] = answers[i];
}
}
public String getProblem() {
return this.problem;
}
public String[] getAnswers() {
return this.answers;
}
public String getA() {
return this.answers[0];
}
public String getB() {
return this.answers[1];
}
public String getC() {
return this.answers[2];
}
public String getD() {
return this.answers[3];
}
}
Then the reading from the text file would look something like this:
public void read() {
Scanner s = new Scanner("answers.txt");
ArrayList<String> lines = new ArrayList<String>();
while (s.hasNext()) {
lines.add(s.nextLine());//first separate by line
}
ProblemAnswer[] answerKey = new ProblemAnswer[lines.size()];
for (int i = 0; i < lines.size(); i++) {
String[] divide = lines.get(i).split(": "); //0 is the problem name, 1 is the list
//of answers
String[] answers = divide[1].split("|"); //an array of the answers to a given
//question
answerKey[i] = new ProblemAnswer(divide[0], answers); //add a new ProblemAnswer
//object to the key
}
}
Now that leaves you with an answer key with ProblemAnswer objects which is easily checked
with a simple .equals() comparison on the getProblem() method, and whatever index is matched, you have all the answers neatly arranged right within that same object.