Take multiple inputs from text files in java - java

I write a program and need to generate results for different input (integer) values. which i have to read some integer numbers from several text files and store them in these variables.
choice
numofNodes
numofPoints
in each file there might be multiple numbers that should be assigned to one of above variables, for example:
First text file contains five values for first variables and other two variables have one value on separate lines like below:
1 2 3 4 5
60
50
Second text file contains five values for second variables and other two variables have one value on separate lines like below:
1
40 50 60 70 80
50
and so on..
I have no idea how to read them from text files.
any helps will be appreciated.
Here's my Main class:
public static void main(String[] args)throws InterruptedException {
// how to read numbers from different text files here
// and store them in these variables to call func method?
// int choice = ?
// int numofNode = ?
// int numofPoint = ?
path ob=new path(choice,numofNode,numofPoint);
ob.func();
}

put files path in a string array. then you can read the files by creating an instance of java.util.Scanner class that has several methods to read file content.
all you need is to use for and for-each loops to loop through your files and read them.
here's some code that i hope helps!
/**
* converts array of string numbers to array of integer numbers.
*
* #param numbers is array of strings
* #return an integer array which is parsed from <b>numbers</b>
*
*/
static int[] parseInt(String[] numbers) {
return Arrays.stream(numbers).mapToInt(Integer::parseInt).toArray();
}
public static void main(String[] args) {
// put input files path here
String[] name_and_path_of_files = {
"C:\\Users\\YOUR_USER\\Desktop\\input_1.txt",
"C:\\Users\\YOUR_USER\\Desktop\\input_2.txt"
};
// file reader
Scanner inputFileReader = null;
try {
// for all files
for (String fileInfo : name_and_path_of_files) {
// create reader object with file info
inputFileReader = new Scanner(new File(fileInfo));
int line_index = 0;
int choices[] = null;
int numofNodes[] = null;
int numofPoints[] = null;
// trying to read file content
while (inputFileReader.hasNext()) {
String separated_numbers[] = inputFileReader.nextLine().split(" ");
switch (line_index) {
case 0:
choices = parseInt(separated_numbers);
break;
case 1:
numofNodes = parseInt(separated_numbers);
break;
case 2:
numofPoints = parseInt(separated_numbers);
break;
}
line_index++;
}
for (int choice : choices) {
for (int numofPoint : numofPoints) {
for (int numofNode : numofNodes) {
path ob = new path(choice, numofNode, numofPoint);
ob.func();
}
}
}
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
} finally {
if (inputFileReader != null) {
inputFileReader.close();
}
}
}

Related

In Java, using Scanner, Is there a way to find a specific String in a CSV file, use it as a column header and return all values under it?

I am trying to find the String "5464" in a csv document then have it return all of the values under that String (same number of Delimiters from the start of the line), until reaching the end of the list (no more values in the column). Any help would be sincerely appreciated.
import javax.swing.JOptionPane;
public class SearchNdestroyV2 {
private static Scanner x;
public static void main(String[] args) {
String filepath = "tutorial.txt";
String searchTerm = "5464"
readRecord(searchTerm,filepath);
}
public void readRecord(String searchTerm, String filepath)
{
boolean found = false;
String ID = ""; String ID2 = ""; String ID3 = "";
}
try
{
x = new Scanner(new File(filepath));
x.useDelimeter("[,\n]");
while(x.hasNext() && !found )
{
ID = x.next();
ID2 = x.nextLine();
ID3 = x.nextLine();
if(ID.equals(searchTerm))
{
found = true;
}
}
if (found)
{
JOptionPane.showMessageDialog(null,"ID: " + ID + "ID2: " + ID2 + "ID3: "+ID3);
}
}
else
{
JOptionPane.showMessageDialog(null, "Error:");
}
catch(Exception e)
{
}
{
}
I'm not exactly sure of what you mean. The way I read your question:
You want to locate a specific String ("5464") that is contained within a specific column within a comma (,) delimited CSV file. If this specific string (search term) is found then retrieve all other values contained within the same column for the rest of the CSV file records from the point of location. Here is how:
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class SearchNDestroyV2 {
private Scanner fileInput;
public static void main(String[] args) {
// Do this if you don't want to deal with statics
new SearchNDestroyV2().startApp(args);
}
private void startApp(String[] args) {
String filepath = "tutorial.txt";
String searchTerm = "5464";
readRecord(searchTerm, filepath);
}
public void readRecord(String searchTerm, String filepath) {
try {
fileInput = new Scanner(new File(filepath));
// Variable to hold each file line data read.
String line;
// Used to hold the column index value to
// where the found search term is located.
int foundColumn = -1;
// An ArrayList to hold the column values retrieved from file.
ArrayList<String> columnList = new ArrayList<>();
// Read file to the end...
while(fileInput.hasNextLine()) {
// Read in file - 1 trimmed line per iteration
line = fileInput.nextLine().trim();
//Skip blank lines (if any).
if (line.equals("")) {
continue;
}
// Split the curently read line into a String Array
// based on the comma (,) delimiter
String[] lineParts = line.split("\\s{0,},\\s{0,}"); // Split on any comma/space situation.
// Iterate through the lineParts array to see if any
// delimited portion equals the search term.
for (int i = 0; i < lineParts.length; i++) {
/* This IF statement will always accept the column data and
store it if the foundColumn variable equals i OR the current
column data being checked is equal to the search term.
Initially when declared, foundColumn equals -1* and will
never equal i unless the search term is indeed found. */
if (foundColumn == i || lineParts[i].equals(searchTerm)) {
// Found a match
foundColumn = i; // Hold the Coloumn index number of the found item.
columnList.add(lineParts[i]); // Add the found ite to the List.
break; // Get out of this loop. Don't need it anymore for this line.
}
}
}
if (foundColumn != -1) {
System.out.println("Items Found:" + System.lineSeparator() +
"============");
for (String str : columnList) {
System.out.println(str);
}
}
else {
JOptionPane.showMessageDialog(null, "Can't find the Search Term: " + searchTerm);
}
}
catch(Exception ex) {
System.out.println(ex.getMessage());
}
}
}
If however, what you want is to search through the CSV file and as soon as any particular column equals the Search Term ("5464") then simply store the CSV line (all its data columns) which contains that Search Term. Here is how:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class SearchNDestroyV2 {
/* A JFrame used as Parent for displaying JOptionPane dialogs.
Using 'null' can allow the dialog to open behind other open
applications (like the IDE). This ensures that it will be
displayed above all other applications at center screen. */
JFrame iFRAME = new JFrame();
{
iFRAME.setAlwaysOnTop(true);
iFRAME.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
iFRAME.setLocationRelativeTo(null);
}
public static void main(String[] args) {
// Do this if you don't want to deal with statics
new SearchNDestroyV2().startApp(args);
}
private void startApp(String[] args) {
String filepath = "tutorial.txt";
String searchTerm = "5464";
ArrayList<String> recordsFound = readRecord(searchTerm, filepath);
/* Display any records found where a particular column
matches the Search Term. */
if (!recordsFound.isEmpty()) {
System.out.println("Records Found:" + System.lineSeparator()
+ "==============");
for (String str : recordsFound) {
System.out.println(str);
}
}
else {
JOptionPane.showMessageDialog(iFRAME, "Can't find the Search Term: " + searchTerm);
iFRAME.dispose();
}
}
/**
* Returns an ArrayList (of String) of any comma delimited CSV file line
* records which contain any column matching the supplied Search Term.<br>
*
* #param searchTerm (String) The String to search for in all Record
* columns.<br>
*
* #param filepath (String) The CSV (or text) file that contains the data
* records.<br>
*
* #return ({#code ArrayList<String>}) An ArrayList of String Type which
* contains the file line records where any particular column
* matches the supplied Search Term.
*/
public ArrayList<String> readRecord(String searchTerm, String filepath) {
// An ArrayList to hold the line(s) retrieved from file
// that match the search term.
ArrayList<String> linesList = new ArrayList<>();
// Try With Resourses used here to auto-close the Scanner reader.
try (Scanner fileInput = new Scanner(new File(filepath))) {
// Variable to hold each file line data read.
String line;
// Read file to the end...
while (fileInput.hasNextLine()) {
// Read in file - 1 trimmed line per iteration
line = fileInput.nextLine().trim();
//Skip blank lines (if any).
if (line.equals("")) {
continue;
}
// Split the curently read line into a String Array
// based on the comma (,) delimiter
String[] lineParts = line.split("\\s{0,},\\s{0,}"); // Split on any comma/space situation.
// Iterate through the lineParts array to see if any
// delimited portion equals the search term.
for (int i = 0; i < lineParts.length; i++) {
if (lineParts[i].equals(searchTerm)) {
// Found a match
linesList.add(line); // Add the found line to the List.
break; // Get out of this loop. Don't need it anymore for this line.
}
}
}
}
catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
}
return linesList; // Return the ArrayList
}
}
Please try to note the differences between the two code examples. In particular how the file reader (Scanner object) is closed, etc.

Reading text from file and comparing it to seriers of characters

can I get recommendation or like an advice for what should be used or be known to complete this task (in the most rudimentary way I guess). if someone would be willing to write a code that would be fantastic but vague answers on the neccesary knowledge or technique will suffice.
I would like a program where at the start you input characters either seperataed by pressing enter or a string that could be like chopped up into separate items of an array (I guess) - characters separated by a comma - and that would be then compared to a txt file that contains series of entries and only those that contain some of (meaning shorter) or all of the characters that have been provided at the start would be printed, perhaps even the print would be separated by a length of the entry (word).
Any ideas on how to do this? Also, can the results be printed somewhere else than the command line, like another txt file? Need to do this in java. Thanks.
Take a look at following example:
public class SimpleExample {
public static void main(String[] args) throws ClassNotFoundException {
Scanner inputNumbers = new Scanner(System.in);
List<Integer> listOfNumbersToStore = new ArrayList<>();
List<Integer> listOfNumbersToCheck = new ArrayList<>();
int number;
String answer;
boolean flag = true;
// do code within a loop while flag is true
do {
// print message to screen
System.out.print("Would you like to put new number to your file list (Y/N): ");
// get answer (Y/N) to continue
answer = inputNumbers.next();
// if answer is Y or y
if ("Y".equalsIgnoreCase(answer)) {
// print message
System.out.print("Put your number: ");
// get input integer and assign it to number
number = inputNumbers.nextInt();
// add that number to a list of numbers to store to file
listOfNumbersToStore.add(number);
} else if ("N".equalsIgnoreCase(answer)) {
flag = false;
}
} while (flag);
writeToFile(listOfNumbersToStore);
System.out.println("---------- Check numbers ----------");
flag = true; // set it again to true
//do code within a loop while flag is true
do {
System.out.print("Would you like to put new number to your check list (Y/N) : ");
answer = inputNumbers.next();
if ("Y".equalsIgnoreCase(answer)) {
System.out.print("Put your number: ");
number = inputNumbers.nextInt();
listOfNumbersToCheck.add(number);
} else if ("N".equalsIgnoreCase(answer)) {
flag = false;
}
} while (flag);
// get a list from a file
List<Integer> readFromFile = readFromFile();
// check if there are any common elements within compared lists
boolean areThereAnyCommonElements = !Collections.disjoint(
listOfNumbersToCheck, readFromFile);
//create a new treeset used for containing unique elements and ordering it naturally, from 0 to n
Set<Integer> set = new TreeSet<>(listOfNumbersToCheck);
set.retainAll(readFromFile);
// print these messages
System.out.println("Are there any common integers between a list from a file and checking list? " + areThereAnyCommonElements);
System.out.println("Those integers are: " + set.toString());
}
/**
* List implements Seriazable interface, therefore store it to a file
* serialized
*
* #param numberOfIntegers
*/
public static void writeToFile(List<Integer> numberOfIntegers) {
try {
// create a file output stream to write to the file with the specified name.
FileOutputStream fileOutputStream = new FileOutputStream("tekstDataOutputStream");
// writes the serialization stream header to the underlying file stream;
ObjectOutputStream dataOutputStream = new ObjectOutputStream(new BufferedOutputStream(fileOutputStream));
// write a list to object output stream
dataOutputStream.writeObject(numberOfIntegers);
//close them
dataOutputStream.close();
fileOutputStream.close();
} catch (IOException ioE) {
System.err.println("JVM reported an error! Take a look: " + ioE);
}
}
public static List<Integer> readFromFile() throws ClassNotFoundException {
//create an empty list of integers
List<Integer> result = new ArrayList<>();
try {
//opening a connection to an actual file
FileInputStream fis = new FileInputStream("tekstDataOutputStream");
//used for reading from a specified input stream
ObjectInputStream reader = new ObjectInputStream(fis);
//get that list
result = (List<Integer>) reader.readObject();
//close streams
reader.close();
fis.close();
} catch (IOException ioE) {
System.err.println("JVM reported an error! Take a look: " + ioE);
}
return result;
}
}

How do I store data read in from a CSV into a collection

I have been tasked with creating a game called Taboo. It consists of a main word and 3 banned words. The aim of the game is for the words to display on the screen and the user then has to describe the main word without using the word itself or the banned words.
I have so far been able to read in the data that I have stored in a CSV and have it so that when I choose to output BannedWords, it does so. The problem now, is that when it outputs either MainWord or BannedWord1, etc... it outputs the data for each record in the CSV.
Below is the data from my CSV (it is just a test with few records so that when it works I can introduce the rest).
Tree,Brown,Green,Nature
Lake,Blue,Water,Wet
Apple,Green,Fruit,Healthy
If I chose to output MainWord, which is the first word, it outputs like this:
Tree
Lake
Apple
I need to somehow store the data being read in from the CSV individually in a collection so that when I need to use them, they output properly and they in a such a way that I can display them later on in a GUI JLabel.
It might also be useful to note that I am using NetBeans so I am able to use any of the built in functions as well.
public class Card
{
private String sMainWord;
private String sBannedWord1;
private String sBannedWord2;
private String sBannedWord3;
public Card(String sMW, String sBW1, String sBW2,String sBW3)
{
sMainWord = sMW;
sBannedWord1 = sBW1;
sBannedWord2 = sBW2;
sBannedWord3 = sBW3;
}
public void setsMainWord(String sMW)
{
sMainWord = sMW;
}
public String getsMainWord()
{
return sMainWord;
}
public void setsBannedWord1(String sBW1)
{
sBannedWord1 = sBW1;
}
public String getsBannedWord1()
{
return sBannedWord1;
}
public void setsBannedWord2(String sBW2)
{
sBannedWord2 = sBW2;
}
public String getsBannedWord2()
{
return sBannedWord2;
}
public void setsBannedWord3(String sBW3)
{
sBannedWord3 = sBW3;
}
public String getsBannedWord3()
{
return sBannedWord3;
}
public static void main(String[] args) throws FileNotFoundException
{
String fileNameDefined = "/Users/student/NetBeansProjects/TabooGameComplete/CSData.csv";
File file = new File(fileNameDefined);
try
{
Scanner inputStream = new Scanner(file);
while(inputStream.hasNext() != false)
{
String TabooCardWords = inputStream.nextLine();
String[] information = TabooCardWords.split(",");
String MainWord = information[0];
String BannedWord1 = information[1];
String BannedWord2 = information[2];
String BannedWord3 = information[3];
Card TBC = new Card (MainWord, BannedWord1, BannedWord2, BannedWord3);
System.out.println("*" + BannedWord1 + "*");
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
You are executing the output statement in the loop that generates your Cards so that everytime a card is created, you are outputting its BannedWord1. As you are creating them all, one after another, they will all output, one after another.
i.e.
//For each line in file
while(inputStream.hasNext() != false)
{
//Create Card
//Output BannedWord1 used to create Card
}
If you want to output one element of one Card, you will need to keep the Card objects you create to be used outside the loop:-
Card[] cards = new Cards[3];
int i=0;
//For each line in file
while(inputStream.hasNext() != false)
{
//Create Card
cards[i++] = newlyCreatedCardObject; //Store card object for later
//Output BannedWord1 used to create Card
}
//Output BannedWord1 from the Card created from the second line
System.out.println(cards[1].getsBannedWord1());
Additional Point
By convention, java variables begin with lowercase letters and classes with uppercase, so this can be confusing
String TabooCardWords; //Should really be 'tabooCardWords'
...
String MainWord = information[0]; //-> 'mainWord'
String BannedWord1 = information[1]; //-> 'bannedWord1'
String BannedWord2 = information[2]; //-> 'bannedWord2'
String BannedWord3 = information[3]; //-> 'bannedWord3'

String and char replacement on a textview

I'm doing on my translation app, I have some problem in my main translator.
for example like my code below, I try to transform "bed" into "bad" and if last char is "m" it will transform to "t".
When my input was "BEDROOM" I want to transform it into "BADROOT" that code below just read my first statement, and the other became false.
private void MachinetranslatorO(){
String change= input.getText().toString();
if (change.substring(0,3).equals("bed")){
String change1 = change.replaceFirst("bed", "bad");
result.setText(change1);
if (change.substring(change.length()-1).equals("m")){
char replaceWith='t';
StringBuffer aBuffer = new StringBuffer(change);
aBuffer.setCharAt(change.length()-1, replaceWith);
result.setText(aBuffer)
Well...since you asked I will provide a quick little Java Console runnable. The code is commented pretty good so you should have no trouble following it.
This application requires a text file containing Translation data (in this example: English To Spanish) which I have also provided sample data for at the end of this post.
Run the application and enter any one of the English words contained within the Translation Table data file (spanish.txt) and the program will display the Spanish equivalent.
Simply create a new project named LanguageTranslator using your favorite IDE then copy/paste the code below:
package languagetranslator;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class LanguageTranslator {
// Declare and intitialize some Class global variables...
// The language. It is also the name of our translation table
// text file (ie: spanish.txt)
private static String language = "spanish";
// The 2 Dimensional Array which will hold our translation table.
private static String[][] translationTable = {};
// Class main() method
public static void main(String[] args) {
// Load up the translationTable[][] 2D String Array from our
// Tanslation Table text file (spanish.txt).
readInTranslationFile(language + ".txt");
// Declare and initialize our String variable we will use to accept
// console input from User with...
String userInput = "lets go";
// Open a Connection to console Using the Scanner Class
try (Scanner conInput = new Scanner(System.in)) {
// Start a while/loop to continually ask the User to
// supply a English word...
while (!userInput.equals("")) {
// Ask User to supply a Word...
System.out.println("\nPlease supply a English word to translate\n"
+ "or supply nothing to exit:");
// Hold what User enters into console within the userInput variable.
userInput = conInput.nextLine();
// If the User supplied nothing then he/she want to quit.
if (userInput.equals("")) { break; }
// Declare and initialize a boolean variable so as to later determine if
// a translation for the supplied word had been found.
boolean found = false;
// Iterate through the translationTable[][] 2D String Array to see if
// the User's supplied word is contained within. The English word to
// match would be in the first column of the array and the translation
// for that word would be in the second column of the array.
for (int i = 0; i < translationTable.length; i++) {
// convert the word supplied by User and the current word being read
// within column 1 of the 2D Array to lowercase so that letter case
// is not a factor here.
if(userInput.toLowerCase().equals(translationTable[i][0].toLowerCase())) {
// If the word supplied by User is found within the translationTable[][]
// array then set the found variable to true and display the spanish
// translation to console.
found = true;
System.out.println("--------------------------------------");
System.out.println("The " + language + " translation is: \u001B[34m"
+ translationTable[i][1] + "\u001B[39;49m");
System.out.println("--------------------------------------");
}
}
// If we've iterated through the entire tanslationTable array and an a match
// was not found then display as such to the User...
if (!found) {
System.out.println("\n\u001B[31mThe supplied word could not be located within "
+ "the Translation Table.\n\u001B[39;49m");
}
// Continue the while/loop and ask User to supply another word
// until the User supplies nothing.
}
}
// Exit the application if nothing is supplied by User.
System.exit(0);
}
// Method used to fill the tanslationTable[][] 2D String Array from
// a text file which contains all the translation data.
private static void readInTranslationFile(String filePath) {
String line = "";
int cnt = 0;
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
// Read in each line of the tanslation Table text file so as to place each
//line of data into the translationTable[][] 2 String Array...
while((line = br.readLine()) != null){
// Skip past blank lines in the text file and only process file lines
// which actually contain data.
if (!line.equals("")) {
// Each line of data within the Translation table text file consists
// of a |English word and it's Spanish equivalent delimited with a
// Pipe (|) character. A pipe character is used because you may later
// want to add definitions to your data that may contain different types
// of punctuation.
String[] tok = line.split("\\|");
// The redimPreserve() method allows for appending to a raw 2D String
// Array on the fly.
translationTable = redimPreserve(translationTable, cnt + 1, 2);
// Add the file data line to the 2D String Array...
translationTable[cnt][0] = tok[0].trim();
translationTable[cnt][1] = tok[1].trim();
cnt++; // counter used for incrementing the 2D Array as items are added.
}
}
// Close the BufferReader
br.close();
}
// Trap IO Exceptions from the Bufferreader if any...
catch (IOException ex) {
System.out.println("\n\u001B[31mThe supplied Translation Table file could"
+ " not be found!\n\u001B[39;49m" + filePath);
}
}
// The redimPreserve() method allows for appending to a raw 2D String
// Array on the fly. I created this method to make the task esier to
// accomplish.
private static String[][] redimPreserve(String[][] yourArray, int newRowSize, int... newColSize) {
int newCol = 0;
if (newColSize.length != 0) { newCol = newColSize[0]; }
// The first row of your supplied 2D array will always establish
// the number of columns that will be contained within the entire
// scope of the array. Any column value passed to this method
// after the first row has been established is simply ignored.
if (newRowSize > 1 && yourArray.length != 0) { newCol = yourArray[0].length; }
if (newCol == 0 && newRowSize <= 1) {
JOptionPane.showMessageDialog (null,"RedimPreserve() Error\n\n"
+ "No Column dimension provided for 2D Array!",
"RedimPreserve() Error",JOptionPane.ERROR_MESSAGE);
return null;
}
if (newCol > 0 && newRowSize < 1 && yourArray.length != 0) {
JOptionPane.showMessageDialog (null,"RedimPreserve() Error\n\n"
+ "No Row dimension provided for 2D Array!",
"RedimPreserve() Error",JOptionPane.ERROR_MESSAGE);
return null;
}
String[][] tmp = new String[newRowSize][newCol];
if (yourArray.length != 0) {
tmp = Array2DCopy(yourArray, tmp);
}
return tmp;
}
// Used within the redimPreserve() method to copy 2D Arrays.
private static String[][] Array2DCopy(String[][] yourArray, String[][] targetArray) {
for(int i = 0; i < yourArray.length; i++) {
System.arraycopy(yourArray[i], 0, targetArray[i], 0, yourArray[i].length);
}
return targetArray;
}
}
For a sample Translation Table text file you can copy/paste the following lines into a text editor and save the file as "spanish.txt" within the Classpath of your project (LanguageTranslator):
0|el cero
1|un
2|dos
3|tres
4|cuatro
5|cinco
6|seis
7|siete
8|ocho
9|nueve
a|un
able|poder
also|además
always|siempre
anyway|de todas formas
anyways|de todos modos
an|un
and|y
any|alguna
anybody|nadie
anything|cualquier cosa
apple|manzana
banana|platano
be|ser
because|porque
bedroom|cuarto
best|mejor
can|poder
can't|hipocresia
date|fecha
easy|facil
hard|difícil
harder|mas fuerte
now|ahora
never|nunca
new|nuevo
goodbye|adiós
hello|hola
her|su
high|alto
him|el
his|su
home|casa
how|como
in|en
inside|dentro
is|es
isn't|no es
it|eso
it's|sus
its|sus
leave|salir
list|lista
low|bajo
love|amor
of|de
out|fuera
outside|fuera de
over|encima
that|ese
the|la
then|entonces
these|estas
this|esta
those|aquellos
top|parte superior
topped|rematada
time|hora
to|a
was|estaba
weather|clima
what|que
where|donde
whether|si
who|quien
why|por que
you|tu
your|tu
Add data as you see fit to the file if you like.
Hope this helps...
Your first statement works fine but after that you assign your new reult to change1 not change. So in your second if statement you should use the newer formed string - change1. Don't use the older string change in the second if statement.
Replace change with change1 in second if statement.
**EDIT - **
private void MachinetranslatorO(){
String change= input.getText().toString();
String change1;
if (change.substring(0,3).equals("bed")){
change1 = change.replaceFirst("bed", "bad");
result.setText(change1);
if (change1.substring(change1.length()-1).equals("m")){
char replaceWith='t';
StringBuffer aBuffer = new StringBuffer(change1);
aBuffer.setCharAt(change1.length()-1, replaceWith);
result.setText(aBuffer)

Formatting an array list into a specific format

The program I am writing will sort a hospital record that comes in a text file. The format of the text file is lastname,firstname,age,roomnumber, it will look exactly like this :
Franklin,Benjamin,74,18
Hamilton,Alexander,25,6
Thatcher,Margaret,65,3
Nixon,Richard,45,7
and has to be printed with a certain format, but the user will specify how they are sorted. The format will look like this when sorted by last name:
Last First Age Room
Coolidge Calvin 24 27
Franklin Benjamin 74 8
Hamilton Alexander 50 123
Nixon Richard 45 7
I have been stuck on trying to find a way to store the lines and still be able to print out the lines together in order to keep the information together.
The Program has to be called through command-line and at the same time the program is called the user must specify the input file as the first argument (args[0]) and how to sort it as the second argument (args[1]).
I have tried a few different ways but I keep getting stuck in the same place, what would be the best way to approach this?
This is the current code btw. and the comment blocks is old code I have tried and keep it around, just in case.
import java.io.*;
import java.util.*;
public class PatientRecord {
public static void main(String args[])
{
System.out.println("Servando Hernandez");
System.out.println("Patient sorting Program.");
//
// Scanner scan = null;
// try
// {
// scan = new Scanner(new File(args[0]));
// }
// catch (FileNotFoundException e)
// {
// System.err.println("File path \"" + args[0] + "\" not found.");
// System.exit(0);
// }
//
// ArrayList<String> lines=new ArrayList<String>();
//
// while(scan.hasNextLine())
// lines.add(scan.nextLine());
//
// if(!(args.length == 0))
// {
// if(args[1] == lastname)
// {
// sortByLastName();
// }
// else if(args[1] == firstname)
// {
// sortByLastName();
// }
// else if(args[1] == age)
// {
// sortByAge();
// }
// else if(args[1] == roomnumber)
// {
// sortByRoomNumber();
// }
// }
//
List<Patient> patients = new ArrayList<>();
while(scan.hasNextLine())
{
String[] values= scan.nextLine().split(",");
patients.add(new Patient())
}
String sortType= args[1]
switch(sortType))
{
case "firsname":
break;
case "lastname":
break;
case "age":
break;
case "roomnumber":
break;
}
}
// static String sortByLastName()
// {
// Collections.sort(lines);
//
// for(String x : lines)
// System.out.println(x);
// }
class Patient
{
String firstName;
String lastName;
int age;
int roomNumber;
}
You should write a custom Comparator, let's call it PatientComparator. I will not implement the compare method completely, that's your job :-)
class PatientComparator implements Comparator<Patient> {
String sortType;
public PatientComparator(String sortType) {
this.sortType = sortType;
}
#Override
public int compare(Patient a, Patient b) {
// TODO: write your switch case here
return a.firstName.compareTo(b.firstName);
}
Then, you can sort the Patients using your own Comparator:
Collections.sort(patients, new PatientComparator(arg[1]));
Well I would start by dividing your exercise into two parts:
1- Calling the program through command-line with args[0]. Going through the file and showing the contents to the user (by respecting your format).
2- Add sorting to your script (this can be done in many ways; in general by overriding the compare method). Do step 1,sort with regarding to arg[1] and then the output.
To get you started I have done step 1 for you without doing any formatting on the output.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class Test3 {
//You will store each line as an array of strings
//then you store the lines in a list of arrays of strings
public static ArrayList<String[]> mainList=new ArrayList<String[]>();
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new FileReader(args[0]));
try {
//reading each line from the input file
String line = br.readLine();
//spliting the line by comma (,) which will return
//an array of strings - our names and numbers in string format
while (line != null) {
String[] lineElements=line.split(",");
line = br.readLine();
mainList.add(lineElements);
}
} finally {
br.close();
}
//showing to the user
for (String[] line :mainList){
for (String x:line){
System.out.print(x+" ");
}
System.out.println("");
}
}
}
You simply compile with: javac name.java
Then you simply specify the file's location when you actually run it: java name /path/to/your/file/
I have run it using your sample file and I get this in the console (you simply have to format the output):
Franklin Benjamin 74 18
Hamilton Alexander 25 6
Thatcher Margaret 65 3
Nixon Richard 45 7
There is much more to do but I think this is a great start!

Categories

Resources