Reversing arraylist not working properly - java

My task is to read from an input file test.txt, this text has some sentences.
I need to write a class with a constructor and three methods.
One of which has to reverse the order of the words in a sentence.
import java.util.*;
import java.io.*;
public class Reverser {
Scanner sc3 = null ;
//constructor takes input file and initialize scanner sc pointing at input
public Reverser(File file)throws FileNotFoundException, IOException{
sc3 = new Scanner (file);
}
//this method reverses the order of the words in each line of the input
//and prints it to output file specified in argument.
public void reverseEachLine(File outpr)throws FileNotFoundException, IOException{
// ArrayList<String> wordsarraylist = new ArrayList<String>();
while(sc3.hasNextLine()){
String sentence = sc3.nextLine();
// int length = sentence.length();
String[] words = sentence.split(" ");
// wordsarraylist.clear();
List<String> wordsarraylist = new ArrayList<String>(Arrays.asList(words));
Collections.reverse(wordsarraylist);
FileWriter writer = new FileWriter(outpr,true);
for(String str: wordsarraylist) {
writer.write(str + " ");
}
writer.write(System.lineSeparator());
writer.close();
}
}
}
I have removed two other methods but they don't interfere with this one.
And this is my main:
import java.io.*;
public class DemoReverser {
public static void main (String [] args)
throws IOException, FileNotFoundException {
Reverser r = new Reverser(new File("test.txt"));
r.reverseEachLine(new File("out2.txt"));
}
}
The problem is that at the end of the execution my output file contains the same thing. It is not reversing the order. How come? doesn't Collections.reverse() reverse the order? And so when I print it I should have the words in reverse?
I am also required to use arraylist.
This my input file:
This is just a small file. That
has some lines of text.
If we are successful, these
lines will be
reversed.
Let's hope for the best!
I am supposed to get this in my output:
That file. small a just is This
text. of lines some has
these successful, are we If
be will lines
reversed.
best! the for hope Let's
But i am getting this:
This is just a small file. That
has some lines of text.
If we are successful, these
lines will be
reversed.
Let's hope for the best!

Try this code for the method reverseEachLine, it works fine. Don't construct Scanner at the constructor.
public class MyReverser {
private File inputFile;
public MyReverser(File file) {
this.inputFile = file;
}
public void reverseEachLine(File outpr) throws FileNotFoundException, IOException {
Scanner sc = new Scanner(inputFile);
ArrayList<List<String>> wordsarraylist = new ArrayList<List<String>>();
while (sc.hasNextLine()) {
String sentence = sc.nextLine();
List words = Arrays.asList(sentence.split(" "));
Collections.reverse(words);
wordsarraylist.add(words);
}
FileWriter writer = new FileWriter(outpr, false);
for (List<String> list : wordsarraylist) {
for (String string : list) {
writer.append(string + " ");
}
writer.append(System.lineSeparator());
}
writer.flush();
writer.close();
}
}
I have answered here with full code java cannot create file by 3 methods

Related

Why is my array returned by a method not printing to console?

I am writing a program that reads a .txt file into a String array suing a method. However, when I try to test my method by printing the array in the main program, nothing happens. I created a method to read the txt file into an array, and now I am trying to print this array in the main program to make sure it is working correctly.
All help is appreciated, here is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class P4Test {
public static void main(String[] args) throws FileNotFoundException {
// have user enter name for file
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of the file");
String nameOfFile = input.nextLine();
String[] test = readFile(nameOfFile);
System.out.println(Arrays.toString(test));
}
public static String[] readFile(String filename) throws FileNotFoundException
{
//read the file
Scanner file = new Scanner(new File(filename));
// read number of lines inside file
int numString = 0;
while (file.hasNextLine());
{
++numString;
file.nextLine();
}
file.close();
// now we read the file into a string array
Scanner keyboard = new Scanner(new File(filename));
String[] words = new String[numString];
// using a for loop to read in each line to the array
for (int index = 0; index < numString; ++index) {
words[index] = keyboard.nextLine();
}
keyboard.close();
return words;
}
}
Your code is perfectly fine, except for this line:
while (file.hasNextLine());
You need to remove that semicolon from while loop.

How to map first row(attribute name) in excel file with the all cell values in java?

