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
Related
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.
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
I am trying to program a Java Code in which, given the lenght of an int array and a min and max values it returns an random array values.
I am trying to program it in the most simple way, but I am still not getting how the programming process works.
What I have tried is the following:
import java.util.Random;
public class RandomIntArray {
public static void main(String[] args){
System.out.println(createRandom(10));
}
public static int[] createRandom(int n) {
Random rd = new Random();
int[] array = new int[n];
int min = 5;
int max = 99;
for (int i = 0; i < array.length; i++) {
array[i] = rd.nextInt();
while (array[i] > min) ;
while (array[i] < max) ;
}
return array;
}
}
public static int[] createRandom(int n) {
Random rd = new Random();
int[] array = new int[n];
int min = 5;
int max = 10;
for (int i = 0; i < array.length; i++) {
array[i] = rd.nextInt(max-min+1) + min;
System.out.print(array[i] +" ");
}
return array;
}
public static void main(String[] args){
createRandom(5);
}
Try using IntStream to achieve what you want
public static void main(String[] args) {
int[] arr = createRandom(10);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
public static int[] createRandom(int n) {
Random r = new Random();
int min = 5;
int max = 99;
return IntStream
.generate(() -> r.nextInt(max - min) + min)
.limit(n)
.toArray();
}
The first thing we must adjust is the random number generation. It appears you specify a min and max, so a number must be generated in with these bounds. We can use the Random.nextInt(int bound) method to set a range equal to max - min. However, this range will start from 0, so we must add your min value to make the bound complete. Using this process will eliminate the need for the existing while loops. See this question for more on this.
Now, every value in the array will be generated as
array[i] = rd.nextInt(max - min) + min
When trying to print array elements, a System.out.println() statement with the variable name of the array will print a memory address of the array. This will NOT print the entire array of values.
We must instead iterate over the elements to print them. It would be best to use a for loop to do this, but your program could generate an array of any size. So, we should use a for-each loop instead as follows:
for (int num : createRandom(10)) {
System.out.println(num);
}
This for-each is saying "for each int in the array returned by createRandom(10), refer to is as variable num and print it."
This is the final code:
import java.util.Random;
public class RandomIntArray {
public static void main(String[] args){
for (int num : createRandom(10)) {
System.out.println(num);
}
}
public static int[] createRandom(int n) {
Random rd = new Random();
int[] array = new int[n];
int min = 5;
int max = 99;
for (int i = 0; i < array.length; i++) {
array[i] = rd.nextInt(max - min) + min;
System.out.println(array[i]);
}
return array;
}
}
I got an 100 random elements array, each element is in range of 0-10, and i need to count each integer how many times it was typed (e.g. 1,2,2,3,8,8,4...)
OUTPUT:
1 - 1
2 - 2
3 - 1
8 - 2
4 - 1
My code so far is:
import java.util.Random;
public class Asses1 {
public static void main(String[] args) {
getNumbers();
}
private static int randInt() {
int max = 10;
int min = 0;
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static int[] getNumbers() {
int number = 100;
int[] array = new int[number];
for (int i = 0; i < array.length; i++) {
System.out.println(randInt());
}
System.out.println(number+" random numbers were displayed");
return array;
}
}
Add this method, which will do the counting:
public static void count(int[] x) {
int[] c=new int[11];
for(int i=0; i<x.length; i++)
c[x[i]]++;
for(int i=0; i<c.length; i++)
System.out.println(i+" - "+c[i]);
}
and change the main into this so that you call the previous method:
public static void main(String[] args) {
count(getNumbers());
}
Also, change the for loop in getNumbers into this in order to fill array with the generated numbers, not just printing them:
for (int i = 0; i < array.length; i++) {
array[i] = randInt();
System.out.println(array[i]);
}
Here is how it can be done in java 8
// Retrieve the random generated numbers
int[] numbers = getNumbers();
// Create an array of counters of size 11 as your values go from 0 to 10
// which means 11 different possible values.
int[] counters = new int[11];
// Iterate over the generated numbers and for each number increment
// the counter that matches with the number
Arrays.stream(numbers).forEach(value -> counters[value]++);
// Print the content of my array of counters
System.out.println(Arrays.toString(counters));
Output:
[12, 11, 7, 6, 9, 12, 8, 8, 10, 9, 8]
NB: Your method getNumbers is not correct you should fix it as next:
public static int[] getNumbers() {
int number = 100;
int[] array = new int[number];
for (int i = 0; i < array.length; i++) {
array[i] = randInt();
}
System.out.println(number+" random numbers were displayed");
return array;
}
int[] array2 = new int[11];
for (int i = 0; i < array.length; i++){
array2[randInt()]++
}
for (int i = 0; i < array.length; i++)
System.out.println(String.valueOf(i) + " - " + String.valueOf(array2[i]));
What I have done is:
Create an helping array array2 for storing number of occurences of each number.
When generating numbers increment number of occurences in helping array.
Map<Integer,Integer> map=new HashMap<Integer,Integer>();
int temp;
for (int i = 0; i < array.length; i++) {
temp=randInt();
if(map.containsKey(temp)){
map.put(temp, map.get(temp)+1);
}else{
map.put(temp, 1);
}
}
Trying to make a HIT(x). when Hit called it decreases the elements( which are greater than x) of array by one and then print the array. and x is also an array which contains some element. For example. AR[7 4 5 3] and x= [4 2 5] then output is [5 3 4 2]. I am trying but not getting the relevant output. my code terminates only after taking the array element.
import java.util.Scanner;
public class Kom1 {
static int[] array;
public void hit(int x) {
for (int i = 0; i < array.length; i++) {
if (array[i] > x) {
array[i] --;
}
}
printArray();
}
public void printArray() {
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int maxElements = scanner.nextInt();
array = new int[maxElements];
for (int i = 0; i < maxElements; i++) {
array[i] = scanner.nextInt();
}
}
}
Your algorithm should be like this
for(int i=0;i<x.length;i++){
for(int j=0;j<array.length;j++){
if(array[j]>x[i]){
array[j]--;
}
}
}
Things you missed
x is a array of elements. but you are using as single integer value
you haven't define or get x
your main method don't have a calling methods for processing