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()]);
Related
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)
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.
}
}
I'm going to show all of my code here so you guys get a gist of what I'm doing.
import java.io.*;
import java.util.*;
public class Plagiarism {
public static void main(String[] args) {
Plagiarism myPlag = new Plagiarism();
if (args.length == 0) {
System.out.println("Error: No files input");
}
else if (args.length > 0) {
try {
List<String> foo = new ArrayList<String>();
for (int i = 0; i < 2; i++) {
BufferedReader reader = new BufferedReader (new FileReader (args[i]));
foo = simplify(reader);
for (int j = 0; j < foo.size(); j++) {
System.out.print(foo.get(j));
}
}
int blockSize = Integer.valueOf(args[2]);
System.out.println(args[2]);
// String line = foo.toString();
List<String> list = new ArrayList<String>();
for (int k = 0; k < foo.size() - blockSize; k++) {
list.add(foo.toString().substring(k, k+blockSize));
}
System.out.println(list);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
public static List<String> simplify(BufferedReader input) throws IOException {
String line = null;
List<String> myList = new ArrayList<String>();
while ((line = input.readLine()) != null) {
myList.add(line.replaceAll("[^a-zA-Z]","").toLowerCase());
}
return myList;
}
}
This is the code that is using substring.
int blockSize = Integer.valueOf(args[2]);
//"foo" is an ArrayList<String> which I have to convert toString() to use substring().
String line = foo.toString();
List<String> list = new ArrayList<String>();
for (int k = 0; k < line.length() - blockSize; k++) {
list.add(line.substring(k, k+blockSize));
}
System.out.println(list);
When I specify blockSize as 4 in cmd this is the result:
[[, a, , ab, abc ]
the text file (standardised using my other code) is this:
abcdzaabcdd
so the result should be this:
[abcd, bcdz, cdza, ] etc.
Any help?
Thanks in advance.
Here is code showing how to improve a little your code. Main change is returning simplified string from simplify method instead of List<String> of simplified lines, which after converting it to string returned String in form
[value0, value1, value2, ...]
Now code returns String in form value0value1value2.
Another change is lowering indentation lever by removing unnecessary else if statement and braking control flow with System.exit(0); (you can also use return; here).
class Plagiarism {
public static void main(String[] args) throws Exception {
//you are not using 'myPlag' anywhere, you can safely remove it
// Plagiarism myPlag = new Plagiarism();
if (args.length == 0) {
System.out.println("Error: No files input");
System.exit(0);
}
String foo = null;
for (int i = 0; i < 2; i++) {
BufferedReader reader = new BufferedReader(new FileReader(args[i]));
foo = simplify(reader);
System.out.println(foo);
}
int blockSize = Integer.valueOf(args[2]);
System.out.println(args[2]);
List<String> list = new ArrayList<String>();
for (int k = 0; k < foo.length() - blockSize; k++) {
list.add(foo.toString().substring(k, k + blockSize));
}
System.out.println(list);
}
public static String simplify(BufferedReader input)
throws IOException {
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = input.readLine()) != null) {
sb.append(line.replaceAll("[^a-zA-Z]", "").toLowerCase());
}
return sb.toString();
}
}
I am trying to read a txt file into a array of doubles. I am using the following code which reads every line of the file:
String fileName="myFile.txt";
try{
//Create object of FileReader
FileReader inputFile = new FileReader(fileName);
//Instantiate the BufferedReader Class
BufferedReader bufferReader = new BufferedReader(inputFile);
//Variable to hold the one line data
String line;
// Read file line by line and print on the console
while ((line = bufferReader.readLine()) != null) {
System.out.println(line);
}
//Close the buffer reader
bufferReader.close();
}catch(Exception e){
System.out.println("Error while reading file line by line:"
+ e.getMessage());
}
However I want to store the txt file into a 2d double array.
I ve tried the above to load also the dimension of the txt. But I am having problems with the exceptions catch (NoSuchElementException e), it seems that it couldnt read the file.
try {
while (input.hasNext()) {
count++;
if (count == 1) {
row = input.nextInt();
r = row;
System.out.println(row);
continue;
} else if (count == 2) {
col = input.nextInt();
System.out.println(col);
c = col;
continue;
} else {
output_matrix = new double[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
String el = input.next();
Double temp = Double.valueOf(el);
double number = temp.doubleValue();
//output_matrix[i][j] = el;
output_matrix[i][j] = number;
//System.out.print(output_matrix[i][j]+" ");
}
//System.out.println();
}
}
}
} catch (NoSuchElementException e) {
System.err.println("Sfalma kata ti tropopoisisi toy arxeioy");
System.err.println(e.getMessage()); //emfanisi tou minimatos sfalmatos
input.close();
System.exit(0);
} catch (IllegalStateException e) {
System.err.println("Sfalma kata ti anagnosi toy arxeioy");
System.exit(0);
}
You might want to be using the Scanner class for it, especially the Scanner.nextDouble() method.
Also, if you don't know in advance the dimensions of the array - I'd suggest using an ArrayList instead of a regular array.
Code example:
ArrayList<ArrayList<Double>> list = new ArrayList<>();
while ((line = bufferReader.readLine()) != null) {
ArrayList<Double> curr = new ArrayList<>();
Scanner sc = new Scanner(line);
while (sc.hasNextDouble()) {
curr.add(sc.nextDouble());
}
list.add(curr);
}
At firs declare a list and collect into it all read lines:
List<String> tempHistory = new ArrayList<>();
while ((line = bufferReader.readLine()) != null) {
tempHistory.add(line);
}
Then, after bufferReader.close(); convert this tempHistory list into double[][] array.
double[][] array = new double[tempHistory.size()][];
for (int i = 0; i < tempHistory.size(); i++) {
final String currentString = tempHistory.get(i);
final String[] split = currentString.split(" ");
array[i] = new double[split.length];
for (int j = 0; j < split.length; j++) {
array[i][j] = Double.parseDouble(split[j]);
}
}
It works, but as I added in comments, this is a not so good solution, and is better to use Collections instead of array.
BTW, it works even the rows lengths are different for different lines.
So what i need to do is load a csv file to a JTable with dynamic array(anywhere between 2 and 6 values), first i came up with this solution:
private String[][] Load()
{
try {
final BufferedReader br = new BufferedReader(new FileReader("FilePath");
try{
String line;
final ArrayList<String> List1 = new ArrayList<String>();
final ArrayList<String> List2 = new ArrayList<String>();
final ArrayList<String> List3 = new ArrayList<String>();
while((line = br.readLine()) != null)
{
final String[] parse = line.split(",");
List1.add(parse[0]);
List2.add(parse[1]);
List3.add(parse[2]);
}
final ArrayList[] lists = new ArrayList[]{List1, List2, List3};
final String[][] temp = new String[List1.size()][List1.get(0).split(",").length];
for(int x = 0 ; x < temp.length ; x++)
{
for(int y = 0 ; y < temp[x].length ; y++)
{
temp[x][y] = (String) lists[y].get(x);
}
}
return temp;
}finally
{
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
which i thought was horrible, so i came up with this solution:
private String[][] Load()
{
try
{
final BufferedReader br = new BufferedReader(new FileReader("FilePath"));
try
{
final List<String> raw = new ArrayList<String>();
String line;
while((line = br.readLine()) != null)
raw.add(line);
final String[][] temp = new String[raw.size()][raw.get(0).split(",").length];
for(int x = 0 ; x < raw.size() ; x++)
{
final String[] parse = raw.get(x).split(",");
for(int y = 0 ; y < temp[x].length ; y++)
{
temp[x][y] = parse[y];
}
}
return temp;
}finally
{
br.close();
}
}catch(IOException e){
e.printStackTrace();
}
return null;
}
but i'm not so sure about that either, both of them work just fine so really all i'm asking is, how would you do it?
Edit: can't really use external libs with this project.