join files using scanner - java

I have 2 files as below :
1.txt
first|second|third
fourth|fifth|sixth
2.txt
first1|second1|third1
fourth1|fifth1|sixth1
Now I want to join them both :
first|first1|second1|third1|second|third
fourth|fourth1|fifth1|sixth1|fifth|sixth
Am trying using scanner but not able to join them. Any suggestion.
Scanner scanner = new Scanner(new File(("F:\\1.txt")));
Scanner scanner2 = new Scanner(new File(("F:\\2.txt")));
while(scanner.hasNext()) {
while(scanner2.hasNext()) {
system.out.println(scanner.next() + "|" + scanner2.next() + "|");
}
// output
first|second|third|first1|second1|third1|
fourth|fifth|sixth|fourth1|fifth1|sixth1|

Scanner scanner = new Scanner(new File(("F:\\1.txt")));
Scanner scanner2 = new Scanner(new File(("F:\\2.txt")));
String[] line1, line2, res;
while (scanner.hasNext() && scanner2.hasNext()) {
line1 = scanner.next().split("\\|");
line2 = scanner2.next().split("\\|");
int len = Math.min(line1.length,line2.length);
res= new String[line1.length + line2.length];
for(int index = 0, counter = 0; index < len; index++){
res[counter++] = line1[index];
res[counter++] = line2[index];
}
if(line1.length > line2.length){
for(int jIndex = 2*line2.length, counter = 0;jIndex < (line1.length+line2.length);jIndex++ ){
res[jIndex] = line1[line2.length + (counter++)];
}
}else if(line2.length > line1.length){
for(int jIndex = 2*line1.length, counter = 0;jIndex < (line1.length+line2.length);jIndex++ ){
res[jIndex] = line2[line1.length + (counter++)];
}
}
String result = Arrays.asList(res).toString().replaceAll("(^\\[|\\]$)", "").replace(", ", "|");
System.out.println(result);
}
scanner.close();
scanner2.close();
You can discard the if conditions if both lines contains same number of tokens
This will give output as,
first|first1|second|second1|third|third1
fourth|fourth1|fifth|fifth1|sixth|sixth1
And
String[] line1, line2, res;
while (scanner.hasNext() && scanner2.hasNext()) {
line1 = scanner.next().split("\\|");
line2 = scanner2.next().split("\\|");
res= new String[line1.length + line2.length];
int counter = 0;
res[counter++] = line1[0];
for(int index = 0; index < line2.length; index++){
res[counter++] = line2[index];
}
for(int index = 1; index < line1.length; index++){
res[counter++] = line1[index];
}
String result = Arrays.asList(res).toString().replaceAll("(^\\[|\\]$)", "").replace(", ", "|");
System.out.println(result);
}
scanner.close();
scanner2.close();
will give output as
first|first1|second1|third1|second|third
fourth|fourth1|fifth1|sixth1|fifth|sixth

Related

How to add columns and give result in separate variable

I have a text file of format
aaaaa 128321 123465
bbbbb 242343 424354
ccccc 784849 989434
I would like to add values in 2nd column and 3rd column into separate variables.
I am new to Java
Thank you.
Below is code that i used but i want the sum:
File f = new File("SampleInput.txt");
try{
ArrayList<String> lines = get_arraylist_from_file(f);
for(int x =1; x < lines.size(); x++){
System.out.println(lines.get(x));
}
}catch(Exception e){System.out.println("File not found!!!!");}
}
public static ArrayList<String> get_arraylist_from_file(File f)
throws FileNotFoundException {
Scanner s;
ArrayList<String> list = new ArrayList<String>();
s = new Scanner(f);
while (s.hasNext()) {
list.add(s.next());
}
s.close();
return list;
}
String line = lines.get(x);
String[] columns = line.split("\\s+"); // \\s+ is regex that splits string by 1 or more white-characters
String first = columns[0];
String second = columns[1];
String third = columns[2];
Try this.
ArrayList<String> lines = get_arraylist_from_file(f);
int sum1 = 0, sum2 = 0;
for(int x = 0 ; x < lines.size(); x += 3){
sum1 += Integer.parseInt(lines.get(x + 1));
sum2 += Integer.parseInt(lines.get(x + 2));
}
System.out.println("sum1=" + sum1 + " sum2=" + sum2);

Reading Int from file in Java

