Reputation: 99
I've been searching around for an answer and I've always found things that have partially answered my issue. So, this is my code for now:
import java.util.Scanner;
public class VelikaDN {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter numbers: ");
int[] array = new int[100];
for (int i = 0; i < array.length; i++) {
array[i] = input.nextInt();
// Number of elements
int counter = 0;
for (int j = 0; j < array.length; j++) {
if (array[j] != 0)
counter++;
}
System.out.println("This array has " + counter + " numbers.");
}
}
}
It works but at the end I've noticed something that wasn't so minor as I thought it was. This is the output: https://i.sstatic.net/N5nsO.png I've tried to reposition the print all over the code, tried to somehow stop the loop but I failed. I'm really not even sure anymore what is the issue. I tried to let go of this issue and do another task but as I've already said, anything outside the loop is not showing up.
I'm sorry if this is confusing, I'm new at Java and I'm also pretty bad at explaining. If you have some tips or an alternate solution, feel free to just toss it in here. If there is something else I need to explain, then just say so.
Upvotes: 0
Views: 50
Reputation: 694
I dont see the point of using 2 nested for loops (or 2 separate loops), its just making the algorithm complexity O(n^2) You can check if the value is 0 in the first loop and if its not incremet the value of the counter
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter numbers: ");
int[] array = new int[2];
int counter = 0;
for (int i = 0; i < array.length; i++) {
array[i] = input.nextInt();
if(array[i] != 0) {
counter++;
}
}
System.out.println("This array has " + counter + " numbers.");
}
EDIT
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter numbers: ");
int[] array = new int[100];
int i = 0;
for (; i < array.length; i++) {
int inputValue = input.nextInt();
if(inputValue <= 0) {
break;
} else {
array[i] = inputValue;
}
}
System.out.println("This array has " + i + " numbers.");
}
EDIT 2 (Credit @Andreas)
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter numbers: ");
int[] array = new int[100];
int i = 0;
while (input.hasNextInt()) {
int inputValue = input.nextInt();
array[i++] = inputValue;
}
System.out.println("This array has " + i + " numbers.");
}
Upvotes: 0
Reputation: 164
Put int counter=0;
outside the loop and then post the system.out after the loop
Upvotes: 1