how do I subract ints from each other in an array Java - java

I have to write a program where the user inputs 3 numbers into an array and then the output is the numbers subtracted from each other.
I have tried using a for loop for this but it just outputs the numbers added together then turns it negative eg : if i put in the numbers 1,2 and 3 it should output -4 but outputs -6.
this is my code : (the print line part is in another method )
int sub = 0;
for(int j =0; j < numbers.length;j++)
{
sub -= numbers[j];
}
return sub;
how do I get the numbers to subtract.
Also if anyone knows how to get the numbers to divide by each other that would be really helpful : )
Thanks in advance

int sub = numbers[0];
for(int j = 1; j < numbers.length;j++)
{
sub -= numbers[j];
}
return sub;
To divide, use /= instead of -=.

Change it to look like this:
int sub = numbers[0];
for (int j = 1; j < numbers.length; j++) {
sub -= numbers[j];
}
return sub;
Your code does
0 - numbers[0] - numbers[1] - numbers[2]
when what you want is
numbers[0] - numbers[1] - numbers[2]

It seems that you are assigning sub= 0 which is creating an issue. You need to assign the first value of array instead.
I have corrected the code for you:
public static void main (String[] args) throws java.lang.Exception
{
int a [] ={1, 2, 3};
int sub = a[0];
for(int j =1; j < a.length;j++)
{
sub = sub -a[j];
}
System.out.println (sub);
}
You may run this code here. You may find complete code here

Related

2D Array with variable internal array length JAVA

Im currently writing some code that print Pascal's Triangle. I need to use a 2D array for each row but don't know how to get the internal array to have a variable length, as it will also always changed based on what row it is int, for example:
public int[][] pascalTriangle(int n) {
int[][] array = new int[n + 1][]
}
As you can see I know how to get the outer array to have the size of Pascal's Triangle that I need, but I don't know how to get a variable length for the row that corresponds with the line it is currently on.
Also how would I print this 2D array?
Essentially what you want to happen is get the size of each row.
for(int i=0; i<array.size;i++){//this loops through the first part of array
for(int j=0;j<array[i].size;j++){//this loops through the now row
//do something
}
}
You should be able to use this example to also print the triangle now.
This is my first answer on StackOverFlow. I am a freshman and have just studied Java as part of my degree.
To make every step clear, I will put different codes in different methods.
Say n tells us how many rows that we are going to print for the triangle.
public static int[][] createPascalTriangle(int n){
//We first declare a 2D array, we know the number of rows
int[][] triangle = new int[n][];
//Then we specify each row with different lengths
for(int i = 0; i < n; i++){
triangle[i] = new int[i+1]; //Be careful with i+1 here.
}
//Finally we fill each row with numbers
for(int i = 0; i < n; i++){
for(int j = 0; j <= i; j++){
triangle[i][j] = calculateNumber(i, j);
}
}
return triangle;
}
//This method is used to calculate the number of the specific location
//in pascal triangle. For example, if i=0, j=0, we refer to the first row, first number.
public static int calculateNumber(int i, int j){
if(j==0){
return 1;
}
int numerator = computeFactorial(i);
int denominator = (computeFactorial(j)*computeFactorial(i-j));
int result = numerator/denominator;
return result;
}
//This method is used to calculate Factorial of a given integer.
public static int computeFactorial(int num){
int result = 1;
for(int i = 1; i <= num; i++){
result = result * i;
}
return result;
}
Finally, in the main method, we first create a pascalTriangle and then print it out using for loop:
public static void main(String[] args) {
int[][] pascalTriangle = createPascalTriangle(6);
for(int i = 0; i < pascalTriangle.length; i++){
for(int j = 0; j < pascalTriangle[i].length; j++){
System.out.print(pascalTriangle[i][j] + " ");
}
System.out.println();
}
}
This will give an output like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

2D Array Scores

