Duplicate even number from first array into another array - java

I have an issue where it seems like when I try to display my new array full of even numbers from the first array, it only outputs the last value? I don't see where the problem lies within the nested for loop inside my GetEven method?
package allevenproj;
import java.util.*;
public class AllEvenProj {
static int Read(int[] arr) {
Scanner scan = new Scanner(System.in);
int count = 0;
for (int i = 0; i < arr.length; i++) {
System.out.printf("Enter arr[%d]: ", i);
arr[i] = scan.nextInt();
if (arr[i] % 2 == 0) {
count++;
}
}
System.out.printf("There are %d even numbers\n", count);
return count;
}
static int[] GetEven(int[] arr, int count) {
int[] evenArr = new int[count];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < count; j++) {
if (arr[i] % 2 == 0) {
evenArr[j] = arr[i];
}
}
}
return evenArr;
}
static void Print(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter size of array: ");
int n = scan.nextInt();
int[] arr = new int[n];
int a = Read(arr);
Print(GetEven(arr, a));
}
}

You'are getting only the last value because due to the inner for loop in the GetEven method: every time you do a full inner loop (you do it for every number in arr) you rewrite the whole evenArr.
So the fix is removing the inner loop:
static int[] getEven(int[] arr, int count) {
int[] evenArr = new int[count];
int j = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
evenArr[j++] = arr[i];
}
}
return evenArr;
}
By the way, methods name should be lowercase. Naming conventions

As Ruben said the problem is in your loop. I took the liberty to refactor your code a bit just to show you a better approach to the problem
package allevenproj;
import java.util.*;
public class AllEvenProj {
static int[] read(int size) {
Scanner scan = new Scanner(System.in);
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
System.out.printf("Enter arr[%d]: ", i);
arr[i] = scan.nextInt();
}
return arr;
}
static void print(int[] arr) {
System.out.printf("There are %d even numbers\n", arr.length);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter size of array: ");
int size = scan.nextInt();
print(Arrays.stream(read(size)).filter(x -> x % 2 == 0).toArray());
}
}

Related

What changes are to be made to run this code?

package com.company;
import java.util.*;
public class Main {
public static int Largest(int array[]) {
int largest = Integer.MIN_VALUE;
for (int i = 0; i <= 5; i++) {
if (array[i] > largest) {
array[i] = largest;
}
System.out.println(largest);
}
return largest;
}
public static void main(String[] args) {
// write your code here
Scanner sc = new Scanner(System.in);
int array[] = new int[5];
for (int i = 0; i <= 5; i++) {
array[i] = sc.nextInt();
System.out.println(array[i]);
}
Largest(array);
System.out.println("largest element is : "+Largest(array));
}
}
This is the code to find the largest no. in an array but the output I'm getting for this code isn't desirable. Please check and let me know the problems in this code.
public static int Largest(int array[]) {
int largest = Integer.MIN_VALUE;
//for (int i = 0; i <= 5; i++) {
//wrong loop range
for (int i = 0; i < array.length; i++) {
if (array[i] > largest) {
//array[i] = largest;
//wrong assignment
largest = array[i];
}
System.out.println(largest);
}
return largest;
}
Try like this :
package com.company;
import java.util.*;
public class Main {
public static int Largest(int array[]) {
int largest = Integer.MIN_VALUE;
for (int i = 0; i < 5; i++) {
if (array[i] > largest) {
largest = array[i];
}
System.out.println(largest);
}
return largest;
}
public static void main(String[] args) {
// write your code here
Scanner sc = new Scanner(System.in);
int array[] = new int[5];
for (int i = 0; i < 5; i++) {
array[i] = sc.nextInt();
System.out.println(array[i]);
}
Largest(array);
System.out.println("largest element is : "+Largest(array));
}
}
You are wrong on two thing :
the loops on your array go until index = 5, however your array has a length of 5, so the last index is 4.
you were assigning array[i] = largest instead of largest = array[i]

How many times a number occurs

