我正在开发Java项目,但遇到了问题。我想在列表/数组c中减去两个列表或数组a和b,但是我不知道该怎么做。我希望“ a [i] -b [i]”应在下一个列表c中,对于5-2 = 3,其值应为c[i]
类似,任何建议和帮助将不胜感激。
码:
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();
}
}
}
}
}
最佳答案
它非常简单。在解决编程问题之前。务必分步进行。以您的问题为例。您需要从2个数组中减去带有值的值。
int [] list1 = {4,2,1};
int [] list2 = {2,2,-1};
现在您有2个列表。好的下一步,编写一个循环遍历列表。但是首先要确保两个列表的长度相同,否则您将得到一个跳出的索引。
for(int i =0; i< list1.length; i++)
{
list3[i] = list1[i] - list2[i];
}
无论如何,这里是完整的答案。一定要了解它
公共课减
{
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]);
}
}
}