(Java) Methods, having issues with displaying even numbers properly - java

Let me start off by saying that I'm fairly new to programming and as such, I've been using references in hopes to better learn Java programming, as trial and error is how I learn best. However, I'm currently stumped and have no idea what to do.
I am trying to get a user to input 5 numbers into an array, and then have the program display the numbers back to the user, including how many are "even" and what numbers they are. For example, if a user were to enter 1, 2, 3, 4, 5. The program would ideally output "1, 2, 3, 4, 5" of which two are even, the even numbers are "2" and "4"
As is, the code executes well, but the resulting "numbers which are even" always results in 0, 0, 0, 0, 0
I would greatly appreciate if anyone was able to provide some assistance or tips on how to improve, thank you.
package PracticeExam1;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
private static Scanner sc;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] numArray = loadArray(scan);
double largeCount = countLarge(numArray);
int i, evenCount = 0;
int [] arr = new int[5];
System.out.println("The array contains: " + Arrays.toString(numArray));
System.out.println(largeCount + " of these values are even numbers.");
evenCount = CountEven(arr, 5);
}
public static int[] loadArray(Scanner sc)
{
// Integer array of size 5
Scanner scnr = new Scanner(System.in);
int[] arr = new int[5];
for(int i = 0; i < arr.length; i++) {
System.out.print("Enter a number to store in the array: ");
arr[i] = (int) scnr.nextDouble();
}
return arr;
}
public static int countLarge(int[] a)
{
int lc = 0;
for(int e : a)
{
if(e % 2 == 0) {
lc++;
}
}
return lc;
}
public static int CountEven(int [] arr, int even)
{
int evenPos,
evenArr = 0;
System.out.print("\n List of Even Numbers in this Array are: ");
for(evenPos = 0; evenPos < arr.length; evenPos++)
{
if(arr[evenPos] % 2 == 0)
{
System.out.print(arr[evenPos] +" ");
evenArr++;
}
}
return evenArr;
}
}

you have never added any number to your evenArr, so it can only print 0,0,0,0,0.
I've made a example how you can do this:
public static int CountEven(int [] arr, int even)
{
int[] evenArr = new int[even];
int evenCnt = 0;
System.out.print("\n List of Even Numbers in this Array are: ");
for(i = 0; i < arr.length; i++)
{
if(arr[i] % 2 == 0)
{
System.out.print(arr[i] +" ");
evenArr[evenCnt] = arr[i];
evenCnt ++;
}
}
return evenArr;
}
Regards
Beni

Related