I need to write a program that reads an array of ints and an integer number n. The program must check how many times n occurs in the array.
Input:
The first line contains the size of the input array.
The second line contains elements of the array separated by spaces.
The third line contains n.
Output:
The result is only a single non-negative integer number.
My code:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int len = scanner.nextInt();
int[] array = new int[len];
int n = scanner.nextInt();
for (int i = 0; i < len; i++){
array[i] = scanner.nextInt();
}
int counter = 0;
for (int i = 0; i < len; i++) {
if (array[i] == n) {
counter++;
}
}
System.out.println(counter);
}
}
Test input:
6
1 2 3 4 2 1
2
My result: 1
My question is why int n = scanner.nextInt();read "1". It should "2".
Reading the n variable was in the wrong place. The solution:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int len = scanner.nextInt();
int[] array = new int[len];
for (int i = 0; i < len; i++){
array[i] = scanner.nextInt();
}
int counter = 0;
int n = scanner.nextInt();
for (int i = 0; i < len; i++) {
if (array[i] == n) {
counter++;
}
}
System.out.println(counter);
}
}
You should read n after you read the array like so:
Scanner scanner = new Scanner(System.in);
int len = scanner.nextInt();
int[] array = new int[len];
for (int i = 0; i < len; i++){
array[i] = scanner.nextInt();
}
int n = scanner.nextInt();
int counter = 0;
for (int i = 0; i < len; i++) {
if (array[i] == n) {
counter++;
}
}
System.out.println(counter);

Array index out of bounds exception in java code

I am writing the code to print a matrix on taking user input in the form of n value:
Suppose if,
n= 3
output:
3 3 3
3 0 3
3 1 3
3 2 3
3 3 3
I am getting ArrayIndexOutOfBoundException in the line: a[i][j]=n;
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Scanner scan = new Scanner(System.in);
//System.out.println("Enter n");
int n = scan.nextInt();
System.out.println(n);
int a[][]= new int[n][n];
int b=0;
int mid = n/2 +1;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i+j==mid)
{
a[i][j]=n-b;
b++;
}
else
{
a[i][j]=n;
}
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(a[i][j]);
}
System.out.println();
}
}
}
If a request for a negative or an index greater than or equal to size of array is made, then the JAVA throws a ArrayIndexOutOfBounds Exception. This is unlike C/C++ where no index of bound check is done. TheArrayIndexOutOfBoundsException is aRuntime Exception thrown only at runtime.
Look at this line:
for(int j=0;i<n;j++)
you increment while "i < n" but you increment "j++".
When your j reaches value 3, the inner loop continues, but exceeds the array-length (of 3, because the hightest array-index is actually 2).
(Also on a minor sidenote, it is usually preferrable to write ++i or ++j within for-loop increments. This is not a rule, just easier to read for most oldscool c-Devs). Also consider leaving spaces to inprove readability:
import java.util.*;
public class HelloWorld {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// System.out.println("Enter n");
int n = scan.nextInt();
System.out.println(n);
int a[][] = new int[n][n];
int b = 0;
int mid = n / 2 + 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i + j == mid) {
a[i][j] = n - b;
b++;
} else {
a[i][j] = n;
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j]);
}
System.out.println();
}
}
minor correction in a loop
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Scanner scan = new Scanner(System.in);
//System.out.println("Enter n");
int n = scan.nextInt();
System.out.println(n);
int a[][]= new int[n][n];
int b=0;
int mid = n/2 +1;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++) //minor correction here
{
if(i+j==mid)
{
a[i][j]=n-b;
b++;
}
else
{
a[i][j]=n;
}
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(a[i][j]);
}
System.out.println();
}
}
}

Java program asking for 10 numbers and puts them in an array. How do I ask for input? Is my code correct so far?

