How to check if certain numbers appear in an array? - java

I'm relatively new to java. I'm trying to find if numbers from 0 - 4 are stored
somewhere in an array of size 5. The array is populated by the user entering integers between 0-4. I have successfully managed to get it to confirm that the first number entered by the user is in the array however, the numbers after that not appearing.
So for example: If the user enters the numbers 2,2,2,1,3 I will get only 2 appears in the array as a result.
public static void checkEachNumber(int[] array)
{
int currentNum = 0;
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array.length; j++)
{
currentNum = i;
if(currentNum == array[j])
{
System.out.println(currentNum + " appears in the array");
break;
}
else
{
System.out.println(currentNum + " doesn't appear in the array");
break;
}
}
}
}

To resolve your problem you should simply remove the have used in the else part of the array.
Consider a case like this
ex. 2 1 4 3
when checking for i=1 it will first compare the value with 2 so it will come out of the loop.
public static void checkEachNumber(int[] array)
{
int currentNum = 0;
for(int i = 0; i < array.length; i++)
{
int flag=0;
for(int j = 0; j < array.length; j++)
{
currentNum = i;
if(currentNum == array[j])
{
System.out.println(currentNum + " appears in the array");
flag=1;
break;
}
}
if(flag==0)
{
System.out.println("currentNum+"Doesn't appear in array");
}
}
}

When you execute a break statement, the loop stops running completely. In general, the way to scan for a match is going to look like this:
found_match = no
for (... in ...) {
if (match) {
found_match = yes
break
}
}
if (found_match) {
do_found_match_stuff();
}

Related

Why this error of sorting occuring only in cases of >5 table elements?

please see my code for BubbleSorting. When I choose 5 or more numbers for my table to be sorted I get an error:
at first.firstt.sorting_v2.sorting(sorting_v2.java:35).
Completely do not know why it occured, when I choose 2 or three element to sort it works perfect.
I know it can be made different way, this type of sorting but please show me what I did wrong as still learn and I'm very curious about the details of this error hmm.
Also see the image below:enter image description here
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Choose how much number you want to sort:");
int sizeOfTab = scanner.nextInt();
int[] numbers = new int[sizeOfTab];
for (int i = 0; i < sizeOfTab; i++) {
System.out.println("Choose number to collection: ");
numbers[i] = scanner.nextInt();
}
scanner.close();
System.out.println(Arrays.toString(sorting(numbers)));
}
private static int[] sorting(int[] numbers) {
boolean notDone = false;
for (int i = 0; i < numbers.length - 1; i++) {
for (int j = 1; j < numbers.length; j++) {
if (numbers[i] > numbers[j]) {
int tmp = numbers[j];
numbers[j] = numbers[i];
numbers[i] = tmp;
notDone = true;
}
}
}
return notDone ? sorting(numbers) : numbers;
}
}
Your logical error is that you are always restarting your second inner loop from j = 1 aka the second element in
for (int j = 1; j < numbers.length; j++) { ... }
You only ever want to compare numbers[i] > numbers[j] for cases where j is greater than i.
Lets say you have the array [1, 2, 3, 4]
Currently your loop will run and reach a point where it will check numbers[2] > numbers[1] and switch the second and third element despite the array already being sorted.
To fix this simply always have your second loop start from the current value of i with 1 added:
for (int j = i+1; j < numbers.length; j++) { ... }

Receiving an error: variable i is already defined in method main