Im trying to read from a text file certain numbers. It was working a few days ago and now suddenly its not reading the numbers after certain words. Here are my java functions for write and read. NOTE THIS IS USED IN A JSP:
public void writeToFile() {
try {
File aFile = new File(nameOfFile + "MAIN" + ".txt");
aFile.createNewFile();
PrintWriter writeTo = new PrintWriter(aFile);
writeTo.print("Matrix 1" + "\nRows: " + row1 + "\n");
writeTo.print("Columns: " + column1 + "\n");
writeTo.println("Method used: " + operationName);
if("DotProduct".equals(operationName))
writeTo.println("Vector: " + vectorRow1);
writeTo.println();
for(int i = 0; i < getRow1(); i++) {
int counter = 0;
for(int j = 0; j < getCol1(); j++, counter++)
writeTo.print(matrixToFile[i][j] + "\t");
if(counter == getCol1()) {
writeTo.print("\n");
}
}
writeTo.close();
File aFile2 = new File(nameOfFile + "SECOND.txt");
aFile2.createNewFile();
writeTo = new PrintWriter(aFile2);
writeTo.print("Matrix 2" + "\nRows: " + row2 + "\n");
writeTo.print("Columns: " + column2 + "\n");
if("DotProduct".equals(operationName))
writeTo.println("Vector: " + vectorCol2);
writeTo.println();
for(int i = 0; i < getRow2(); i++) {
int counter = 0;
for(int j = 0; j < getCol2(); j++, counter++)
writeTo.print(matrix2ToFile[i][j] + "\t");
if(counter == getCol2()) {
writeTo.print("\n");
}
}
writeTo.close();
File aFile3 = new File(nameOfFile + "RESULT.txt");
aFile3.createNewFile();
writeTo = new PrintWriter(aFile3);
writeTo.print("Result" + "\nRows: " + row3 + "\n");
writeTo.print("Columns: " + column3 + "\n");
writeTo.println();
if("DotProduct".equals(operationName))
writeTo.println("Result:" + resultVector);
else {
for(int i = 0; i < getRow3(); i++) {
int counter = 0;
for(int j = 0; j < getCol3(); j++, counter++)
writeTo.print(result[i][j] + "\t");
if(counter == getCol3()) {
writeTo.print("\n");
}
}
}
writeTo.close();
nameOfFile = "/var/lib/tomcat7/webapps/Matrices/WEB-INF/MatrixData/";
errors.put("dataStored", "Your results have been stored!");
} catch(IOException ex) {
System.out.printf("Error!");
}
}
This is the read file:
public void readFromFile(String resultOrNot, String fileName) {
nameOfFile = "/var/lib/tomcat7/webapps/Matrices/WEB-INF/MatrixData/";
workMe = fileName;
try {
Scanner readFile = new Scanner(new File(nameOfFile + workMe));
readFile.useDelimiter("Rows: ");
while(readFile.hasNextInt()) {
stringRow = readFile.next();
}
setRow1VIAString(stringRow);
readFile.useDelimiter("Columns: ");
while(readFile.hasNextInt()) {
stringCol = readFile.next();
}
setColumn1VIAString(stringCol);
readFile.useDelimiter("Method used: ");
while(readFile.hasNext()) {
operationName = readFile.next();
}
readFile.useDelimiter("\n");
for(int i = 0; i < row1 || readFile.hasNextDouble(); i++)
for(int j = 0; j < column1; j++)
matrix1[i][j] = readFile.nextDouble();
readFile.close();
workMe = workMe.replace("MAIN", "SECOND");
readFile = new Scanner(new File(nameOfFile + workMe));
readFile.useDelimiter("Rows: ");
while(readFile.hasNextInt()) {
stringRow = readFile.next();
}
setRow2VIAString(stringRow);
readFile.useDelimiter("Columns: ");
while(readFile.hasNextInt()) {
stringCol = readFile.next();
}
setColumn2VIAString(stringCol);
readFile.useDelimiter("\n");
for(int i = 0; i < row1 || readFile.hasNextDouble(); i++)
for(int j = 0; j < column1; j++)
matrix1[i][j] = readFile.nextDouble();
readFile.close();
if("giveMeResult".equals(resultOrNot)) {
workMe = workMe.replace("SECOND", "RESULT");
readFile = new Scanner(new File(nameOfFile + workMe));
readFile.useDelimiter("Rows: ");
while(readFile.hasNextInt()) {
stringRow = readFile.next();
}
setRow3VIAString(stringRow);
readFile.useDelimiter("Columns: ");
while(readFile.hasNextInt()) {
stringCol = readFile.next();
}
setColumn3VIAString(stringCol);
readFile.useDelimiter("\n");
for(int i = 0; i < row3 || readFile.hasNextDouble(); i++)
for(int j = 0; j < column3; j++)
matrix1[i][j] = readFile.nextDouble();
}
} catch(IOException ex) {
ex.printStackTrace();
}
}
The converting function:
public void setRow1VIAString(String aRow) {
row1 = Integer.parseInt(aRow);
}
And this is the error:
java.lang.NumberFormatException: null
java.lang.Integer.parseInt(Integer.java:454)
java.lang.Integer.parseInt(Integer.java:527)
matrixcalculator.MatrixCalculator.setRow1VIAString(MatrixCalculator.java:171)
matrixcalculator.MatrixCalculator.readFromFile(MatrixCalculator.java:728)
org.apache.jsp.choosing_jsp._jspService(choosing_jsp.java:84)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
I know it means that the string trying to me parse is null, what I dont understand is why is it null now? Its been working alright and now suddenly its doing this. Im aware of the whitespaces but I got them counted so that there wont be any problems.