Program that deletes one integer (or more if there's duplicates) from an array by it's value

I need to write a program, which deletes a number of elements from an int array that are equal to some int value. Eventually I should get an array that isn't bigger than the initial one.
I mustn't use lists or any methods that do the deletion directly.
I tried to do this this way and I can't trace the flaw. I suppose, it should be in the last "for" construction but I'm not sure.
import java.util.Arrays;
import java.util.Scanner;
public class App {
public static void main(String\[\] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Array size: ");
int sizeInput = scan.nextInt();
int[] original = new int[sizeInput];
System.out.print("Array itself: ");
for (int i = 0; i < sizeInput; i++) {
original[i] = scan.nextInt();
}
System.out.println("Number to be deleted: ");
int dNumber = scan.nextInt();
int[] newArr = new int[original.length];
for (int i = 0; i < original.length - 1; i++) {
int sum = 0;
if (original[i] == dNumber) {
newArr[i] = original[i + 1];
sum = sum + 1;
} else if (original[i] != dNumber) {
newArr[i] = original[i + sum];
}
}
System.out.println(Arrays.toString(newArr));
}
}
and here's what I got in my console eventually:
Array size: 5
Array itself: 1 2 3 4 5
Number to be deleted: 2
\[1, 3, 3, 4, 0\]
You see? In the output I get the second "3" for some reason and I also don't get why there's no last element of the initial array.
Please, explain what wrote wrong so that my code doesn't solve the problem. And please explain ho can I solve It. Thanks!
You need a position int for the new array, so you go further only when you set a new value
int[] original = {1, 2, 3, 4, 5};
int dNumber = 2;
int[] newArr = new int[original.length];
int j = 0;
for (int val : original) {
if (val != dNumber) {
newArr[j] = val;
j++;
}
}
newArr = Arrays.copyOf(newArr, j); // truncate
System.out.println(Arrays.toString(newArr));
// [1, 3, 4, 5]

How to count number of even terms which is the sum of consecutive numbers in array. For eg [1,2,2,5,5] , there are 2 pairs whose value result in even

import java.util.*;
public class even{
public static void main(String[] args){
Scanner scn = new Scanner(System.in);
int n1 = scn.nextInt();
int[] a1 = new int[n1];
for(int i=0;i<a1.length;i++){
a1[i] = scn.nextInt();
}
int count = 0;
for(int i=0;i<a1.length;i++){
for(int j=1;j>=i+1;j--){
if((a1[i]+a1[j])%(2)==0){
count++;
}
}
}
System.out.println(count);
}
}
//Code does not provide the desired output
For eg [1,2,2,5,5] , there are 2 pairs whose value result in even.
[2,3,3,1,2] has 2 pairs (3,3 and 3,1). The code is not generating
desired results
If you just want to test for consecutive numbers you can solve it with one loop:
public static void main(String[] args){
int[] input = {1, 2, 2, 5, 5};
int count = 0;
for(int i = 0; i < input.length - 1; i++){
if((input[i] + input[i+1]) % 2 == 0) count++;
}
System.out.println(count);
}
You just have to make sure to only loop til input.length-1 so you don't get an index out of bounds error.

Take array as input from user and output accumulative sum as new array

I can't get this program to work. It's supposed to take an array as input and output a new array with the accumulative sum of the input array. I used a function for this (bottom part).
For example:
Input: 1 2 3 4
Output: 1 3 6 10
Here's my program:
import java.util.Scanner;
public class Accumulate {
public static void main(String[] args) {
int n, sum = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter the size of the array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
}
System.out.println(Arrays.toString(accSum(a)));
s.close();
}
public static int[] accSum(int[] in) {
int[] out = new int[in.length];
int total = 0;
for (int i = 0; i < in.length; i++) {
total += in[i];
out[i] = total;
}
return out;
}
}
Use Arrays.toString() to print an array.
You can't call System.out.println(accSum(a)); directly as that will print the memory address of the array and not the contents. Wrap the call with Arrays.toString(accSum(a)) and it will print the expected output.
PS: The code in your post doesn't compile:
scanner.close(); should be s.close();
accSum() should be static.
Addendum:
So your full code became this:
public static void main(String[] args) {
int n, sum = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter the size of the array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
}
System.out.println(Arrays.toString(accSum(a)));
s.close();
}
public static int[] accSum(int[] in) {
int[] out = new int[in.length];
int total = 0;
for (int i = 0; i < in.length; i++) {
total += in[i];
out[i] = total;
}
return out;
}
You can use Arrays.stream(int[],int,int) method to get the sum of the previous array elements:
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4};
int[] arr2 = accSum(arr1);
System.out.println(Arrays.toString(arr2));
// [1, 3, 6, 10]
}
public static int[] accSum(int[] arr) {
return IntStream
// iterate over the indices of the array
.range(0, arr.length)
// sum of the current element and all previous elements
.map(i -> arr[i] + Arrays.stream(arr, 0, i).sum())
// return an array
.toArray();
}
See also: Modifying a 2D array

Java code to generate comma separated values and sum

While running this code I am getting ArrayIndexOutOfBoundsException.
public class Evensum {
public static void main(String[] args) {
int num = Integer.parseInt(args[0]);
int even[] = new int[num];
int sum = 0,j = 0;
String evennums = "";
//Insert your code here
for(j=0; j<=num; j++) {
if(num%2==0) {
even[j]=num;
sum=sum+num;
args[j]= Integer.toString(num);
}
evennums=String.join(",", args);
}
System.out.println(evennums);
System.out.println(sum);
}
}
for (j=0; j<=num; j++)
This is wrong. It should be:
for (j = 0; j < num; j++)
Why? Assume num is 5. Before this line you initialized even to 5. The indices of even would be 0, 1, 2, 3, 4.
Now, with j<=num, you are trying to access the index 5, which does not exist and hence the exception.
args[j]= Integer.toString(num);
This line will raise another exception. I am assuming you're only passing one parameter from the command line which is args[0]. This means the args array is of size 1 and you cannot add more elements to it.
Also, it is not a good practice to add/modify elements to the args array. You should create a new array for this.
Please find the much simpler version of the Code by avoiding the Integer.toString and String.join to pass on the Arguments. Simple Integer Arraylist and adding the elements to will do the Trick.
package com.umapathy.java.learning.programs;
import java.util.ArrayList;
import java.util.List;
public class EvenSum
{
public static void main(String[] args)
{
int num = 20; //Initialize the user-defined value for the loop execution
int sum = 0 ; //Initialize the Sum Value as 0
List<Integer> evenlist = new ArrayList<Integer>(); //Define an integer
Array list
for (int i=2; i<=num; i++) //Begin the loop from the value of 2
{
if(i%2==0) //Logic to find whether a given number is Even Number or not
{
sum = sum + i; // If the logic returns true, Calculate the Sum Value
evenlist.add(i); // Add the Integer to the previous defined Integer
// Arraylist by calling add method
}
}
System.out.println(evenlist); // Print the Output outside the loops
System.out.println(sum);
}
}
Output Generated as follows:--
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20] 110
package javaApp;
public class EvenSum {
public static void main(String[] args) {
int num = 20;
int even[] = new int[num];
int sum = 0,j = 0;
String evennums = "";
for(j=1; j<=num; j++) {
if(j%2==0) {
sum=sum+j;
evennums=evennums+","+j;
}
}
evennums=evennums.replaceFirst(",","");
System.out.println(evennums);
System.out.println(sum);
}
}
Why initialized the even array size if its actual length is unknown in initially. It's better to go with ArrayList in this case which have characteristic to grow dynamically.
Try in this way
public static void main(String[] args) {
int num = Integer.parseInt(args[0]);
List<Integer> evens = new ArrayList<Integer>();
int sum = 0;
for (int j = 0; j <= num; j++) {
if (j % 2 == 0) {
sum += j;
evens.add(j);
}
}
System.out.println("Even Numbers List : "+evens);
System.out.println("Total Sum : "+sum);
// If you want an array of int instead of ArrayList you can convert ArrayList into int[] with following two lines
int evenArray[] = even.stream().mapToInt(x->x).toArray();
System.out.println("Even Numbers Array : "+evenArray);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//System.out.println("Args: "+args[0]);
int num = Integer.parseInt(args[0]);
int even[] = new int[num];
int sum = 0,j = 0;
String evennums = "";
//Insert your code here
for(j=0; j<=num; j++) {
if(j%2==0) {
//even[j]=num;
sum=sum+j;
if(j!=0) evennums=evennums+","+j;
}
}
evennums=evennums.substring(1);
System.out.println(evennums);
System.out.println(sum);
}
At time of running in eclipse follow below steps:
Right click on class--> Run AS --> Run Configuration
Go to Arguments tab and pass value as 10
Click Run
Output:
2,4,6,8,10
30