I am trying to write a program that:
1) asks for user input to create an array of 10 elements
2) checks to make sure the elements are distinct
3) identifies the highest value among the elements.
I think Im close but I keep receiving this error message:
error: variable i is already defined in method main(String[])
for (int i = 0; i < myList.length; i++) {
Here is my full code:
import java.util.Scanner;
public class max101 {
public static void main(String[] args) {
double[] myList = new double[10];
double max = myList[0];
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter " + myList.length + " distinct numbers: ");
for (int i = 0; i < myList.length; i++)
myList[i] = input.nextDouble ();
for(int i = 0; i <myList.length; i++) {
for(int j = i+1; j<myList.length; j++) {
if(myList[i] == (myList[j])); {
System.out.println("Numbers are not distinct. Please try again and enter 10 distinct numbers");
}
if(myList[i] != (myList[j])); {
for (int i = 0; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
System.out.println("The maximum value is " + max);
}
}
}
}
}
}
Try using different variable names in your loops
If you dont want to do the above dont reinitialize the variable with int just put i = 0
It might also be useful to look into how scope works.
My suspicion is you’re not ending your blocks properly — a block meaning from { to }. When I have my IDE indent your code, it is:
for (int i = 0; i < myList.length; i++)
myList[i] = input.nextDouble();
for (int i = 0; i < myList.length; i++) {
for (int j = i + 1; j < myList.length; j++) {
if (myList[i] == (myList[j]))
;
{
System.out.println("Numbers are not distinct. Please try again and enter 10 distinct numbers");
}
if (myList[i] != (myList[j]))
;
{
for (int i = 0; i < myList.length; i++) {
if (myList[i] > max)
max = myList[i];
System.out.println("The maximum value is " + max);
}
}
}
}
I think you see now that i is declared inside a for loop that already declares i. Also once you’ve detected a duplicate I think you should break out of the two loops rather than checking for more duplicates, and not find a max until the user has entered 10 new numbers.
One more tip, don’t put a semicolon after your if ( … ), it breaks your logic.

Java 2d array counts zeros in column

I start learning programming about 4 days ago by myself and iam a lil bit stuck with 2d arrays. I try to challenging myself with tasks, like get from 2d array column with most zeros or atleast just count zeros, so far i get this far
public class b {
public static void main(String[] args) {
int a[][] = new int [5][5];
int i,j;
int s = 0;
for(i= 0;i<a.length; i++)
for(j = 0; j<a[i].length; j++){
a[i][j] = (int)(Math.random()*10);
}
for(i=0;i<a.length;i++){
for(j=0;j<a[i].length;j++) {
System.out.print(a[i][j] + "\t");
}
System.out.println();
}
for(j=0;j<a[0].length;j++) {
for(i=0;i<a.length;i++) {
if(a[i][j] >-1 || a[i][j]<1) {
s++;
System.out.println(s +"\t");
s = 0;
}
}
}
}
}
Can somebody explain me why result is always 1 and why it counts columns and rows in one row?
Suppose the condition enters into if(a[i][j] >-1 || a[i][j]<1) then you increase s by 1 then print it which gives 1 then you reassign it to s=0 so it gives same 1 each time.So remove the s=0 and place the printing line after end of loop
public class b {
public static void main(String[] args) {
int a[][] = new int [5][5];
int i,j;
int s = 0;
for(i= 0;i<a.length; i++)
for(j = 0; j<a[i].length; j++){
a[i][j] = (int)(Math.random()*10);
}
for(i=0;i<a.length;i++){
for(j=0;j<a[i].length;j++)
System.out.print(a[i][j] + "\t");
System.out.println();
}
for(j=0;j<a[0].length;j++){
for(i=0;i<a.length;i++)
if(a[i][j] >-1 && a[i][j]<1){
s++;
}
System.out.println("Zero in column no. "+j+" is "+s +"\t");
s=0;
}
}
}
Demo
Result will be 1 because you're re-assigning 0 to s everytime. But the issue is not only that.
Firstly your condition is using wrong indices. Instead of a[i][j] you should use a[j][i] as you're traversing column-wise. Secondly:
if(a[j][i] >-1 || a[j][i]<1){
can be simply written as:
if(a[j][i] == 0) {
So the structure is the outer for loop will iterate over each column number. And for each column number, inner for loop will find count of 0. You've to maintain a max variable outside both the loops, to track the current max. Also, you've to use another variable inside the outer for loop to store the count for current column.
Everytime the inner for loop ends, check if current column count is greater than max. If yes, reset max.
int max = 0;
for(j=0;j<a[0].length;j++){
int currentColumnCount = 0;
for(i=0;i<a.length;i++) {
if(a[j][i] == 0) {
currentColumnCount++;
}
}
if (currentColumnCount > max) {
max = currentColumnCount;
}
}

Numerically listing Arrays

So my code is having a problem. Here's what I want to do: have one array have the original set of numbers (up to 10 numbers) and then copy and paste those numbers onto the second array. And then afterwards, the second area lists those numbers from the first array numerically (going from the lowest number to the highest).
The problem is... my second output is giving me a good output with the lowest numbers going to the highest numbers, however, at the same time, I'm getting a long list of repeated numbers and a ton of zeros if I stop my code with the -9000 input. Can anyone tell me what the problem is and how to fix it? I don't want to sort this second array with the Array.sort() option, by the way. No importing anything but the scanner:
public static void main(String[] args) {
System.out.println("Input up to '10' numbers for current array: ");
int[] array1 = new int[10];
int i;
Scanner scan = new Scanner(System.in);
for (i = 0; i < 10; i++) {
System.out.println("Input a number for " + (i + 1) + ": ");
int input = scan.nextInt();
if (input == -9000) {
break;
} else {
array1[i] = input;
}
}
System.out.println("\n" + "Original Array: ");
for (int j = 0; j < i; j++) {
System.out.println((j + 1) + ": " + array1[j]);
}
System.out.println("\n" + "Organized Array: ");
int[] array2 = new int[i];
for (i = 0; i < array1[i]; i++) {
System.out.println(+array1[i]);
for (int j = 0; j < i; j++) {
int temp;
boolean numerical = false;
while (numerical == false) {
numerical = true;
for (i = 0; i < array1.length - 1; i++) {
if (array2[i] > array2[i + 1]) {
temp = array2[i + 1];
array2[i + 1] = array2[i];
array2[i] = temp;
numerical = false;
}
}
}
}
for (i = 0; i < array2.length; i++) {
System.out.println(array2[i]);
}
}
}
You have several issues that you need to fix to make your program run:
You have forgotten to copy array1 into array2:
The output that you think is coming from sorting array2 is actually from the process of sorting.
int[] array2 = new int[i];
for (int j = 0; j < i; j++) {
array2[j] = array1[j];
}
You placed the output of sorted array inside the loop that does sorting:
Check the level of curly braces, and move the output loop to after the sorting loop
for (i = 0; i < array2.length; i++) {
System.out.println(array2[i]);
}
Your sorting algorithm has an extra loop:
Having the outermost loop makes no sense: your bubblesort algorithm works perfectly without it, so you should remove the loop, and move its body up by one level of nesting:
for (i = 0; i < array1[i]; i++) { // Remove the loop
... // <<== Keep the body
}
Your innermost loop reuses i incorrectly:
Replace loop variable i with another variable, e.g. m
for (int m = 0 ; m < array2.length - 1; m++) {
if (array2[m] > array2[m + 1]) {
temp = array2[m + 1];
array2[m + 1] = array2[m];
array2[m] = temp;
numerical = false;
}
}
Demo.
in your for loop you set i limit to array1[i] value not to array lenght, surely it is wrong.
you are reusing the same index i, inside the other loops of the outer big 'for' loop, so the i value will be messed up by inner loops
you never copied the array1 values to array2

Get equal values within a stack

I'm doing a stack on java that this contains five integers but I have to print out only the values are equal.
Example 1 - 2 - 2 - 3 - 4
The same number is: 2
How can I determine which make the same numbers?
Here is my code:
package e.d_pilas;
import java.util.*;
public class ED_PILAS {
private int stck[];
private int tos;
ED_PILAS(int size){
//New stack
stck = new int[size];
tos = -1;
}
void push(int value) {
stck[++tos] = value;
}
int pop() {
if (tos < 0) {
return 0;
} else
return stck[tos--];
}
public static void main(String[] args) {
int number;
Scanner read = new Scanner (System.in);
System.out.print("Enter five (5) numbers to fill the stack \n");
ED_PILAS stack = new ED_PILAS(5);
for (int i = 1; i < 6; i++){
System.out.print("Enter the value "+i+" to fill the stack \n");
number=read.nextInt();
stack.push(number);
}
System.out.println("Equal values contained in the stack: \n");
for (int j = 1; j < 6; j++){
System.out.println("\t " + stack.pop());
}
}
}
Thank you!
In the first method it will print the duplicates entries only one time. in second method if stack contains more than two entries it will print multiple times.
ArrayList<int> list=new ArrayList<int>();
for (int j = 1; j < 6; j++){
int num=stack.pop();
if(list.contains(num)){
System.out.println(num);
}
else{
list.add(num);
}
}
OR
stack.pop() methods removes the element then use stack.search() method to find duplicates
for (int j = 1; j < 6; j++){
int num=stack.pop();
if(stack.search(num)==1){
System.out.println(num);
}
else{
}
}
While you do pop() from stack you can store in ArrayList<Integer> and check on every pop() if it already exists or not. If it repeats then print it and mark it as printed (so that you donot print it again).
Use this logic it will work for consecutive same values otherwise use ArrayList:
int n=stack.pop();
int dummy;
for (int j = 1; j < 6; j++){
dummy=stack.pop();
if(n==dummy)
{
System.out.println("\t The same number is " + n);
}
else{
n=dummy;
}
Use an ArrayList to store the previous pop'd values. If you see this value again during a pop, simply print the number.
ArrayList<Integer> popdList=new ArrayList<Integer>();
for (int j = 1; j < 6; j++){
int value=stack.pop();
if(popdList.contains(value){
System.out.println(value);
} else{
popdList.add(value);
}
}
More info on ArrayLists
Also, instead of changing your main function you could edit your pop function to only return the duplicate values like this:
ArrayList<Integer> popdList=new ArrayList<Integer>();
int pop() {
if (tos < 0) {
return 0;
} else {
int value = stck[tos--];
if(popdList.contains(value){
return value;
} else{
popdList.add(value);
}
}
}

Categories