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
Related
I was asked to
Create a method with a single parameter, an array of integers, that will return an array of integers. Count how many odd values exists within the array. Create a new array with that many elements. Place all the odd values into this new array ( that is all odd values from the array passed through as a parameter ). Return this new array
but I am having some difficulty in transferring the odd values into the new array. I can get the correct size based on the number of odd values in the first array but right now they appear as zeros. Here is the code:
import java.util.Scanner;
public class Main {
public static int output(int[]beans){
int sum = 0;
for (int p = 0; p < beans.length; p++){
if(beans[p]%2 != 0){
sum++;
}
}
System.out.print("The number of odd vaules in this array are: "+sum);
System.out.println();
int[] notbeans = new int[sum];
System.out.print("The odd values within the first array are: ");
for (int index = 0; index < beans.length; index++){
if( beans [index] %2 != 0){
System.out.print(beans[index]);
}
}
System.out.println();
for (int g = 0; g < notbeans.length; g++){
System.out.print(notbeans[g]);
}
return notbeans[1];
}
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int[]array = new int[5];
for (int t = 0; t < array.length; t++){
System.out.print("Enter an integer: ");
array[t] = key.nextInt();
}
output(array);
}
}
According to your question, method output needs to...
Return this new array
Hence method output needs to return int[] (and not int).
After counting the number of odd values in the array passed to method output and creating the array that the method needs to return, in order to populate the returned array, you need to maintain a second [array] index. You are using the same index to populate the returned array and to iterate the array parameter. The returned array may be smaller in size, i.e. contain less elements, than the array parameter so using the same index for both arrays may cause method output to throw ArrayIndexOutOfBoundsException. In any method, you should also always check whether the method parameters are valid.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static int[] output(int[] beans) {
int sum = 0;
if (beans != null && beans.length > 0) {
for (int p = 0; p < beans.length; p++) {
if (beans[p] % 2 == 1) {
sum++;
}
}
}
int[] notBeans = new int[sum];
int j = 0;
for (int index = 0; index < beans.length; index++) {
if (beans[index] % 2 == 1) {
notBeans[j++] = beans[index];
}
}
return notBeans;
}
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int[] array = new int[5];
for (int t = 0; t < array.length; t++){
System.out.print("Enter an integer: ");
array[t] = key.nextInt();
}
System.out.println(Arrays.toString(output(array)));
}
}
Your output function should return an array, so return type will not be int. It will be int[]. See the below code and let me know.
public class Main {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int[]array = new int[5];
for (int t = 0; t < array.length; t++){
System.out.print("Enter an integer: ");
array[t] = key.nextInt();
}
int[] arr=output(array);
for(int i=0;i<arr.length;i++){
int val=arr[i];
if(val!=0){
System.out.println(val);
}
}
}
public static int[] output(int[]beans){
int[] notBeans=new int[beans.length];
int i=0;
for(int v:beans){
if(v%2!=0){
notBeans[i]=v;
i++;
}
}
return notBeans;
}
}
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
In the following code, I have resized an array, increased in length by 5 elements. length is displaying correctly. But when I run a loop to display the elements of the array, only initialized elements are displayed. How can I show all the elements?
package arraychallenge;
import java.util.*;
public class ArrayChallenge {
public static void main(String[] args) {
Scanner CountScanner = new Scanner(System.in);
System.out.println("How many integers you have in your list? ");
int count = CountScanner.nextInt();
System.out.println("Enter the integers now - ");
int[] MyArray = getIntegers(count);
System.out.println("Unsorted Array is present here:");
for (int i = 0; i < MyArray.length; i++) {
System.out.println(MyArray[i]);
}
sortArray(MyArray);
printArray(MyArray);
resizeArray(MyArray, MyArray.length, 5);
printArray(MyArray);
}
public static int[] getIntegers(int count) {
Scanner MyScanner = new Scanner(System.in);
int[] MyArray = new int[count];
for (int i = 0; i < MyArray.length; i++) {
MyArray[i] = MyScanner.nextInt();
}
return MyArray;
}
public static void sortArray(int[] MyArray) {
int temp;
for (int i = 0; i < MyArray.length; i++) {
for (int j = i+1; j < MyArray.length; j++) {
if (MyArray[i] > MyArray[j]) {
temp = MyArray[i];
MyArray[i] = MyArray[j];
MyArray[j] = temp;
}
}
}
}
public static void printArray(int[] MyArray) {
System.out.println("Sorted Array is present here:");
for (int i = 0; i < MyArray.length; i++) {
System.out.println(MyArray[i]);
}
}
public static void resizeArray(int[] MyArray, int count, int increase){
int[] tempArray = MyArray;
MyArray = new int[count+increase];
System.out.println("length of MyArray is now " + MyArray.length);
for (int i = 0; i < count; i++) {
MyArray[i] = tempArray[i];
}
}
}
In your resizeArray method, you are passing in MyArray. Then you are creating a new array of size 5, and assigning it to the MyArray variable, but this is not the same as the one you passed in.
Read this answer: https://stackoverflow.com/a/40523/3887715
My attempt at a good way to visualize object passing: Imagine a balloon. Calling a fxn is like tieing a second string to the balloon and handing the line to the fxn. parameter = new Balloon() will cut that string and create a new balloon (but this has no effect on the original balloon). parameter.pop() will still pop it though because it follows the string to the same, original balloon. Java is pass by value, but the value passed is not deep, it is at the highest level, i.e. a primitive or a pointer. Don't confuse that with a deep pass-by-value where the object is entirely cloned and passed. – dhackner Oct 20 '10 at 16:38
In short, you call the variable MyArray in resizeArray, but it's not the same MyArray you created in main. It's a new variable inside resizeArray that happens to have the same name. So by doing MyArray = new int[count+increase];, you are not changing your original MyArray, you are changing a new one.
If you run this:
public class ArrayTest {
public static void main(String[] args) {
int[] array1 = new int[]{1,2,3,4,5};
System.out.println("Print array in main 1:");
printArray(array1);
increaseArraySize(array1, 5);
System.out.println("Print array in main 2:");
printArray(array1);
}
private static void increaseArraySize(int[] array1, int size) {
int[] tempArray = array1;
array1 = new int[tempArray.length + size];
for (int i = 0; i < tempArray.length; i++) {
array1[i] = tempArray[i];
}
System.out.println("Print array in increaseArraySize:");
printArray(array1);
}
public static void printArray(int[] MyArray) {
for (int i = 0; i < MyArray.length; i++) {
System.out.println(MyArray[i]);
}
}
}
You get:
Print array in main 1:
1
2
3
4
5
Print array in increaseArraySize:
1
2
3
4
5
0
0
0
0
0
Print array in main 2:
1
2
3
4
5
So you can see the 0s are being printed the second time the printArray method is called.
If you change the name of MyArray in resizeArray, maybe that will help you understand.
As suggested by the comments, you can have resizeArray return an array, and then assign that back to MyArray in main().
I have this question about how to write a method to fill an array with integers. I did this method, but I got confused on how to print it. Should I start with for loop in each method? And how should I print them on one line with a space between each number like this:[1 2 3 4 5 6 7 ... 50]?
public class Numbers {
public int[] numbers;
public Numbers() {
numbers = new int[50];
}
public void numSequence() { // filling the array with sequence of integers.
for(int i = 0; i < 50; i++) {
numbers[i] = i;
}
}
public void printArray() { // printing the array
// do I need for loop here
for(int i = 0; i < 50; i++) {
System.out.print(i+1);
}
}
public static void main(String[] args){
Numbers d = new Numbers();
d.numSequence();
d.printArray();
}
}
Your printArray method is not printing the array. It's printing the indices of the for loop. So first of all, print the actual array values.
Also with that print, you can add your own spaces after each letter.
E.g.
public void printArray() { // printing the array
System.out.print("["); // not in loop
for(int i = 0; i < numbers.length; i++) { // loop through numbers array
System.out.print(numbers[i]); // print the element in the array
if (i != numbers.length - 1) { // not the last element, so print a space
System.out.print(" ");
}
}
System.out.print("]"); // not in loop
}
But then you will run into an issue. Because when you created your numbers array, you started at 0, not 1. Now, you could fix this by adding 1 to the numbers array like you did in your question. But that's bad practice, since you could have just created your array properly in the first place. So change your numSequence method to this:
public void numSequence() { // filling the array with sequence of integers.
for(int i = 1; i <= 50; i++) { // starts at 1, and <= 50 so it adds 50 too
numbers[i] = i;
}
}
Not necessary to create a class to do this kind of stuff. The example code in Java 8 is something like:
Stream<Integer> stream = Stream.iterate(1, t-> t + 1);
System.out.println(Arrays.toString(stream.limit(50).toArray()));
If you insist on using the printArray method, please take a look at the implementation of Arrays#toString. Basically you have to use StringBuilder to concatenate the array items.
I am not going in detail ,i will just patch up your code,
public class Numbers {
public int[] numbers;
public Numbers() {
numbers = new int[50];
}
public void numSequence() { // filling the array with sequence of integers.
for(int i = 0; i < 50; i++) {
//Add i+1 here o when we print we get 1 2 3 ....50
numbers[i] = i+1;
}
}
public void printArray() { // printing the array
// Use numbers.length instead of 50.
for(int i = 0; i < numbers.length; i++) {
//Print the values inside the array numbers
System.out.print(numbers[i]+" ");
}
}
public static void main(String[] args){
Numbers d = new Numbers();
d.numSequence();
d.printArray();
}
}
Tip : You can make the Program more scalable by using this method instead of yours and access it as d.numSequence(100) this will print 1 2 3 ...100
public void numSequence(int theNumberLimit) {
for(int i = 0; i < theNumberLimit; i++) {
numbers[i] = i+1;
}
}
Thank you hope this helps
Without using collections,i have written a java program to remove duplicate integer element from an integer array,however the program is removing only one integer element and other integer element is left over.
Could you let me know how should i remove duplicate integer elements in the below core java program.In the below core java program i have to remove the duplicate integer element 5
Help provided will be appreciated.
Below is the Java code.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class DeleteElementFromArray {
static int[] a = {5,1,2,3,4,5,7,8,9,10};
static int[] b = new int[10];
static int i, k, f, j = 0;
static int l = a.length;
void DeletElementInt() {
for (i = 0; i < l; i++) {
if (i != k) {
if (i < k) {
b[i] = a[i];
} else{
b[i - 1] = a[i];
}
}
}
}
public static void main(String[] args) {
DeleteElementFromArray d = new DeleteElementFromArray();
System.out.println("Array Elements are ");
for (i = 0; i < l; i++){
System.out.println(a[i]);
}
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(is);
System.out.println("Enter the Element for Delete");
try {
String s = br.readLine();
f = Integer.parseInt(s);
for (i = 0; i < l; i++) {
if (f == a[i]) {
System.out.println("Delete Element found from given array");
k = i;
j++;
d.DeletElementInt();
}
}
l = l - 1;
System.out.println("New Array ");
for (i = 0; i < l; i++)
{
System.out.println(b[i]);
}
if (j == 0) {
System.out.println("Entered Element does not found from given array");
}
} catch (IOException e) {
System.out.println(e);
}
}
}
//output
/*
Array Elements are
5
1
2
3
4
5
7
8
9
10
Enter the Element for Delete
5
Delete Element found from given array
New Array
1
2
3
4
5
7
8
9
10
*/
Here is the fixed code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class DelElem {
static int[] a = {5,1,2,3,4,5,7,8,9,10};
static int[] b = new int[10];
static int f, i, k, j = 0;
static int l = a.length;
static void DeleteElementInt(int elementToDelete) {
j = 0;
for (int i = 0; i < l; i++)
if (a[i] != elementToDelete)
b[i - j] = a[i];
else
++j;
}
public static void main(String[] args) {
System.out.println("Array elements are:");
for (i = 0; i < a.length; i++)
System.out.println(a[i]);
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(is);
System.out.print("Enter the element to be deleted: ");
try {
String s = br.readLine();
f = Integer.parseInt(s);
DeleteElementInt(f);
System.out.println("New array:");
for (i = 0; i < l - j; i++)
System.out.println(b[i]);
if (j == 0)
System.out.println("Entered element was not found in the given array");
} catch (IOException e) {
System.out.println(e);
}
}
}
//output
/*
Array elements are:
5
1
2
3
4
5
7
8
9
10
Enter the element to be deleted: 5
New array:
1
2
3
4
7
8
9
10
*/
First you have to sort your array. It will be much easier for you to remove the duplicates if you do. The Arrays class contains various methods (most of them are static) to manipulate arrays. Use Arrays.sort(array). If you're not allowed to, you have to use one of the many existing sorting algorithm. The simplest being Bubble sort.
Insert the first integer in your result array, and in a temporary variable which will contain the last inserted value. Parse the source array: if the current value is different than the temporary var, insert it in the result array (and update the temp var).
Be careful with the size of your return array.
is Arrays.sort() okay?
static int[] a = {5,1,2,3,4,5,7,8,9,10};
static int[] b = new int[a.length];
Arrays.sort(a);
b[0]=a[0];
int bIndex = 1;
for(int aIndex = 1; aIndex < a.length; aIndex++) {
if(b[bIndex-1] != a[aIndex]) {
b[bIndex] = a[aIndex];
bIndex++;
}
}
int[] result = Arrays.copyOfRange(b, 0, bIndex);
if this is for educational purposes another interesting approach could be to construct a tree structure with the numbers and flatten the tree to an array when all inserts are done.
The first question when some one ask you to work with arrays should be. Do the order is important ?
Most problem with arrays can be solved by sorting it first and then the problem is reduced to trivial from complex as you always work on the same type of data. As Archimedes sad once "Give me a place to stand on, and I will move the Earth". The sort operation is that stand place.
When you sort your array, then you just need to traverse it and find that next item is equal to previous. This is trivial.
How ever if the order is important then we have a little bit harder task.
So first solution that pop i my mind is to create new point to stand. The rules are that array has items grater or equal then zero.
In this case we could do something like this.
We find the grates element in our source array.
We create a boolean array with size of grates item.
We move through each item of source list and
We check that boolean arrays position of value has false if so then we set it to true an print the result else we go to next item of source array.
The step 4 was simplified as we want to print the list. The technical aspect of returning new one with distinct values is trivial to.
So good luck.
import java.util.Scanner;
public class RemoveAllOccurences{
static int[] removeAll(int[] a,int n){
int[] dupl = new int[a.length];
for(int i = 0;i < dupl.length;i++){
dupl[i] = -999;
}
int index = 0;
//looping over,finding all occurrences of n and creating new array that does not contain n.
for(int i = 0;i < a.length;i++){
if(a[i] != n){
dupl[index++] = a[i];
}
}
//returning array with all duplicates removed.
return dupl;
}
public static void main(String[] args) {
int[] a = {3,5,5,5,3,6,5,3,3};
int numberToRemove;
System.out.println("the array values are:");
for(int i:a){
System.out.print(a[i]+"\t");
}
Scanner sc = new Scanner(System.in);
System.out.println("\nenter the number for which all occurences need to be deleted:");
numberToRemove = sc.nextInt();
int[] b = removeAll(a,numberToRemove);
System.out.println("After removing all occurences of "+numberToRemove);
for(int i:b){
if(i != -999)
System.out.print(i+"\t");
}
}
}
Below is my solution:
First step:- Iterate through array with nested loops to find duplicates
Second step:- If found duplicates copy all elements in new array except duplicate element.
Please find below code, any improvement would be appreciated.
public class DuplicateElements {
private static int[] arr = new int[]{3,2,4,4,5,3,8,2,4,9,10};
public static void main(String[] args) {
for(int i=0;i<arr.length;i++){
int arr_i = arr[i];
for(int j=0;j<arr.length;j++){
if(arr_i == arr[j] && i != j){
removeElement(j);
}
}
}
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+", ");
}
}
public static void removeElement(int position){
int[] intArr = new int[arr.length - 1];
for(int i=0;i<position;i++){
intArr[i] = arr[i];
}
for(int i=position+1;i<arr.length;i++){
intArr[i-1] = arr[i];
}
arr = intArr;
}
}
public static void main(String[] args) {
int a[]={1,4,3,2,6,5,7,3,5,4,2};
int b[]=new int[a.length];
Arrays.sort(a);
int j=0;
for(int i=0;i<a.length;i++){
while(i<a.length-1 && a[i]==a[i+1]){
a[i]=999; // This can be any tag which you are not going to have in your array
i++;
}
if(a[i]!=999)
b[j++]=a[i];
}
System.out.println(b);
}
Use:
package Array;
import java.util.Scanner;
public class DuplicateArrayElement {
//operation
void duplicate(int arr[],int size) {
int count=0;
for(int i=0;i<size-1;i++) {
for(int j=i+1;j<size;j++) {
if(arr[i]==arr[j]) {
arr[i]=0;
count++;
}
}
}
for(int i =0; i<size;i++) {
if(arr[i]!=0) {
System.out.println(" "+arr[i]);
}
}
System.out.println("Total duplicate number : "+count);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
DuplicateArrayElement duplicateArrayElement = new DuplicateArrayElement();
try {
System.out.println("Enter the size of array:");
int size = input.nextInt();
int arr[] = new int[size];
System.out.println("Enter the elements: ");
for (int i = 0; i < size; i++) {
arr[i] = input.nextInt();
}
System.out.println("Orignal Array: ");
for (int i : arr) {
System.out.print(" " + i);
}
System.out.println("\nAfter removing duplicate values :");
duplicateArrayElement.duplicate(arr, size);
} catch (ArrayIndexOutOfBoundsException ex) {
System.out.println(ex);
} finally {
input.close();
}
}
}