Find the minimum number of operations after which P becomes an identity permutation

Consider a Permutation P of length n .
Let us define an operation on P as follows:
P[i]=P[P[i]]; for every i from 1 to n
for example:
P[n] = {2, 3, 1};
After 1 operation:
P[1] becomes P[P[1]] = P[2]= 3;
P[2] becomes P[P[2]] = P[3]= 1;
P[3] becomes P[P[3]] = P[1]= 2;
So, P becomes [3, 1, 2] ;
You need to find the minimum number of operations to be performed after which P becomes an Identity Permutation.
Output -1 if not possible.
Input 1:
P = [2 , 1];
Output 1:
1
As it will become Identity Permutation after 1 operation only.
Input 2:
P = [2 , 3 , 1];
Output 2:
-1
As Identity Permutation is not possible by the given operation.
I've tried to solve this code as follows, but I'm not getting the right way to solve it.
Java:
import java.util.Scanner;
public class Permutation {
public static void main(String args[]) throws Exception {
Scanner s = new Scanner(System. in );
System.out.println("Enter the number of Test Cases");
int t = s.nextInt();
for (int i = 0; i < t; i++) {
System.out.println("Enter the number n");
int n = s.nextInt();
int[] arr = new int[n + 1];
for (i = 1; i <= n; i++) {
arr[i] = s.nextInt();
}
int count = 0;
int[] arr1 = new int[n + 1];``
arr1 = arr;
do {
for (i = 1; i <= n; i++) {
arr1[i] = arr1[arr1[i]];
}
count++;
}
while ( arr != arr1 );
System.out.println(count);
}
}
}
In this code,I loop until n! tries or when find the permutation.If check is true,then I found and can write the count,if count reaches the n! which means all permutations are done and I couldn't find the identity permutation and I write -1.Loop boundary is like that.Let's look at the algorithm.
I copied orijinal array to another array to don't lose any information.And after each iteration when array is changed,I also kept it.
After arr1[i] = arr[arr[i]];,I sorted the arr1 and check whether sorted arr1 is equal previous arr1 or not,if they are equals then I found the permutation,break the loop make check boolean true and print result,else iterate one more time.
import java.util.Arrays;
import java.util.Scanner;
public class Permutation {
public static void main(String args[] ) throws Exception {
Scanner s = new Scanner(System.in);
System.out.println("Enter the number of Test Cases");
int t = s.nextInt();
for(int i=0;i<t;i++)
{
System.out.println("Enter the number n");
int n = s.nextInt();
int[] arr=new int[n+1];
for(i=1;i<=n;i++){
arr[i]=s.nextInt();
}
int count=0;
int[] arr1=new int[n+1];
arr1 = Arrays.copyOf(arr, arr.length);
boolean check;
do {
for (i = 1; i <= n; i++) {
arr1[i] = arr[arr[i]];
}
arr = Arrays.copyOf(arr1, arr1.length);
count++;
int [] temp = Arrays.copyOf(arr1, arr1.length);
Arrays.sort(arr1);
check = false;
for(int m =1;m<=n;m++){
if(arr1[m]==temp[m])
check = true;
else{
check = false;
break;
}
}
}
while(count<fact(n) && check!=true);
if(count == fact(n))
System.out.println("-1");
else
System.out.println(count);
}
}
public static int fact(int n){
int temp = 1;
for(int i=1;i<=n;i++)
temp*=i;
return temp;
}
}

Categories

Resources