How can I print below result in java? - java

I am writing a java problem for converting the string with the "qwe" result.
Basically, the program requires to create a txt file with some words. Then, the program will read the words in txt and generate the words with qwe repeatedly.
If the words is abcdefg, the expected result should be qweqweq.
Can anyone help me?
import java.io.*;
public class Assignment2_1 {
static String[] readInputFile(String filename) {
int totalLines = 0;
try {
String thisLine;
BufferedReader reader = new BufferedReader(new FileReader(filename));
while ((thisLine = reader.readLine()) !=null){
totalLines++;
}
reader.close();
} catch (Exception e) {
System.out.println("File problem with" +filename);
System.exit(0);
}
String[] strArray = new String[totalLines];
try {
BufferedReader reader = new BufferedReader(new
FileReader(filename));
for (int i=0; i < totalLines; i++) {
strArray[i] = reader.readLine();
}
reader.close();
} catch (Exception e) {
System.out.println("File problem with" +filename);
System.exit(0);
}
return strArray;
}
public static void main(String[] args)
{
if (args.length != 1) {
System.out.println("Please provide a filename!\n");
System.exit(0);
}
String[] strArray = {"q","w","e"};
for (int i = 0; i <strArray.length; i++) {
System.out.println(strArray[i]);
}
}
}

You never call readInputFile(String) method in main(String[]) method.
You can try to use this code:
public static void main(String[] args){
if (args.length != 1) {
System.out.println("Please provide a filename!\n");
System.exit(0);
}
String[] lines=readInputFile(args[0]);
String[] strArray={"q","w","e"};
int count=0;
for(int i=0;i<lines.length;i++){
for(int j=0;j<lines[i].length();j++){
System.out.print(strArray[count%3]);
count++;
}
System.out.print("\r\n");
}
}

You can use Stream API too.
static String[] strArray={"q","w","e"};
int count=0;
public static void main(String[] args){
if (args.length != 1) {
System.out.println("Please provide a filename!\n");
System.exit(0);
}
String[] lines=readInputFile(args[0]);
Stream.of(lines).forEach(s->{
for(int j=0;j<s.length();j++){
System.out.print(strArray[count%3]);
count++;
}
System.out.print("\r\n");
}
}

Related

How can I read only the first word of each line in a file in Java?

I have a file and it contains name, surname and age information. For example: Mike, Tyson, 54. There is 1 person in every 1 row. I just want to read the names. How can I do that? I did the reading of all lines, but I could not only read the name.
public static void main(String[] args) {
File f = new File("C:/Users/muham/Desktop/students.txt");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
String s = reader.readLine();
String[] students = new String[6];
int i=0;
while(s != null){
students[i] = s;
s=reader.readLine();
i++;
}
Arrays.sort(students);
String[] arr = null;
for(i = 0; i<students.length;i++){
System.out.println(students[i]);
}
} catch (FileNotFoundException ex) {
} catch (IOException ex) {
}
}
Use split to get the name try this code
public static void main(String[] args) {
File f = new File("C:/Users/muham/Desktop/students.txt");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
String s = reader.readLine();
String[] students = new String[6];
int i=0;
while(s != null){
students[i] = s.split(",")[0];
s=reader.readLine();
i++;
}
//Arrays.sort(students);
String[] arr = null;
for(i = 0; i<students.length;i++){
System.out.println(students[i]);
}
} catch (FileNotFoundException ex) {
} catch (IOException ex) {
}
}

How return a multidimensional arrayList in java?