This is the original prompt:
Write program that declares a 2-dimensional array of doubles called scores with three rows and three columns. Use a nested while loop to get the nine (3 x 3) doubles from the user at the command line. Finally, use a nested for loop to compute the average of the doubles in each row and output these three averages to the command line.
Here is my code:
import java.util.Scanner;
public class Scorer {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double [][] scores = new double[3][3];
double value = 0;
int i = 0;
int j;
while (i < 3) {
j = 0;
while (j < 3) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
scores[i][j] = value;
j++;
}
i++;
}
int average = 0;
for (i = 0; i < scores.length; i++) {
for (j = 0; j < scores[i].length; j++) {
average += value;
value = value / scores[i][j];
System.out.println(value);
}
}
}
}
The part that I need help on is the nested for loop at the bottom of the code. This code is supposed to compute the average of the numbers that are entered; however, I am confused on how to do that with the nested for loop.
you're almost there!
Here are the things you need to do:
1)you've to initialize the variable 'average' after the first for loop.
because average needs to be 0 i.e., reset after second for loop ends each time.
2)you've defined "value = value / scores[i][j]" . I don't know why you did that, but "value = scores[i][j]" must solve your problem.
3) you should print the average only thrice i.e., after calculating average of each row. so, print average at the end of second for loop.
Hope this makes it clear.
here's the code for your reference:
for (i = 0; i < 3; i++) {
int average = 0;
for (j = 0; j < 3; j++) {
value = scores[i][j];
average += value;
}
System.out.println(average/3);
}
Ever i represents a row, every j represents a column.
You need the average of every row, meaning that for every same i and every different j for that i you need to store the values and calculate the average.
Looks like homework code. We can give you hints but not write it for you :(

A method to solve a word search in Java using 2d arrays.?

I'm trying to create a method that will search through a 2d array of numbers. If the numbers add up to a certain sum, those numbers should remain and all of the other numbers should be changed to a 0. For example, if the desired sum is 7 and a row contains 2 5 1 2, the result should be 2 5 0 0 after the method is implemented. I have everything functioning but instead of keeping all of the numbers that add up to the sum, only the last number is retained. So, I am left with 0 5 0 0 . I think I need another array somewhere but not sure exactly how to go about implementing it. Any ideas?
public static int[][] horizontalSums(int[][] a, int sumToFind) {
int[][] b = new int[a.length][a[0].length];
int columnStart = 0;
while (columnStart < a[0].length) {
for (int row = 0; row < a.length; row++) {
int sum = 0;
for (int column = columnStart; column < a[row].length; column++) {
sum += a[row][column];
if (sum == sumToFind) {
b[row][column] = a[row][column];
}
}
}
columnStart++;
}
return b;
}
In your example you use 2 5 1 1, would 0 5 1 1 also be a valid response? Or do you just need to find any combination? A recursive function may be the best solution.
If you just need to scan through the array and add up the numbers until the sum is reached then just add a for loop to copy the previous values from the array to the new array when the sum is found. Something like:
if (sum == sumToFind)
{
for (int i= 0; i<= columnStart; i++)
{
b[row][i] = a[row][i];
}
}
if (sum == sumToFind)
{
for (int i= columnStart; i<= column; i++)
{
b[row][i] = a[row][i];
}
}
A minor tweak was all it needed. If you have columnStart and column like in the other answer, it only finds the first number of the series.

Adding integers of array upto some number (java)

I have a java question.
I have two int[] arrays: cdn and cmn.
cdn is {1,1,1,1,1,1,2,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
cmn is {8,8,16}
I need a program that adds the consecutive integers of cdn[] upto cmn[init] and returns the number of integers used in the addition. Then it continues adding from the next integer of cdn[] upto cmn[init+1] and return the number of integers. For the arrays above this is done 3 times: the first time the return value is 7, the second time it is 7, and the third time it is 16. The number of integers can be collected in and int[] which is {7,7,16}. The code I have is:
int numofints = 0;
int init = 0;
int plus = 0;
while(init < m2){
for(int j = 0; j < cdn.length; j++){
plus += cdn[j];
numofints++;
if(plus == cmn[init]){
init++;
}
}
}
System.out.print(numofints);
in which m2 is the size of cmn, which is 3 in this case. Note that my program starts to loop from the beginning of cdn over and over again, because j = 0. I want it to start where it ended the previous time!
I hope you have a solution for me.
Bjorn
just pull j out of the outer loop, and use a while, instead of for, for the inner loop
and you also need to put plus = 0 into the loop
public class T {
public static void main(String[] args) {
int[] cdn = {1,1,1,1,1,1,2,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
int[] cmn = {8,8,16};
int numofints = 0;
int init = 0;
int m2 = 3;
int j = 0;
while(init < m2){
int plus = 0;
while(j < cdn.length){
plus += cdn[j];
j++;
numofints++;
if(plus == cmn[init]){
init++;
System.out.println(j);
break;
}
}
if (j == cdn.length) break;
}
}
}
Shoudln't if(plus == cmn[init]){ be if(plus >= cmn[init])? If you change cdn at all and "plus" happens to go over "cmn[init]", your code is going to break.

I can't figure out how to reset a loop (see example)

I need to write a method that accepts two ints as arguments, a min and a max. On the first line i need to print all numbers in that range (inclusive). On the next line I start with min+1, print all numbers up to max, and then go back to the front of the range and print min. Next line I start with min+2, and so on until I have repeated this starting with each number in the range.Very hard to explain, here's two examples: Say I pass 1 and 5 as the min and max arguments. I want the method to print this:
12345
23451
34512
45123
51234
Or if 3 and 9 were passed, I would expect this:
3456789
4567893
5678934
6789345
7893456
8934567
9345678
I've tried all kinds of things, I'm sure there is an easy way to do this that I am not realizing. I'm supposed to do this without arrays or arrayLists. I think I have a good base to work with, but I just can't figure out where to go from here. My base code prints this:
12345
2345
345
45
5
And this:
3456789
456789
56789
6789
789
89
9
I'm stumped. Here's my code:
public void printSquare(int min, int max){
for (int i=min; i<=max; i++){
for (int j=i; j<=max; j++){
System.out.print(j);
}
System.out.println();
}
}
You should think about how many values you want on each row, and then determine what those values should be. Its hard to make it any clearer without giving you the solution.
Let us know how you go.
Peter is right, and IMO is answering a homework question in the right manner. You know how many elements you want on each line, so you need an outer loop that gives you that many elements, this will stop you from getting the cascading behavior you're seeing now.
At that point you need to think about your inner loop(s), and you'll probably find this easiest using the modulus operator (%). This will allow you to iterate without ever going over your target.
You should be able to figure it out from there, and you're much better off figuring out the algorithm yourself than copying it from someone else, at least at this level of development. Good Luck!
Think about a way to print the missing numbers. The answer is below, if you cannot come up with it you can check it.
This should also print the missing parts:
public void printSquare(int min, int max){
for (int i=min; i<=max; i++){
for (int j=i; j<=max; j++){
System.out.print(j);
}
for (int k=0; k<i-min; k++){
System.out.print(min+k);
}
System.out.println();
}
}
I didn't run this one but it might work:
public void printSquare(int min, int max){
int dif = max - min;
for (int i=min; i<=max; i++){
for (int j=i; j <= i+dif ; j++){
int temp = j;
if ( temp > max ) temp = temp - max;
System.out.print(temp);
}
System.out.println();
}
}
try and just shift an array like so:
static void Main(string[] args)
{
// this will work equally well with numbers letters or other types of characters
int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
String a = "hello";
for (int i = 0; i < nums.Length; i++)
{
int j = 5;
int num = i;
while (j-- > 0)
{
if (num >= nums.Length)
{
num = 0;
}
// shift the loop
Console.Write(nums[num++]);
}
Console.WriteLine();
}
}
public class Test1{
public void printSquare(int min, int max){
for (int i=min; i<=max; i++){
for (int j=i; j<=max; j++){
System.out.print(j);
}
for(int k= min; k<i; k++){
System.out.print(k);
}
//System.out.print(i-1);
System.out.println();
}
}
public static void main(String[] args){
Test1 t = new Test1();
t.printSquare(1,5);
}
}
This is a very simple implementation. Hope this helps!
int n = max-min+1;
for (int i=0 ; i<n; i++){
for (int j=0; j<n; j++)
cout<<min + (i+j)%n;
cout<<"\n";
}
Output:
min = 3 | max = 9
3456789
4567893
5678934
6789345
7893456
8934567
9345678
Here's the code..
for i = 0 to max-min
for j = 0 to max-min
print min + (i+j)%n

Categories