swapping column from a text file in Java - java

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.

Related

How can read a txt file so that all words are placed in a new array element and not every new line is placed in a element?

I currently have written a code that is able to read through a .txt file and for every new line it will be placed in a array element (not very hard). It works but this was not my initial intention, I want to have every word placed in a new array element, not after every new line. Here is my current code, can someone maybe help? Thank you!
public static ArrayList<String> read_file() {
try {
ArrayList<String> data_base = new ArrayList<String>();
Scanner s1 = new Scanner(new File("C:\\Users\\Jcool\\OneDrive\\A Levels\\Computer Science\\CSV files\\data convert\\convert.txt"));
while(s1.hasNextLine()) {
data_base.add(s1.nextLine());
}
return data_base;
}catch(FileNotFoundException e) {
}
return null;
}
Read all the lines at once and split them into array.
private static String readAllBytes(String filePath)
{
String content = "";
try
{
content = new String ( Files.readAllBytes( Paths.get(filePath) ) );
}
catch (IOException e)
{
e.printStackTrace();
}
return content;
}
Create a method named readAllBytes and call it like this;
/* String to split. */
String stringToSplit = readAllBytes(filePath);
String[] tempArray;
/* delimiter */
String delimiter = " ";//space if its a file contains words
/* given string will be split by the argument delimiter provided. */
tempArray = stringToSplit.split(delimiter);
If you mean to split your lines into array check this answer.
Take a look at the split(String) method. It returns a String[]. As an example
String string = "AAA-BBB";
String[] parts = string.split("-");
String part1 = parts[0]; // AAA
String part2 = parts[1]; // BBB

Read from txt file - Save when a line-break occurs

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

Why doesn't my program recognize the last names properly?

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

Printing the string after a string in a string in java

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");

Split string with three words

What is the best way to split a string containing three words?
My code looks like this right now (see below for updated code):
BufferedReader infile = new BufferedReader(new FileReader("file.txt"));
String line;
int i = 0;
while ((line = infile.readLine()) != null) {
String first, second, last;
//Split line into first, second and last (word)
//Do something with words (no help needed)
i++;
}
Here is the full file.txt:
Allegrettho Albert 0111-27543
Brio Britta 0113-45771
Cresendo Crister 0111-27440
Dacapo Dan 0111-90519
Dolce Dolly 0116-31418
Espressivo Eskil 0116-19042
Fortissimo Folke 0118-37547
Galanto Gunnel 0112-61805
Glissando Gloria 0112-43918
Grazioso Grace 0112-43509
Hysterico Hilding 0119-71296
Interludio Inga 0116-22709
Jubilato Johan 0111-47678
Kverulando Kajsa 0119-34995
Legato Lasse 0116-26995
Majestoso Maja 0116-80308
Marcato Maria 0113-25788
Molto Maja 0117-91490
Nontroppo Maistro 0119-12663
Obligato Osvald 0112-75541
Parlando Palle 0112-84460
Piano Pia 0111-10729
Portato Putte 0112-61412
Presto Pelle 0113-54895
Ritardando Rita 0117-20295
Staccato Stina 0112-12107
Subito Sune 0111-37574
Tempo Kalle 0114-95968
Unisono Uno 0113-16714
Virtuoso Vilhelm 0114-10931
Xelerando Axel 0113-89124
New code as #Pshemo suggested:
public String load() {
try {
Scanner scanner = new Scanner(new File("reg.txt"));
while (scanner.hasNextLine()) {
String firstname = scanner.next();
String lastname = scanner.next();
String number = scanner.next();
list.add(new Entry(firstname, lastname, number));
}
msg = "The file reg.txt has been opened";
return msg;
} catch (NumberFormatException ne) {
msg = ("Can't find reg.txt");
return msg;
} catch (IOException ie) {
msg = ("Can't find reg.txt");
return msg;
}
}
I receive multiple errors, what's wrong?
Assuming that each line always contains exactly three words instead of split you can simply use Scanners method next three times for each line.
Scanner scanner = new Scanner(new File("file.txt"));
int i = 0;
while (scanner.hasNextLine()) {
String first = scanner.next();
String second = scanner.next();
String last = scanner.next();
//System.out.println(first+": "+second+": "+last);
i++;
}
line.split("\\s+"); // don't use " ". use "\\s+" for more than one whitespace
Assuming the line has 3+ words, use the split(delimiter) method:
String line = ...;
String[] parts = line.split("\\s+"); // Assuming words are separated by whitespaces, use another if required
then you can access to the first, second and last respectively:
String first = parts[0];
String second = parts[1];
String last = parts[parts.length() - 1];
Remember that indexes starts with 0.
String []parts=line.split("\\s+");
System.out.println(parts[0]);
System.out.println(parts[1]);
System.out.println(parts[parts.length-1]);

Categories

Resources