This program asks for the user to input 10 numbers and is converted into an int array. If the array is lucky (contains the numbers 7, 13, or 18) then it prints out the sum of all the numbers in the array. If it does not contain those then it is false and it only prints the sum of all the even numbers.
How do I correctly ask for this input? How do I get the sum of the even numbers in the array? Is any of the other code incorrect?
import java.util.Scanner;
public class FunArrays {
public static void main(String[] args) {
// until you do user input, you should test your methods using "test" as the input.
int[] test = {1,2,3,4,5,6,7};
luckyNumber1 = {7};
luckyNumber2 = {13};
luckyNumber3 = {18};
int[] a=new int[9];
Scanner sc=new Scanner(System.in);
System.out.println("Please enter numbers...");
for(int j=0;j==9;j++)
a[j]=sc.nextInt();
}
public static int sum(int [ ] value) {
int i, total = 0;
for(i=0; i<10; i++)
{
total = total + value[ i ];
}
return (total);
}
public static int sumOfEvens (
public static boolean isLucky (int[] array) {
if ( (int == luckyNumber1) || (int == luckyNumber2) || (int == luckyNumber3 )
return true;
else
return false
}
// write the static methods isLucky, sum, and sumOfEvens
}
You have an array of size 9. Instead it should be of size 10. So, Change the initialization to
int[] a=new int[10];
Use modulo operator % or remainder operator in Java to find out even or odd numbers.
int evenSum = 0;
for(int j=0;j<a.length;j++){
if(a[j]%2 == 0){
//even numbers
evenSum = evenSum + a[j];
}else{
//odd numbers
}
}
return evenSum;
int[] a=new int[9];
Scanner sc=new Scanner(System.in);
System.out.println("Please enter numbers...");
for(int j=0;j==9;j++)
a[j]=sc.nextInt();
}
There's something wrong with your loop, it should be
for (int j = 0; j < 9; j++)
With this fix it should correctly prompt the users for 9 numbers. Change to 10 for the array and the loop it would takes in 10 number.
Sum of evens
static int sumOfEvens(int array[]) {
int sum = 0;
for(int i = 0; i < array.length; i++>) {
if(array[i] % 2 == 0)
sum += array[i];
}
return sum;
}
Input
for(int j = 0; j < a.length; j++)
a[j] = sc.nextInt();
import java.util.Scanner;
public class MyMain1 {
public static void main(String[] args) {
// until you do user input, you should test your methods using "test" as
// the input.
int[] luckyNumbers = { 7, 13, 18 };
int[] a = new int[10];
Scanner sc = new Scanner(System.in);
System.out.println("Please enter numbers...");
for (int j = 0; j <= 9; j++) {
a[j] = sc.nextInt();
}
sc.close();
boolean sumAll = false;
for (int i : a) {
for (int j : luckyNumbers) {
if (i == j) {
sumAll = true;
break;
}
}
if(sumAll) {
break;
}
}
if (sumAll) {
System.out.println("Summing all : " + sumAll(a));
} else {
System.out.println("Summing Only Even : " + sumEven(a));
}
}
public static int sumAll(int[] value) {
int total = 0;
for (int j : value) {
total = total + j;
}
return total;
}
public static int sumEven(int[] value) {
int total = 0;
for (int j : value) {
if (j % 2 == 0) {
total = total + j;
}
}
return total;
}
}

How to make Bubble Sort in Java to output the sorted numbers?

This is my code for the Bubble Sort. I cannot get the actual sorted values to output. The program reads the inputted numbers, but does not print it sorted.
I'm not sure what I have to do to make them sort.
Any advice or suggestions would be helpful.
package sortingalgorithm2;
import java.util.Scanner;
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Scanner read = new Scanner (System.in);
int[] num = new int[15];
int size = 15;
System.out.println("Enter 15 numbers: ");
for (int i=0; i <= size-1; i++)
{
num[i] = read.nextInt();
}
for (int i=0; i <= size-1; i++)
{
if (num[i] >=1 && num[i] <= 1000)
{
System.out.println("The numbers you entered are: ");
System.out.println(+num[0]);
System.out.println(+num[1]);
System.out.println(+num[2]);
System.out.println(+num[3]);
System.out.println(+num[4]);
System.out.println(+num[5]);
System.out.println(+num[6]);
System.out.println(+num[7]);
System.out.println(+num[8]);
System.out.println(+num[9]);
System.out.println(+num[10]);
System.out.println(+num[11]);
System.out.println(+num[12]);
System.out.println(+num[13]);
System.out.println(+num[14]);
}
else
{
System.out.println("Data input is invalid. Enter a number between "
+
"1 and 1000.");
break;
}
}
BubbleSort (num);
for (int i=0; i < num.length; i++)
{
System.out.println("The sorted numbers are: ");
System.out.print(num[i]+ " ");
}
}
private static void BubbleSort(int[] num)
{
for (int i=0; i <= num.length; i++)
for (int x=1; x <= num.length; x++)
if (num[x] > num[x+1])
{
int temp = num[x];
num[x] = num[x+1];
num[x+1] = temp;
}
}
}
Try this Bubble sort :
private static void BubbleSort(int[] num) {
for (int i = 0; i < num.length; i++) {
for (int x = 1; x < num.length - i; x++) {
if (num[x - 1] > num[x]) {
int temp = num[x - 1];
num[x - 1] = num[x];
num[x] = temp;
}
}
}
}
You are printing the actual numbers in the order the user entered. Try this instead:
int[] sortedNumbers = new int[15];
sortedNumbers = BubbleSort (num);
for (int i=0; i < sortedNumbers.length; i++)
{
System.out.println("The sorted numbers are: ");
System.out.print(sortedNumbers[i]+ " ");
}
public static int[] BubbleSort(int [] num)
{
int temp;
for (int i=1; i<num.length; i++)
{
for(int j=0; j<num.length-i; j++)
{
if (num[j] > num [j+1])
{
temp = num [j];
num [j] = num [j+1];
num [j+1] = temp;
}
}
}
return num;
}
Try this :
for (int i = 0; i < num.length; i++) {
for (int j = i + 1; j < num.length; j++) {
if (num[i] > num[j]) {
num[i] = num[i] + num[j] - (num[j] = num[i]);
}
}
}
you are passing the array variable num (which is not static) to BubbleSort()(which does not returns a value and shadows the global num variable with its own) and trying to use the same num variable to access your sorted array from your main method which is not right.
The genuine fix to this is to declare your variable num as static just before the main method( in the class declaration). So I have made the changes in the program and here is the solution.
import java.util.Scanner;
public class sol {
static int num [] =new int [15]; //declaring num as static in the class definition.
public static void main(String[] args)
{
Scanner read = new Scanner (System.in);
int size = 15;
System.out.println("Enter 15 numbers: ");
for (int i=0; i <= size-1; i++)
{
num[i] = read.nextInt();
}
read.close();
/*for (int i=0; i <= size-1; i++)
{
if (num[i] >=1 && num[i] <= 1000)
{
System.out.println("The numbers you entered are: ");
System.out.println(+num[0]);
System.out.println(+num[1]);
System.out.println(+num[2]);
System.out.println(+num[3]);
System.out.println(+num[4]);
System.out.println(+num[5]);
System.out.println(+num[6]);
System.out.println(+num[7]);
System.out.println(+num[8]);
System.out.println(+num[9]);
System.out.println(+num[10]);
System.out.println(+num[11]);
System.out.println(+num[12]);
System.out.println(+num[13]);
System.out.println(+num[14]);
}
else
{
System.out.println("Data input is invalid. Enter a number between "
+
"1 and 1000.");
break;
}
}*/ //I have disabled this just to check with the sort method.
BubbleSort ();//no need to pass the array as it is static and declared as a //class variable hence can be used to by all the methods of that class
System.out.println("The sorted numbers are: ");
for (int i=0; i < num.length; i++)
{
System.out.print(num[i]+ " ");
}
}
private static void BubbleSort()
{
for (int i=0; i < num.length; i++)// required changes in the looping
for (int x=0; x < num.length-i-1; x++)
if (num[x] > num[x+1])
{
int temp = num[x];
num[x] = num[x+1];
num[x+1] = temp;
}
}
}

Categories

Resources