I have tried the following code to get first row of value(attribute name) in excel file mapping with other specific cell values i.e attribute-name=value (e.g age=30-39,meno-pause=premeno,.. etc). And then, the mapping values are add ArrayList.
But no correct output please help me!
attribute-name>> age,meno-pause,tumor-size,inv-nodes,node-caps,deg-malig,breast,breast-quard,irradiat,Class
-------***
Values>>
30-39,premeno,30-34,0-2,no,3,left,left_low,no,no-recurrence-events
40-49,premeno,20-24,?,no,2,right,right_up,no,no-recurrence-events
40-49,premeno,20-24,0-2,no,2,left,left_low,no,no-recurrence-events
60-69,ge40,15-19,0-2,no,2,right,left_up,no,no-recurrence-events
40-49,premeno,0-4,0-2,no,2,right,right_low,no,no-recurrence-events
60-69,ge40,15-19,0-2,no,2,left,left_low,no,no-recurrence-events
50-59,premeno,25-29,0-2,no,2,left,left_low,no,no-recurrence-events
60-69,ge40,20-24,0-2,no,1,left,left_low,no,no-recurrence-events
40-49,premeno,50-54,0-2,no,2,left,left_low,no,no-recurrence-events
40-49,premeno,20-24,0-2,no,2,right,left_up,no,no-recurrence-events
Java Code
public class Excel {
private static Scanner sc;
public static void main(String[] args) throws FileNotFoundException {
List<String> transactions = new ArrayList<String>();
String str1,str2=null;
String addArray = null;
sc = new Scanner(new File("bc_dataset.csv"));
str1=sc.nextLine();
while (sc.hasNextLine())
{
String str2 = sc.nextLine();
transactions.add(str1 + "=" + str2);
System.out.println(transactions);
}
}
Check below changes. Explanation is in comments.
public class Excel {
private static Scanner sc;
public static void main(String[] args) throws FileNotFoundException {
List<String> transactions = new ArrayList<String>();
String str1,str2=null;
String addArray = null;
sc = new Scanner(new File("bc_dataset.csv"));
str1=sc.nextLine();
String []attributes = str1.split(","); // split the attributes by `,`. This will return array of String [age,meno-pause,tumor-size,...]
while (sc.hasNextLine())
{
String str2 = sc.nextLine();
String []linesplit = str2.split(","); // split the line by `,`. This will return array of String [30-39,premeno,30-34....]
// loop over both arrays and add them together
for(int i = 0; i<attributes.length; i++){
finalline = finalline+attributes[i]+"="+linesplit[i]+",";
}
// this will add extra `,` in the end of string which I leave on you to escape
transactions.add(finalline); // add final line to the list
System.out.println(transactions);
}
}

Input a text file in a two dimensional array with doubles

I'm new in Java.
I want to input a text file and create from it a two dimensional array the input is
like this
12,242 323,2324
23,4434 23,4534
23,434 56,3434
....
34,434 43,3443
I have tried
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class InputText {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
int i=0;
File file;
file = new File("file.txt");
Scanner read=new Scanner(file);
while (read.hasNextLine()) {
String line=read.nextLine();
System.out.println(line);
}
}
}
which gives me the input but I cannot insert this in an array I tried different ways like splitting it.
Any suggestions?
Sorry for not being clear. The input i mentioned is doubles seperated by spaces. Also the format i gave you is what i get after i run the part of the programm i wrote. What i see in the text file is the numbers seperated by spaces. I tried to implement your suggestion but nothing seemed to work. I'm really lost here....
If you want to split a line to two numbers you can use
string[] numbers = line.split("\\s+");
If you want to read a double with comma
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
...
double d1 = format.parse(numbers[0]).doubleValue();
double d2 = format.parse(numbers[1]).doubleValue();
Personally i prefer to use scanner. In that case create it with
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
Scanner scanner2 = new Scanner(scanner.nextLine()).useLocale(Locale.FRANCE);
if (!scanner2.hasNextDouble()){
System.out.println("Do not have a pair");
continue;
}
double d1 = scanner2.nextDouble();
if (!scanner2.hasNextDouble()){
System.out.println("Do not have a pair");
continue;
}
double d2 = scanner2.nextDouble();
//do something
}
After reading the line.. you will have to again split the string on ','. The split string need to be converted into interger. YOu can see as below:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class InputText {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
int i = 0;
File file;
file = new File("file.txt");
Scanner read = new Scanner(file);
while (read.hasNextLine()) {
String line = read.nextLine();
String[] numbers = line.split(",");
for (i = 0; i < numbers.lenght; i++) {
String numStr = numbers[i];
String x=numStr.replaceAll("\\s+",""); //eleminate the space in any.
Double num = Double.valueOf(x);
System.out.println(" num is: " + num); //Here you can store the number in array.
}
}
}
}
Try to use something like that(add also try catch statement)
String line = "";
br = new BufferedReader(new FileReader("file.txt"));
int i=0;
while ((line = br.readLine()) != null) {
// use comma as separator
String[] lineArray= line.split(",");
for(int j=0;j<lineArray.length;j++){
my2DArray[i][j] = lineArray[j];
}
i++;
}
for(int i=0;i<my2DArray[0].length;i++){
for(int j=0;j<my2DArray[1].length;j++){
System.out.print(my2DArray[i][j] + " ");
}
}

