Java outputting to text file? - java

So I am having troubles printing to output. I understand the concept, but when it comes to this problem its kinda weird. I've tried different print lines and all of them give me different results from the console window. I'm still trying different things, but im starting to run out of ideas. Thanks and much appreciated !
This is what I want the expected output to be.
1
1, 2, 3, 4
When I try println it does this for output.println(data[0]);
1
, 2, 3, 4
when I do a regular print it does this
1, 2, 3, 4
This is the text file print method`
public class JavaApplication1 {
static int[] Array(int[] data) {
int size = 1;
if (data !=null) {
size = 1 +data.length;
}
return new int [size];
}
private static int[] addToArray(int[] data, int x) {
int[] array2 = Array(data);
if(data !=null) {
System.arraycopy(data,0,array2,0,data.length);
}
array2[array2.length - 1] = x;
return array2;
}
private int[] data;
public JavaApplication1 (int[] data, int x) {
this.data = addToArray(data, x);
}
public void printall() {
System.out.print(data[0]);
for (int i = 1; i < data.length; i++) {
System.out.printf(", %d", data[i]);
}
System.out.println();
} public void text() {
try {
PrintWriter output = new PrintWriter("test.txt");
output.print(data[0]);
for (int i = 1; i < data.length; i++) {
output.printf( ", %d", data[i]);
output.flush();
}
} catch (Exception ex) {
}
}
public static void main(String[] args) {
int[] in = {1,2,3};
int[] test = {1,2,3};
int l = 4;
int x = 4;
JavaApplication1 a = new JavaApplication1(null, 1);
a.printall();
JavaApplication1 b = new JavaApplication1(in, x);
b.printall();
JavaApplication1 c = new JavaApplication1(null, 1);
c.text();
JavaApplication1 d = new JavaApplication1(test, l);
d.text();
}
}

Try this :
public void text() {
try {
PrintWriter output = new PrintWriter("test.txt");
output.println(data[0]);
for (int i = 0; i < data.length; i++) {
if (i != (data.length - 1)) {
output.printf("%d, ", data[i]);
} else {
output.printf("%d", data[i]);
}
output.flush();
}
} catch (Exception ex) {
}
}

To make it a new line for each output loop it and add "\n" to each line you write or you can convert to string and edit String format to whatever you want. You can add a comma if you want
string.format()

try do in this way
public void text() {
try {
PrintWriter output = new PrintWriter("test.txt");
for (int i = 0; i < data.length; i++) {
if(i > 0){
output.print(",");
}
output.print(data[i]);
output.flush();
}
} catch (Exception ex) {
}
}

Try this:
PrintWriter output = new PrintWriter("test.txt");
output.println(data[0]); //this is where you call the println
for (int i = 0; i < data.length; i++) {
output.printf( ", %d", data[i]);
output.flush();
}

Cause of problem: In your code, everytime you call text(), you are replacing existing file, without updating or appending new data to it.
Refer this SO question. You can write printWriter as
PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter("test.txt", true)));
I have tested on local, Try this code.
public void text() {
try {
// Adding data to existing file without replacing it.
PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter("test.txt", true)));
output.print(data[0]);
for (int i = 1; i < data.length; i++) {
output.printf(", %d", data[i]);
}
output.print("\n"); // Added next line in the file
output.flush();
output.close(); // closing PrintWriter.
} catch (Exception ex) {
// log your exception.
}
}

Related

How do I turn this function from java to recieve an url to show the results

So I'm recieving this url http://cei.edu.uy/plata.txt which contains numbers, what my function does is try to give the least amount of money required to get to that number, but I don't know how to actually use the numbers in that url on my function and save the result in the file "result.txt", because as of now I'm giving the numbers mannualy with the var "V" I give the amount of money to the function. This is my code:
public static void main(String[] args) throws IOException {
try {
URL url = new URL("http://cei.edu.uy/plata.txt");
try (Scanner s = new Scanner(url.openStream())) {
File f = new File("result.txt");
try (PrintStream print = new PrintStream(f)) {
int bills[] = {2000, 1000, 500, 200, 100,50, 20, 10, 5, 2, 1};
int m = bills.length;
int V = 153;
System.out.println ( minBills(bills, m, V));
while (s.hasNext()) {
}
print.flush();
}
}
} catch (MalformedURLException ex) {
}
}
static int minBills(int bills[], int m, int V)
{
int table[] = new int[V + 1];
table[0] = 0;
for (int i = 1; i <= V; i++)
table[i] = Integer.MAX_VALUE;
for (int i = 1; i <= V; i++)
{
for (int j = 0; j < m; j++)
if (bills[j] <= i)
{
int sub = table[i - bills[j]];
if (sub != Integer.MAX_VALUE
&& sub + 1 < table[i])
table[i] = sub + 1;
}
}
if(table[V]==Integer.MAX_VALUE)
return -1;
return table[V];
}
}
you can get the numbers form the URL using InputStreamReader as below
private static List<Integer> getNumbersFromUrl(String string) {
List<Integer> nums = new ArrayList<>();
try {
URL link = new URL(string);
BufferedReader in = new BufferedReader(
new InputStreamReader(link.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
nums.add(Integer.parseInt(inputLine));
}
in.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return nums;
}
Passing URL string to above method
List<Integer> nums = getNumbersFromUrl("http://cei.edu.uy/plata.txt");
System.out.println("numbers:"+nums);
Output:
number:[8, 153, 10, 312]
EDIT
you can get the numbers from URL by calling getNumbersFromUrl method
and to assign 153 reading from URL, replace below line
int V = 153;
with
List<Integer> nums = getNumbersFromUrl("http://cei.edu.uy/plata.txt");
int v = nums.get(1);
Note: variable name should start with lowercase(camelCase)

The problem with the word display if I have too many blank lines

I did not want to repeat the other question, I solved a problem in which I post the most common word in the text, but I have a problem, it does not work if I have more blank lines, how can I solve it?
I tried other ways of stackoverflow, but failed.
This is my code.
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Map < String, Integer > map = new LinkedHashMap < String, Integer > ();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(System.in));
String currentLine = reader.readLine();
while (currentLine != null) {
String[] input = currentLine.replaceAll("[^a-zA-Z-\"\\n\\n\", \"\\n\"]", " ").toLowerCase().split(" ");
for (int i = 0; i < input.length; i++) {
if (map.containsKey(input[i])) {
int count = map.get(input[i]);
map.put(input[i], count + 1);
} else {
map.put(input[i], 1);
}
}
currentLine = reader.readLine();
}
String mostRepeatedWord = null;
int count = 0;
for (Map.Entry < String, Integer > m: map.entrySet()) {
if (m.getValue() > count) {
mostRepeatedWord = m.getKey();
count = m.getValue();
} else if (m.getValue() == count) {
String key = m.getKey();
if (key.compareTo(mostRepeatedWord) < 0) {
mostRepeatedWord = key;
}
}
}
System.out.println(mostRepeatedWord);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Modify your for loop so that you're not adding to your map on a blank line.
for (int i = 0; i < input.length; i++) {
// Skip the blank lines
if (!input[i].trim().equals("")) {
if (map.containsKey(input[i])) {
int count = map.get(input[i]);
map.put(input[i], count + 1);
} else {
map.put(input[i], 1);
}
}
}

Read from a text file, sort it, and write it again

So our professor has assigned us with a program which reads a text file he has provided us with; it sorts it, and creates a new file with the sorted stuff. He wants us to call three methods from the main i.e. read, sort, and write
I have done some of the work, but i'm confused what arguments to provide for io.sort. And how do i convert that text thing into an array to provide an argument Here's my code:
public void read() {
try {
Scanner myLocal = new Scanner(new File("dictionary.txt"));
while (myLocal.hasNextLine()) {
System.out.println(myLocal.nextLine());
}
} catch (IOException e) {
System.out.println(e);
}
}
public void sort(String[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1; j++) {
/* ERROR: When j == 0, j - 1 == -1, which is out of bounds */
if (arr[j - 1].compareTo(arr[j]) > 0) {
swap(j, arr);
}
}
}
}
public void swap(int j, String[] arr) {
String temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
}
public void write() {
try {
PrintStream writer = new PrintStream(new File("sorted.txt"));
for (int i = 0; i < 100; i++) {
writer.println(i);
}
writer.close();
} catch (IOException e) {
System.out.println(e);
}
}
Here is how i've changed my read() method:
public void read()
{
String[] myArray = new String[1000];
try {
Scanner myLocal = new Scanner( new File("dictionary.txt"));
String a = myLocal.nextLine();
while (myLocal.hasNextLine()){
for (int i=0; i<myArray.length; i++){
myArray[i] = a;
}
}
}
catch(IOException e){
System.out.println(e);
}
}
class IO{
String[] myArray = new String[30000];
public void read()
{
try {
Scanner myLocal = new Scanner( new File("dictionary.txt"));
while (myLocal.hasNextLine()){
for (int i=0; i<myArray.length; i++){
String a = myLocal.nextLine();
myArray[i] = a;
}
}
}
catch(IOException e){
System.out.println(e);
}
}
public void sort()
{
int n = myArray.length;
for (int i=0; i<n-1; i++){
for(int j=0; j<n-i-1; j++){
if(myArray[j+1].compareTo(myArray[j])<0){
String temp = myArray[j];
myArray[j] = myArray[j+1];
myArray[j+1] = temp;
//toLower
}
}
}
}
public void swap(int j, String[] arr)
{
String temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
public void write()
{
try{
PrintStream writer = new PrintStream(new File("sorted.txt"));
for (int i=0; i<myArray.length; i++){
writer.println(myArray[i] + "\n");
}
writer.close();
}
catch(IOException e){
System.out.println(e);
}
}
}
CORRECT CODE (SOLVED)
class IO{
String[] myArray = new String[30000];
public void read()
{
try {
Scanner myLocal = new Scanner( new File("dictionary.txt"));
while (myLocal.hasNextLine()){
for (int i=0; i<myArray.length; i++){
String a = myLocal.nextLine();
myArray[i] = a;
}
}
}
catch(IOException e){
System.out.println(e);
}
}
public void sort()
{
int n = myArray.length;
for (int i=0; i<n; i++){
for(int j=1; j<n-i; j++){
if (myArray[j-1].compareTo(myArray[j])>0){
swap(j, myArray);
}
}
}
}
public void swap(int j, String[] myArray)
{
String temp = myArray[j-1];
myArray[j-1]=myArray[j];
myArray[j]=temp;
}
public void write()
{
try{
PrintStream writer = new PrintStream(new File("myIgnoreNew.txt"));
for (int i=0; i<myArray.length; i++){
writer.println(myArray[i] + "\n");
}
writer.close();
}
catch(IOException e){
System.out.println(e);
}
}
}

Java - Comparing two huge text files

I am trying to develop a basic java program to compare two huge text files and print non matching records .i.e. similar to minus function in SQL. but I am not getting the expected results because all the records are getting printed even though both files are same. Also suggest me whether this approach is performance efficient for comparing two huge text files.
import java.io.*;
public class CompareTwoFiles {
static int count1 = 0 ;
static int count2 = 0 ;
static String arrayLines1[] = new String[countLines("\\Files_Comparison\\File1.txt")];
static String arrayLines2[] = new String[countLines("\\Files_Comparison\\File2.txt")];
public static void main(String args[]){
findDifference("\\Files_Comparison\\File1.txt","\\Files_Comparison\\File2.txt");
displayRecords();
}
public static int countLines(String File){
int lineCount = 0;
try {
BufferedReader br = new BufferedReader(new FileReader(File));
while ((br.readLine()) != null) {
lineCount++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return lineCount;
}
public static void findDifference(String File1, String File2){
String contents1 = null;
String contents2 = null;
try
{
FileReader file1 = new FileReader(File1);
FileReader file2 = new FileReader(File2);
BufferedReader buf1 = new BufferedReader(file1);
BufferedReader buf2 = new BufferedReader(file2);
while ((contents1 = buf1.readLine()) != null)
{
arrayLines1[count1] = contents1 ;
count1++;
}
while ((contents2 = buf2.readLine()) != null)
{
arrayLines2[count2] = contents2 ;
count2++;
}
}catch (Exception e){
e.printStackTrace();
}
}
public static void displayRecords() {
for (int i = 0 ; i < arrayLines1.length ; i++) {
String a = arrayLines1[i];
for (int j = 0; j < arrayLines2.length; j++){
String b = arrayLines2[j];
boolean result = a.contains(b);
if(result == false){
System.out.println(a);
}
}
}
}
}
Based upon your explanation you do not need embedded loops
consider
public static void displayRecords() {
for (int i = 0 ; i < arrayLines1.length && i < arrayLines2.length; i++)
{
String a = arrayLines1[i];
String b = arrayLines2[i];
if(!a.contains(b){
System.out.println(a);
}
}
For the performance wise, you should try to match the size of the files. If the sizes(in bytes) are exactly the same, you might not need to compare them.

How to subtract values of two lists/arrays in Java?

I am working on a Java project and I am having a problem. I want to have the subtract of two lists or arrays a and b in list/array c but I don't know how to do that. I want "a[i] -b[i]" should be in next list c where the value should be c[i] similarly for 5-2=3 any suggestion and help would be appreciated.
Code:
public static void länge() {
{
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(new File("C:\\Users/Voodoothechild/Desktop/Pidata/Anfang.txt")));
String line = null;
while ((line = br.readLine()) != null) {
{
BufferedReader bro = null;
try {
bro = new BufferedReader(new FileReader(new File("C:\\Users/Voodoothechild/Desktop/Pidata/Ende.txt")));
String lines = null;
while ((lines = br.readLine()) != null) {
String[] anfang = line.split("\n");
String[] ende = lines.split("\n");
List<Integer> an = new ArrayList<Integer>();
List<Integer> en = new ArrayList<Integer>();
for (int index = 0 ; index<ende.length ; index++) {
an.add(Integer.parseInt(anfang[index]));
en.add(Integer.parseInt(ende[index]));
Integer[] anf = new Integer[an.size()];
int[] result = new int[anf.length];
for (int i = 0; i < result.length; i++) {
result[i] = anf[i] - end[i];
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bro != null) {
try {
bro.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
}
}
It can be done easily using Stream API:
int[] list1 = {4,2,1};
int[] list2 = {2,2,-1};
IntStream.range(0, list1.length)
.mapToObj(i -> list1[i] - list2[i])
.collect(Collectors.toList());
or even easier using Javaslang:
Stream.range(0, list1.length)
map(i -> list1[i] - list2[i]);
or by zipping two lists together:
List.ofAll(list1)
.zip(List.ofAll(list2))
.map(t -> t._1 - t._2);
Its pretty straight forward. Before tackling a programming problem. Always do it in steps. Take your problem for example. You need to subtract values from 2 arrays with values.
int[] list1 = {4,2,1};
int[] list2 = {2,2,-1};
Now you have 2 list. Ok next step, write a loop to go through the list. But first make sure that both list have the same length or else you will get an index out of bounce.
for(int i =0; i< list1.length; i++)
{
list3[i] = list1[i] - list2[i];
}
Anyway here is the full answer. Be sure to understand it
public class subtract
{
public static void main(String[] args)
{
int[] list1 = {4,2,1};
int[] list2 = {2,2,-1};
int[] list3 = new int[list1.length];
//Looping the list
for(int i =0; i< list1.length; i++)
{
list3[i] = list1[i] - list2[i];
}
//Print Statement
for(int j =0; j< list3.length; j++)
{
System.out.println(list3[j]);
}
}
}
Here's a very simple answer you can apply to your program.
public static void main(String[] args) {
int[] a = new int[4];
int[] b = new int[4];
int[] c = new int[4];
a[0] = 5;
a[1] = 12;
a[2] = 20;
a[3] = 50;
b[0] = 1;
b[1] = 2;
b[2] = 3;
b[3] = 4;
for(int i=0; i<a.length; i++){
c[i] = a[i] - b[i];
System.out.println(c[i]);
}
}
The answer is the method removeAll of class Collection
ArrayList<Integer> s1 = new ArrayList<Integer>(Arrays.asList(a1));
ArrayList<Integer> s2 = new ArrayList<Integer>(Arrays.asList(a2));
s1.removeAll(s2);
Integer[] result = s1.toArray(new Integer[s1.size()]);

Categories

Resources