In a given array K (13), find the amount of elements located in front of the last zero element.
The values of the array elements set in the range [-8.23].
withdraw the number of the last zero element and the amount.
Import java.util.arrays;
// Creating a class MASS2
Public Class Mass2 {
Public Static Void Main (String [] Args)
{
// Creating an array for 13 digits
int [] z;
Z = new int [13];
For (int i = 0; i & lt; z.length; i ++) {
// Creating an array on 13 random numbers in the range [-8,23]
Z [i] = -8 + (int) (math.random () * 24)
// Conclusion of the input array with retreat "" between the elements of the array
System.Out.print (+ z [i] + ");
}
System.Out.printLN ();
int sum = 0;
int sum = 0
for (int i = 0; i & lt; z.length; i ++)
{
IF (z [i] == 0)
{
Sum = Sum;
}
ELSE.
{
SUM + = Z [i];
}
}
System.out.PrintLN ("Sum:" + SUM)
}
}
Answer 1
// Creating a class MASS2
Public Class Mass2 {
Public Static Void Main (String [] Args) {
// Creating an array for 13 digits
int [] z;
z = new int [13];
For (int i = 0; i & lt; z.length; i ++) {
// Creating an array on 13 random numbers in the range [-8,23]
z [i] = -8 + (int) (math.random () * 24);
// Conclusion of the input array with retreat "" between the elements of the array
System.out.print (z [i] + ");
}
int sum = 0;
int index = 0;
INT RESULT = 0;
For (int i = 0; i & lt; z.length; i ++) {
SUM + = Z [i];
if (z [i] == 0) {
result = Sum;
index = i;
}
}
if (result == 0) {
result = Sum;
}
System.Out.printLN ();
System.out.PrintLN ("Amount:" + Result + "Index:" + Index);
}
}
Option with the fact that there may be more than one zero element.
Answer 2
Do not you think that for such a simple task you have too much code?
Here is a realization to generate an array and calculation of the amount of elements, and write the search index of the last zero element yourself (it is too simple).
import java.util.arrays;
Public Class Mass2 {
Public Static Void Main (String [] Args) {
int [] randomarray = new java.util.random (). INTS (13, -8, 23) .toarray ();
System.out.PrintLN (Arrays.Tostring (Randomarray));
System.out.PrintLN ("Sum:" + ArrayS.Stream (Randomarray) .sum ());
}
}
Answer 3
int [] z;
Z = new int [13];
For (int i = 0; i & lt; z.length; i ++) {
Z [i] = -8 + (int) (math.random () * 24);
System.Out.print (+ z [i] + ");
}
System.Out.printLN ();
int lastnonzeroindex = 0;
int sum = 0;
for (int i = 0; i & lt; z.length; i ++)
{
IF (z [i] == 0)
{
If (I & GT; 0) {
Lastnonzeroindex = i-1; // remember Indince
} else {
Lastnonzeroindex = 0; // The first element is zero!
}
Break; // Immediately complete the cycle in order not to touch the subsequent elements
}
ELSE.
{
SUM + = Z [i];
}
}
System.out.printLN ("Amount:" + SUM);
System.out.PrintLN ("Index not zero element:" + LastnonzeroIndex);