Trying to alter a text file in java

Here is my code:
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
public class Filter{
Message myMessage;
Scanner input;
Scanner input2;
String sender;
String subject;
String emailMIN;
String line;
String line2;
ArrayList<String> blacklist = new ArrayList<String>();
ArrayList<String> keywords = new ArrayList<String>();
ArrayList<String> subjectWords = new ArrayList<String>();
ArrayList<String> emails = new ArrayList<String>();
//String[] lines;
File SpamMessage;
File inFile;
File inFile2;
File tempFile;
String[] lines;
public Filter(Message m,String blacklistFile, String keywordFile, String Spam)throws IOException{
inFile = new File(blacklistFile);
inFile2 = new File(keywordFile);
input = new Scanner (inFile);
input2 = new Scanner (inFile2);
myMessage =m;
SpamMessage=new File(Spam);
}
public void filter() throws IOException{
PrintWriter output = new PrintWriter(SpamMessage);
while(input.hasNextLine()){
line = input.nextLine();
//System.out.println(line);
if(line!=null)
blacklist.add(line);
}
while(input2.hasNextLine()){
line2 = input2.nextLine();
//System.out.println(line2);
if(line!=null)
keywords.add(line2);
}
emails=myMessage.getEmails();
// System.out.println(emails.size() + emails.get(1));
for(int i = 0; i < emails.size(); i++){
// boolean isSpam = false;
lines = emails.get(i).split("\n");
// System.out.println(lines[5] + lines[7]);
sender = lines[2].substring(lines[2].indexOf('<'), lines[2].indexOf('>'));
//` System.out.println(sender);
emailMIN = lines[6].substring(lines[6].indexOf('<'), lines[6].indexOf('>'));
// System.out.println(emailMIN);
for(int j =0; j<lines.length; j++)
{
if(j==2)
{
for(String blacklist2: blacklist)
{
// System.out.println(blacklist2);
if(lines[j].contains(blacklist2))
{
output.println(emailMIN);
}
// output.close();
}
}
if(j==5 || j>=7)
{
// System.out.println(keywords.size());
for(String keywords2: keywords)
{
// System.out.println(keywords2);
if(lines[j].contains(keywords2))
{
output.println(emailMIN);
}
// output.close();
}
}
//addKeywords();
}
}
output.close();
addKeywords();
}
public void addKeywords() throws IOException
{
tempFile = new File("tempFile.txt");
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
for(int i=0; i<lines.length; i++)
{
if(i==5){
String[] words = lines[i].split(" ");
for(String word: words){
if(word.length()>=6){
subjectWords.add(word +"\n");
//System.out.println(subjectWords);
}
}
keywords.addAll(subjectWords);
pw.println(keywords);
}
}
pw.close();
if (!inFile2.delete()) {
//System.out.println("Could not delete file");
return;
}
// Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile2)){
//System.out.println("Could not rename file");
}
}
}
I'm trying to update the list of words in the keywords txt file right now it does update it but it puts it in the format [generic, pharmacy, little, inside]
Which is wrong because then if I run my code again it is searching if the file contains [generic, pharmacy, little, inside] and I need it to search for every word not the plus a comma or brace. So basically I want it to copy the words in a list format like this
generic
pharmacy
little
inside
That way it searches for each individual word. I figured out how to do this part. Now, how do I add the senders to a different text file? Also is there a way to modify this so it doesn't add the same keywords twice? Thanks
It is because you are writing an array to the file which causes the toString method of it to be called. Write every single item instead.
Instead of pw.println(keywords); 
Do:
for (String keyword : keywords)
{ 
pw.println(keyword.trim());
}
Or, if every word contains \n already, this should work
for (String keyword : keywords)
{ 
pw.print(keyword);
}
Instead of doing:
pw.println(keywords);
you should instead loop through the array and add each line individually.
for(int i = 0; i < keywords.length; i++) {
pw.println(keywords[i]);
}
That was because you are printing an ArrayList object. In your code, keywords is instance of the List and which would you give you an output of [aa,bb] . More over you would get duplicate words since these list instance are class variables, and printed inside a loop
keywords.addAll(subjectWords);
pw.println(keywords);
Either you can loop around keywords outside the for loop or print the word before adding to list.