I want to create a multidimensional array and pass it as a parameter in a method and then fill the arrayList with elements and return the new version of the arrayList to be able to use that array in different classes but I get java.lang.NoSuchMethodError: I think the problem is about the way i return the array. I searched but I could not find . How can I do it correctly?
here is my code;
public test{
public static List<List<String>> 2Darray=new ArrayList<List<String>>(); // TE ERROR IN THIS LINE
public List<List<String>> fillArray(List<List<String>> array){
BufferedReader in = null;
ArrayList<String> row = new ArrayList<String>();
try {
in = new BufferedReader(new FileReader("sampleFile.txt"));
String read = null;
while ((read = in.readLine()) != null) {
String[] splited = read.split("\\s+");
for(int i=0; i<splited.length ; i++){
row.add(splited[i]);
}
array.add(row);
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
}
return array;
}
A little tinkering (just getting it to compile) results in this which seems not to have a problem. Perhaps your issue is elsewhere.
public List<List<String>> fillArray(List<List<String>> array) {
BufferedReader in = null;
ArrayList<String> row = new ArrayList<String>();
try {
in = new BufferedReader(new FileReader("sampleFile.txt"));
String read = null;
while ((read = in.readLine()) != null) {
String[] splited = read.split("\\s+");
for (int i = 0; i < splited.length; i++) {
row.add(splited[i]);
}
array.add(row);
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return array;
}
BTW: You should really use try with resources - it is much clearer.
Modified your code a bit so that it compiled, and replaced the reading from a text file to reading a string. There were several issues, but it seems to work. Give it a try.
The main problems I noticed were mismatching curly braces, and starting a variable name with a number.
import java.util.*;
import java.io.*;
public class Main {
public static List<List<String>> array2D = new ArrayList<List<String>>();
public List<List<String>> fillArray(List<List<String>> array) {
BufferedReader in = null;
ArrayList<String> row = new ArrayList<String>();
try {
String str = "Some test text";
InputStream is = new ByteArrayInputStream(str.getBytes());
//in = new BufferedReader(new FileReader("sampleFile.txt"));
in = new BufferedReader(new InputStreamReader(is));
String read = null;
while ((read = in.readLine()) != null) {
String[] splited = read.split("\\s+");
for(int i=0; i<splited.length ; i++) {
row.add(splited[i]);
}
array.add(row);
}
}
catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
}
finally {
try {
in.close();
}
catch (IOException e) {
}
}
return array;
}
public static void main(String[] args) {
Main main = new Main();
List<List<String>> test = main.fillArray(array2D);
for(int i = 0; i < test.size(); i++) {
for(int j = 0; j < test.get(i).size(); j++) {
System.out.println(test.get(i).get(j));
}
}
}
}

Is it possible to read data from file and store it into 2d Array,when we don't know the number of line in the file,in java

I have to read data from file Here is data and want plot a graph vs thick(column 1 in data) and alpha(column 3) for every model. Every model has 7 line data,the last that start with 0 not required. Here is my code. it works but i don't think it is good code.please, suggest me better way to do the same.
public class readFile {
public static int showLines(String fileName) {
String line;
int currentLineNo = 0;
BufferedReader in = null;
try {
in = new BufferedReader (new FileReader(fileName));
//read until endLine
while(((line = in.readLine()) != null)) {
if (!line.contains("M") && !line.contains("#") && !line.trim().startsWith("0")) {
//skipping the line that start with M, # and 0.
currentLineNo++;
}
}
} catch (IOException ex) {
System.out.println("Problem reading file.\n" + ex.getMessage());
} finally {
try { if (in!=null) in.close(); } catch(IOException ignore) {}
}
return currentLineNo;
}
//Now we know the dimension of matrix, so storing data into matrix
public static void readData(String fileName,int numRow) {
String line;
String temp []=null;
String data [][]=new String[numRow][10];
int i=0;
BufferedReader in = null;
try {
in = new BufferedReader (new FileReader(fileName));
//read until endLine
while(((line = in.readLine()) != null)) {
if (!line.contains("M") && !line.contains("#") && !line.trim().startsWith("0")) {
temp=(line.trim().split("[.]"));
for (int j = 0; j<data[i].length; j++) {
data[i][j] =temp[j];
}
i++;
}
}
// Extract one column from 2d matrix
for (int j = 0; j <numRow; j=j+6) {
for (int j2=j; j2 <6+j; j2++) {
System.out.println(Double.parseDouble(data[j2][0])+"\t"+Double.parseDouble(data[j2][2]));
//6 element of every model, col1 and col3
// will add to dataset.
}
}
} catch (IOException ex) {
System.out.println("Problem reading file.\n" + ex.getMessage());
} finally {
try { if (in!=null) in.close(); } catch(IOException ignore) {}
}
}
//Main Method
public static void main(String[] args) {
//System.out.println(showLines("rf.txt"));
readData("rf.txt",showLines("rf.txt") );
}
}
as johnchen902 implies use a list
List<String> input=new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
input.add(line);
}
br.close();
int N=input.get(0).split(",").size(); // here add your delimiter
int M=input.size();
String[][] data=new String[M][N]
for (int i=0;i<M;i++){
String[] parts = string.split("-");
for (int k=0;k<n;k++){
data[i][k]=parts[k];
}
}
something like that
hope it helps. plz put more effort into asking the question. Give us the needed Input files, and the Code you came up with until now to solve the problem yourself.

How do you store each value separately using comma then they store into separate array?

A simple data file which contains
1908,Souths,Easts,Souths,Cumberland,Y,14,12,4000
1909,Souths,Balmain,Souths,Wests,N
Each line represents a season of premiership and has the following format: year, premiers, runners up, minor premiers, wooden spooners, Grand Final held, winning score,
losing score, crowd
I know how to store a data into an array and use the delimiter, but I am not exactly sure how to store EACH data item by a comma into separate arrays? Some suggestions and what particular code to be used would be nice.
UPDATE:
I just added the code but it still didn't work. Here's the code:
import java.io.*;
import java.util.Scanner;
public class GrandFinal {
public static Scanner file;
public static String[] array = new String[1000];
public static void main(String[] args) throws FileNotFoundException {
File myfile = new File("NRLdata.txt");
file = new Scanner (myfile);
Scanner s = file.useDelimiter(",");
int i = 0;
while (s.hasNext()) {
i++;
array[i] = s.next();
}
for(int j=0; j<array.length; j++) {
if(array[j] == null)
;
else if(array[j].contains("Y"))
System.out.println(array[j] + " ");
}
}
}
Here you go. Use ArrayList. Its dynamic and convenient.
BufferedReader br = null;
ArrayList<String> al = new ArrayList();
String line = "";
try {
br = new BufferedReader(new FileReader("NRLdata.txt"));
while ((line = br.readLine()) != null) {
al.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < al.size(); i++) {
System.out.println(al.get(i));
}
What does not work in your case ?
Because your season array is empty. You need to define the length, for ex:
private static String[] season = new String[5];
This is not right because you don't know how many lines you are going to store. Which is why I suggested you to Use ArrayList.
After working around a bit, I have come up with following code:
private static File file;
private static BufferedReader counterReader = null;
private static BufferedReader fileReader = null;
public static void main(String[] args) {
try {
file = new File("C:\\Users\\rohitd\\Desktop\\NRLdata.txt");
counterReader = new BufferedReader(new FileReader(file));
int numberOfLine = 0;
String line = null;
try {
while ((line = counterReader.readLine()) != null) {
numberOfLine++;
}
String[][] storeAnswer = new String[9][numberOfLine];
int counter = 0;
fileReader = new BufferedReader(new FileReader(file));
while ((line = fileReader.readLine()) != null) {
String[] temp = line.split(",");
for (int j = 0; j < temp.length; j++) {
storeAnswer[j][counter] = temp[j];
System.out.println(storeAnswer[j][counter]);
}
counter++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
catch (FileNotFoundException e) {
System.out.println("Unable to read file");
}
}
I have added counterReader and fileReader; which are used for counting number of lines and then reading the actual lines. The storeAnswer 2d array contains the information you need.
I hope the answer is better now.

How to read files in several languages in Java?

I am trying to read and process several languages' dictionaries in Java. So how can I arrange my code according to that? Thanks.
To turn them uppercase, I used this:
String str_uc=str.toUpperCase(Locale.ENGLISH);
But it's not supported for other languages, I am trying to read.
However, the main issue is that I can't read files in other languages properly before I turned them into uppercase.
Here's what I have done so far. Works perfect for English dictionary.
import java.util.ArrayList;
import java.util.Locale;
import java.io.*;
public class XmlCreating {
static ArrayList<Character> keywordletters = new ArrayList<Character>();
static ArrayList<Character> wordletters = new ArrayList<Character>();
static ArrayList<String> threeletter = new ArrayList<String>();
static ArrayList<String> fourletter = new ArrayList<String>();
static ArrayList<String> fiveletter = new ArrayList<String>();
static ArrayList<String> sixletter = new ArrayList<String>();
static ArrayList<String> sevenletter = new ArrayList<String>();
static ArrayList<String> words = new ArrayList<String>();
static ArrayList<String> allletters = new ArrayList<String>();
public static boolean hasApostrophe(String line){
for(int i=0; i<line.length();i++) {
if(line.charAt(i)=='\'' || line.charAt(i)=='-' )
return false;
}
return true;
}
public static void findLetters(String word, ArrayList<Character> ary) {
for(int i=0; i<word.length(); i++) {
ary.add(word.charAt(i));
}
}
public static boolean consistLetters(String keyword,String word) {
keywordletters.clear();
wordletters.clear();
findLetters(keyword,keywordletters);
findLetters(word,wordletters);
boolean found = false;
for(int i=0; i<wordletters.size(); i++) {
found=false;
for(int j=0; j<keywordletters.size(); j++) {
if(keywordletters.get(j)!='\''){
if(wordletters.get(i)==keywordletters.get(j)) {
keywordletters.set(j,'\'');
found=true;
break;
}
}
}
if(found!=true)
return false;
}
return found;
}
public static void findWords(String keyword){
words.clear();
for(int i=0; i<threeletter.size(); i++)
{
if(consistLetters(keyword,threeletter.get(i))==true)
words.add(threeletter.get(i));
}
for(int i=0; i<fourletter.size(); i++){
if(consistLetters(keyword,fourletter.get(i))==true)
words.add(fourletter.get(i));
}
for(int i=0; i<fiveletter.size(); i++){
if(consistLetters(keyword,fiveletter.get(i))==true)
words.add(fiveletter.get(i));
}
for(int i=0; i<sixletter.size(); i++){
if(consistLetters(keyword,sixletter.get(i))==true)
words.add(sixletter.get(i));
}
for(int i=0; i<sevenletter.size(); i++){
if(consistLetters(keyword,sevenletter.get(i))==true)
words.add(sevenletter.get(i));
}
}
public static void main(String args[]) {
//Locale.setDefault(new Locale("tr","TR"));
try {
FileInputStream fstream1 = new FileInputStream("en-GB.dic");
DataInputStream in = new DataInputStream(fstream1);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String str;
while ((str = br.readLine()) != null) {
String str_uc=str.toUpperCase(Locale.ENGLISH);
if(hasApostrophe(str_uc)){
allletters.add(str_uc);
if(str.length()==3)
threeletter.add(str_uc);
else if(str.length()==4)
fourletter.add(str_uc);
else if(str.length()==5)
fiveletter.add(str_uc);
else if(str.length()==6)
sixletter.add(str_uc);
else if(str.length()==7)
sevenletter.add(str_uc);
}
}
in.close();
}
catch (Exception e) {
System.err.println(e);
}
System.out.println(sevenletter.size());
System.out.println(sixletter.size());
System.out.println(fiveletter.size());
System.out.println(allletters.size());
int noOfXml=(int)(sevenletter.size()/10);
int lastXml=(int)(sevenletter.size()%10);
try{
int a=0;
int b=10;
for(int x=1;x<noOfXml+1;x++) {
FileWriter fstream2 = new FileWriter(x+".xml");
BufferedWriter out = new BufferedWriter(fstream2);
out.write("<?xml version='1.0' encoding='utf-8' ?><dictionary>");
for(int i=a;i<b;i++) {
findWords(sevenletter.get(i));
out.write("<ltr s='"+sevenletter.get(i)+"' w=");
for(int j=0; j<words.size();j++) {
out.write("'"+words.get(j)+"'");
if(j<words.size()-1)
out.write(";");
}
out.write("/>");
}
a=b;
b=b+10;
out.write("</dictionary>");
//Close the output stream
out.close();
}}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
//for last five keywords
if(lastXml!=0) {
try{
FileWriter fstream3 = new FileWriter((noOfXml+1)+".xml");
BufferedWriter out1 = new BufferedWriter(fstream3);
out1.write("<?xml version='1.0' encoding='utf-8' ?><dictionary>");
for(int i=sevenletter.size()-lastXml;i<sevenletter.size();i++) {
findWords(sevenletter.get(i));
out1.write("<ltr s='"+sevenletter.get(i)+"' w=");
for(int j=0; j<words.size();j++) {
out1.write("'"+words.get(j)+"'");
if(j<words.size()-1)
out1.write(";");
}
out1.write("/>");
}
out1.write("</dictionary>");
//Close the output stream
out1.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}//main
}//class
I encode each file as UTF-8
I would read each dictionary into a Set<String> possibly a NavigableSet<String> for each langage and I would place these is a Map keyed by the language.
Another way is to use words as key in a Map:
HashMap<(String) word ,Set<(String) codeLanguage>>
and, as Peter Lawrey sed, in this same Map
<(String) codeLanguage, Set(String) allLanguageWorld>>
If you use oriental language, you have to use Unicode.

Categories