List<String[]> method Adding always same values

In my Java Project, i want to read values from txt file to List method.Values seems like;
1 kjhjhhkj 788
4 klkkld3 732
89 jksdsdsd 23
Number of row changable. I have tried this codes and getting same values in all indexes.
What can i do?
String[] dizi = new String[3];
List<String[]> listOfLists = new ArrayList<String[]>();
File f = new File("input.txt");
try {
Scanner s = new Scanner(f);
while (s.hasNextLine()) {
int i = 0;
while (s.hasNext() && i < 3) {
dizi[i] = s.next();
i++;
}
listOfLists.add(dizi);
}
} catch (FileNotFoundException e) {
System.out.println("Dosyaya ba?lanmaya çal???l?rken hata olu?tu");
}
int q = listOfLists.size();
for (int z = 0; z < q; z++) {
for (int k = 0; k < 3; k++) {
System.out.print(listOfLists.get(z)[k] + " ");
}
}
String [] dizi = new String [3];
dizi is a global variable getting overridden eveytime in the loop. Thats why you are getting same values at all indexes
Make a new instance everytime before adding to the list.
You put the same reference to the list, create a new array in while loop.
while (s.hasNextLine()){
String[] dizi = new String[3]; //new array
int i = 0;
while (s.hasNext() && i < 3)
{
dizi[i] = s.next();
i++;
}
listOfLists.add(dizi);
}

Issues with arrays and repeating outputs

I have a problem that deals with reading a file and putting them into an array.
Then subtracting the arrays to equal 0
Here is what I got so far:
Scanner infile2 = new Scanner(new File(fname));
int [] nums = new int [n];
for (int i = 0; i<n; i++)
{
nums[i] = infile2.nextInt();
}
for (int j = 0; j<n-1;j++){
for (int k = j+1; k<n;k++){
if (nums[j]+nums[k]==0){
int val = nums[j]+nums[k];
}
}
}
}
}
Any suggestions?
Try doing it this way
Scanner infile2 = new Scanner(new File(fname));
int [] nums = new int [n];
for (int i = 0; i<n; i++){
nums[i] = infile2.nextInt();
}
for (int j = 0; j<n;j++){
for (int k = j+1; k<n;k++){
if (nums[j]+nums[k]==0){
int val = nums[j]+nums[k];
System.out.println("num["+j+"]"+ " + " +"num["+k+"]"+" = " + nums[j] + " + " + nums[k] + " = " + val);
}
}
}
take the nested loop out, then it should solve the repeated count issue
Here is what i tried:
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
String fname = "PathToFile/a.txt";
int n = 0;
Scanner infile = new Scanner(new File(fname));
while (infile.hasNextInt()){
n++;
infile.nextInt();
}
Scanner infile2 = new Scanner(new File(fname));
int [] nums = new int [n];
for (int i = 0; i<n; i++)
{
nums[i] = infile2.nextInt();
}
for (int j = 0; j<n-1;j++){
for (int k = j+1; k<n;k++){
if (nums[j]+nums[k]==0){
int val = nums[j]+nums[k];
System.out.println("num["+j+"]"+ " + " +"num["+k+"]"+" = " + nums[j] + " + " + nums[k] + " = " + val);
}
}
}
}catch(Exception e){
System.out.println(e);
}
}
result i am getting
num[1] + num[4] = -40 + 40 = 0
num[1] + num[7] = -40 + 40 = 0
num[3] + num[6] = -10 + 10 = 0