How to filter out info by using useDelimiter

So, what am I trying to do is I get the info from a text file,
For example, 134567H;Gabriel;24/12/1994;67;78;89
Then I display only Admin number which is the first one but not the whole line in drop down list. So here are my codes :
public static String[] readFile(){
String file = "output.txt";
ArrayList <String> studentList = new ArrayList <String> ();
try{
FileReader fr = new FileReader(file);
Scanner sc = new Scanner(fr);
sc.useDelimiter(";");
while(sc.hasNextLine()){
studentList.add(sc.nextLine());
}
fr.close();
}catch(FileNotFoundException exception){
System.out.println("File " + file + " was not found");
}catch(IOException exception){
System.out.println(exception);
}
return studentList.toArray(new String[studentList.size()]);
}
And this is how I populate the drop down list :
public void populate() {
String [] studentList ;
studentList = Question3ReadFile.readFile();
jComboBox_adminNo.removeAllItems();
for (String str : studentList) {
jComboBox_adminNo.addItem(str);
}
}
However, my problem now is the options in drop down list is showing the whole line from the text file. It is not showing the admin number only. I tried with useDelimiter already. Am I supposed to use that?
Any help would be appreciated. Thanks in advance.
Rince help check.
public class Question3ReadFile extends Question3 {
private String adminNo;
public Question3ReadFile(String data) {
String[] tokens = data.split(";");
this.adminNo = tokens[0];
}
public static String[] readFile(){
String file = "output.txt";
ArrayList <String> studentList = new ArrayList <String> ();
try{
FileReader fr = new FileReader(file);
Scanner sc = new Scanner(fr);
while(sc.hasNextLine()){
studentList.add(new Question3ReadFile(sc.nextLine()));
}
fr.close();
}catch(FileNotFoundException exception){
System.out.println("File " + file + " was not found");
}catch(IOException exception){
System.out.println(exception);
}
return studentList.toArray(new String[studentList.size()]);
}
hasNext and next instead of hasNextLine and nextLine
public static void main(String[] args) {
String input = " For example, 134567H;Gabriel;24/12/1994;67;78;89";
Scanner scanner = new Scanner(input);
scanner.useDelimiter(";");
String firstPart = null;
while(scanner.hasNext()){
firstPart = scanner.next();
break;
}
String secondPart = input.split(firstPart)[1].substring(1);
System.out.println(firstPart);
System.out.println(secondPart);
scanner.close();
}
Don't use delimiter in this case. I suggest to make a Student object out of the line.
studentList.add(new Student(sc.nextLine));
and have the Student class:
public class Student {
private final String adminNo;
public Student(String data) {
String[] tokens = data.split(";");
this.adminNo = tokens[0];
}
public String getAdminNo() {
return adminNo;
}
}
and then you just read the fields you need later (student.getAdminNo()) for example.
This approach is much prettier and easier to extend later.
upd: simplistic approach
Or don't bother with stupid OO and just do this:
studentList.add(sc.nextLine.split(";")[0]);

Categories

Resources