The program throws NullPointerException [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Not sure why it gives me the NullPointerException. Please help.
I am pretty sure all the arrays are full, and i restricted all the loops not to go passed empty spaces.
import java.util.;
import java.io.;
public class TextAnalysis {
public static void main (String [] args) throws IOException {
String fileName = args[0];
File file = new File(fileName);
Scanner fileScanner = new Scanner(file);
int MAX_WORDS = 10000;
String[] words = new String[MAX_WORDS];
int unique = 0;
System.out.println("TEXT FILE STATISTICS");
System.out.println("--------------------");
System.out.println("Length of the longest word: " + longestWord(fileScanner));
read(words, fileName);
System.out.println("Number of words in file wordlist: " + wordList(words));
System.out.println("Number of words in file: " + countWords(fileName) + "\n");
System.out.println("Word-frequency statistics");
lengthFrequency(words);
System.out.println();
System.out.println("Wordlist dump:");
wordFrequency(words,fileName);
}
public static void wordFrequency(String[] words, String fileName) throws IOException{
File file = new File(fileName);
Scanner s = new Scanner(file);
int [] array = new int [words.length];
while(s.hasNext()) {
String w = s.next();
if(w!=null){
for(int i = 0; i < words.length; i++){
if(w.equals(words[i])){
array[i]++;
}
}
for(int i = 0; i < words.length; i++){
System.out.println(words[i] + ":" + array[i]);
}
}
}
}
public static void lengthFrequency (String [] words) {
int [] lengthTimes = new int[10];
for(int i = 0; i < words.length; i++) {
String w = words[i];
if(w!=null){
if(w.length() >= 10) {
lengthTimes[9]++;
} else {
lengthTimes[w.length()-1]++;
}
}
}
for(int j = 0; j < 10; j++) {
System.out.println("Word-length " + (j+1) + ": " + lengthTimes[j]);
}
}
public static String longestWord (Scanner s) {
String longest = "";
while (s.hasNext()) {
String word = s.next();
if (word.length() > longest.length()) {
longest = word;
}
}
return (longest.length() + " " + "(\"" + longest + "\")");
}
public static int countWords (String fileName) throws IOException {
File file = new File(fileName);
Scanner fileScanner = new Scanner(file);
int count = 0;
while(fileScanner.hasNext()) {
String word = fileScanner.next();
count++;
}
return count;
}
public static void read(String[] words, String fileName) throws IOException{
File file = new File(fileName);
Scanner s = new Scanner(file);
while (s.hasNext()) {
String word = s.next();
int i;
for ( i=0; i < words.length && words[i] != null; i++ ) {
words[i]=words[i].toLowerCase();
if (words[i].equals(word)) {
break;
}
}
words[i] = word;
}
}
public static int wordList(String[] words) {
int count = 0;
while (words[count] != null) {
count++;
}
return count;
}
}
There are two problems with this code
1.You didn't do null check,although the array contains null values
2.Your array index from 0-8,if you wan't to get element at 9th index it will throw ArrayIndexOutOfBound Exception.
Your code should be like that
public static void lengthFrequency (String [] words) {
int [] lengthTimes = new int [9];
for(int i = 0; i < words.length; i++) {
String w = words[i];
if(null!=w) //This one added for null check
{
/* if(w.length() >= 10) {
lengthTimes[9]++;
} else {
lengthTimes[w.length()-1]++;
}
}*/
//Don't need to check like that ...u can do like below
for(int i = 0; i < words.length; i++) {
String w = words[i];
if(null!=w)
{
lengthTimes[i] =w.length();
}
}
}
//here we should traverse upto length of the array.
for(int i = 0; i < lengthTimes.length; i++) {
System.out.println("Word-length " + (i+1) + ": " + lengthTimes[i]);
}
}
Your String Array String[] words = new String[MAX_WORDS]; is not initialized,you are just declaring it.All its content is null,calling length method in line 31 will give you null pointer exception.
`
Simple mistake. When you declare an array, it is from size 0 to n-1. This array only has indexes from 0 to 8.
int [] lengthTimes = new int [9];
//some code here
lengthTimes[9]++; // <- this is an error (this is line 29)
for(int i = 0; i < 10; i++) {
System.out.println("Word-length " + (i+1) + ": " + lengthTimes[i]); // <- same error when i is 9. This is line 37
When you declare:
String[] words = new String[MAX_WORDS];
You're creating an array with MAX_WORDS of nulls, if your input file don't fill them all, you'll get a NullPointerException at what I think is line 37 in your original file:
if(w.length() >= 10) { // if w is null this would throw Npe
To fix it you may use a List instead:
List<String> words = new ArrayList<String>();
...
words.add( aWord );
Or perhaps you can use a Set if you don't want to have repeated words.

Categories

Resources