How to remove a user entered value from an array? - java

The user enters a value, and it is told that we are to remove the value, and print the newly created array.
How do i write that code? It is supposed to be in that method removeValue.
Can you also explain how it works.
import java.util.*;
public class ArrayHandler {
public static void main(String[]args)
{
int[] array= new int[5]; // populates Array with 5 numbers
for(int i=0;i<array.length;i++) // creates the 5 random numbers
array[i]=(int)(Math.random()*5000);
printList(array); // prints Array
System.out.println("");
System.out.println("Sum: " + calculateSum(array));
System.out.println("Max: " + findMax(array));
System.out.println("Minimum: " + findMin(array));
System.out.println("Value: " + search(array));
}
public static void printList(int[] nums)
{
for(int i=0; i<nums.length;i++) {
System.out.print(nums[i] + " ");
}
}
public static int calculateSum(int[] nums)
{
int sum = 0;
for(int i=0;i<nums.length;i++)
{
sum = sum + nums[i];
}
return sum;
}
public static int findMin(int[] nums)
{
int min = nums[0];
for(int i=0;i<nums.length;i++)
{
if(nums[i] < min)
min=nums[i];
}
return min;
}
public static int findMax(int[] nums)
{
int max=nums[0];
for(int i=0;i<nums.length;i++)
{
if(nums[i] > max)
max=nums[i];
}
return max;
}
public static int search(int[] nums)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("What value do you want?");
int value = keyboard.nextInt();
for(int i=0;i<nums.length;i++)
{
if(nums[i] == value)
return i;
}
return -1;
}
public static int removeValue (int[] nums)
{
int[] array = new array[array.charAt(value) - array.charAt(value)];
if(nums[i] == i)
return array;
else
return -1;
}
}

This has been answered: Removing an element from an Array (Java)
If you want to use only arrays, view this answer: Removing an element from an Array (Java)

public static String removeValue (int[] nums)
{
int i = search(nums);
nums[i] = nums[i] - nums [i];
if(nums[i] == 0)
{
return Arrays.toString(nums);
}
else return "invalid";
}
This will work and instead of calling the search method in your main, call the removeValue method and pass it the array.

Related

Printing the summary of a series of questions using non-void method

Hy. I wrote this piece of code
import java.util.Scanner;
public class SportsEvents {
public static void main(String[] args) {
String[] contestants = getcontestants();
int[] score=getscores();
System.out.println("The maximum score is: "+getMaxValue(score));
System.out.println("The minimum score is: "+getMinValue(score));
System.out.println("The average is: "+getAverage(score));
}
public static String[] getcontestants()
{
int numcontestants=1;
String name[] = new String[numcontestants];
for(int j=0;j<numcontestants;j++){
Scanner ip=new Scanner(System.in);
System.out.println("Enter contestant's name");
name[j]=ip.nextLine();
}
return name;
}
public static int[] getscores()
{
int numscores=8;
int score[] = new int[numscores];
for (int a=0;a<numscores;a++){
Scanner ip=new Scanner(System.in);
System.out.println("Enter the scores");
score[a]=ip.nextInt();
}
return score;
}
public static int getMaxValue(int[] array) {
int maxValue = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > maxValue) {
maxValue = array[i];
}
}
return maxValue;
}
public static int getMinValue(int[] array) {
int minValue = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < minValue) {
minValue = array[i];
}
}
return minValue;
}
public static int getAverage(int[] people) {
int sum = 0;
for (int i=0; i < people.length; i++) {
sum = sum + people[i];
}
int result = sum / people.length;
return result;
}
}
As you can see, the user enters a name and 8 scores and the computers find the biggest score, the lowest score, and the average. I want a non-void method that will give a summary of everything but I don't know how to do it.
Ex: If I entered James as a name and the numbers 1-8, I want it to print: The contestant is James, his highest score was 8. His lowest score was 1. His average is 49.
Thank you and tell me if it's confusing!!
What you want is to store your immediate result into a single object contains min, max, avg.
In java 8 there's already a method out of the box for you:
int[] score=getscores();
IntSummaryStatistics stats = Arrays.stream(score).summaryStatistics();
IntSummaryStatistics contains
private long count;
private long sum;
private int min;
private int max;
You can also manually get that result:
First define a class will hold your data:
public class SportsEvents {
public static class IntArrayStatistic {
private int min = Integer.MAX_VALUE;
private int max = Integer.MIN_VALUE;
private int sum = 0;
private int avg;
private int count;
// Getter - Setter
public static IntArrayStatistic of(int[] input) {
if (input == null) {
throw new IllegalArgumentException("Null array");
}
IntArrayStatistic result = new IntArrayStatistic();
result.count = input.length;
for (int i : input) {
if (i < result.min) {
result.min = i;
}
if (i > result.max) {
result.max = i;
}
result.sum += i;
}
result.avg = result.sum / result.count;
return result;
}
}
}
And to use this:
int[] score=getscores();
IntArrayStatistic stats = IntArrayStatistic.of(score);

Coding Heapsort Algorithm but am getting a Stack Overflow error and cannot figure out why

Below is my code, I keep getting a Stack Overflow error from the last statement in my code which is the recursive call for heapify (the max heapify) method. Please help.
Class 1 code
package hw3javasorttest;
import java.util.*;
public class HW3JavaSortTest {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Unsorted array");
System.out.print("[");
int[] arr = new int[30];
for(int i = 0; i < arr.length; i++) {
arr[i] = (int)(Math.random() * 100);
System.out.print(arr[i] + " ");
}
System.out.println("]");
Scanner in = new Scanner(System.in);
System.out.println("Please enter one of the corresponding numbers to choose the sorting method: ");
System.out.print("1.Heap Sort\n2.Quick Sort");
int Sorting = in.nextInt();
int x;
int q;
x = arr[0];
q = arr[29];
switch (Sorting) {
case 1: System.out.println("Heap Sort:");
HW3JavaSort.HeapSort(arr);
System.out.println(Arrays.toString(arr));
break;
case 2: System.out.println("Quick Sort:");
System.out.println();
// HW3JavaSort.quickSort(arr, x, q);
// System.out.println(Arrays.toString(a));
break;
default: System.out.println("invalid entry");
break;
}
}
}
Class 2 code
package hw3javasorttest;
public class HW3JavaSort {
public static void printArr(int[] arr) { //Method that displays arr
System.out.print("[");
for(int i= 0; i<arr.length; i++){
if(i==arr.length-1) {
System.out.printf("%d]\n", arr[i]);
}
else {
System.out.printf("%d,", arr[i]);
}
}
}
public static void HeapSort(int[] arr) {
int Length = arr.length;
int placeholder;
BuildMaxHeap(arr, Length);
for(int i = arr.length-1; i>0; i--) {
placeholder = arr[0];
arr[0] = arr[i];
arr[i] = placeholder;
heapify(arr, 1, i);
}
}
public static void BuildMaxHeap(int[] arr, int n){ //Organizes max heap
if(arr == null) {
throw new NullPointerException("null");
}
if(arr.length <=0 || n <= 0) {
throw new IllegalArgumentException("illegal");
}
if(n > arr.length) {
n = arr.length;
}
for(int i = n/2; i>= 0; i--) {
heapify(arr, i, n);
}
}
public static void heapify(int [] arr, int i, int n) { //Makes max heap
int largest;
int lc = 2*i;
int rc = 2*i + 1;
int temp = 0;
if(lc<=n && arr[lc-1] > arr[i-1]) {
largest = lc;
} else {
largest = i;
}
if(rc<=n && arr[rc-1] > arr[largest-1]) {
largest = rc;
}
if(largest!=i) {
temp = arr[i-1];
arr[i-1] = arr[largest - 1];
arr[largest - 1] = temp;
heapify(arr, largest, n); //HERE IS WHERE THE COMPILER SAYS I AM //GETTING THE ERROR, SAYS STACK OVERFLOW THEN THE HEAPIFY METHOD THEN THIS LINE //# AND DISPLAYS THE ERROR HUNDREDS OF TIMES
}
}
}
Incorrect formatting caused the algorithm to work differently than expected... fixed by formatting like Java (not Python).
Please take a look at this: https://blog.takipi.com/tabs-vs-spaces-how-they-write-java-in-google-twitter-mozilla-and-pied-piper/

illegal start of type: Often this message means that you are missing a { BEFORE this line

Could anyone help me out with this error?
I couldn't rectify this code.
I can't understand the error.
import java.io.*;
import java.util.Scanner;
public class findMax{
public static int findMax(int[] arr){
int max = 0;
for (int i = 1; i < value.length; i++){
if (value[i] > max){
max = value[i];
}
}
return max;
}
public static void main(String[] args){
int value[];
Scanner in = new Scanner(System.in);
value = in.nextInt();
findMax(value);
}
}
In the function findMax, you need to be consistent with your array variable name (you're currently passing int[] arr but accessing value). Also, you don't want to default max to 0 (you could use arr[0]). Something like,
public static int findMax(int[] arr) {
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
Next, you need to instantiate and assign values into your array (and do something with the result of findMax as is the result isn't used). There are a few ways to do that. One might be,
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] value = new int[] { in.nextInt() };
int max = findMax(value);
System.out.printf("The max value in %s is %d.%n", Arrays.toString(value), max);
}
Alternatively, you could create the array like
int[] value = new int[1];
value[0] = in.nextInt();
Also, you could eliminate the if if you use Math.max(int, int) in findMax like
public static int findMax(int[] arr) {
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
max = Math.max(max, arr[i]);
}
return max;
}
import java.util.ArrayList;
import java.util.Scanner;
public class Stack{ public static int findMax(ArrayList<Integer> arr){
int max = 0;
for (int i = 1; i < arr.size(); i++){
if (arr.get(i) > max){
max = arr.get(i);
}
}
return max;
}
public static void main(String[] args){;
Scanner in = new Scanner(System.in);
ArrayList<Integer> value = new ArrayList<Integer>();
System.out.print("Enter integers please ");
System.out.println("(EOF or non-integer to terminate): ");
while (in.hasNextInt()) {
value.add(in.nextInt());
}
System.out.println(findMax(value));
}}
Try this
public static int findMax(ArrayList<Integer> arr){
int max = arr.get(0);
for (int i = 1; i < arr.size(); i++){
if (arr.get(i) > max){
max = arr.get(i);
}
}
return max;
}
public static void main(String[] args){;
Scanner in = new Scanner(System.in);
ArrayList<Integer> value = new ArrayList<Integer>();
System.out.print("Enter integers please ");
System.out.println("(EOF or non-integer to terminate): ");
while (in.hasNextInt()) {
value.add(in.nextInt());
}
System.out.println(findMax(value));
}

Core Java Practical Questions

A Test array has the following property:
a[0] = a[1] + a[2] = a[3] + a[4] + a[5] = a[6] + a[7] + a[8] + a[9] = ...
The length of a Test array must be n*(n+1)/2 for some n.
Write a method named isTestArray that returns 1 if its array argument is a Test array, otherwise it returns 0. The function signature is:
int isMadhavArray(int[ ] a)
Example:
This is what I have tried:
public class TestArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(isTestArray(new int[] {2,1,1,4,-1,-1}));
}
static int isTestArray(int[] a){
boolean isEq=true;
for(int i=0;i<a.length;i++){
int n=i, value=a.length;
int equation=n*(n+1)/2;
if(value==equation)
{
for(int x=0,y=1;y<a.length;x++,y++){
if(a[0]==a[x]+a[y]){
//having problem over here :(
}
}
}
else
isEq=false;
}
if(isEq)
return 1;
else
return 0;
}
}
Number of elements in sum increases by 1 in every portion.
You should do 2 things:
Write a method that will calculate sum of N elements starting from K position in array
Increment i with the number of the smallest portion in iteration
example code:
int portionSize = 1; // number of elements to sum
int position = 0; // index of first element
while (position + 2 * portionSize + 1 < array.length) { // condition for last iteration
if (sum(position, portionSize) != sum(position + portionSize, portionSize + 1) {
return false; // if not equal, return immediately
}
position += portionSize;
portionSize++;
}
Here is my attempt for your troubling inner for loop. Because each time you loop, you increment the number of indexes you need to add by one, so I think you need another nested loop like this. I know it is ugly. Can't blame me, I am a beginner.
public class TestArray {
public static void main(String[] args) {
System.out.println(isTestArray(new int[] {2,1,1,4,-1,-1}));
}
static int isTestArray(int[] a) {
boolean isEq = false;
for(int i=0; i < a.length; i++) {
int n=i, value = a.length;
int equation= n*(n+1)/2;
if (value==equation) {
int index = 1;
for (int x = 1; x < a.length; x++) {
int total = 0;
for (int y = index, count = 0; count < x+1; y++, count++) {
if (y!= a.length) {
total += a[y];
if (total == a[0])
isEq = true;
else
isEq = false;
index++;
}
else
break;
}
}
}
}
if (isEq)
return 1;
else
return 0;
}
public class TestArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(isTestArray(new int[] {2,1,1}));
System.out.println(isTestArray(new int[] {3, 1, 2, 3, 0}));
}
static int isTestArray(int[] a){
boolean isEq=false, isEx=false;
int equation=0,value=a.length;
//for equation check
for(int n=0;n<value;n++){
equation=n*(n+1)/2;
if(value==equation){
isEx=true;
break;
}
}
//if equation is true
if(isEx)
{
int x=1,y=3,c=0,sum=0;
do{
for(int I=x,J=y;I<J;I++){
sum=sum+a[I];
}
if(a[0]==sum){
isEq=true;
sum=0;
}
else{
isEq=false;
break;
}
c++;
x=y;
y=x+2+c;
}while(x<a.length);
}
//last operation of return
if(isEq)
return 1;
else
return 0;
}
}
import java.io.*;
public class StackQues1{
static boolean flag = true;
static int arrLength = 0;
public static void main(String args[]){
Console c = System.console();
System.out.println("Enter the length of array - ");
arrLength = Integer.parseInt(c.readLine());
//Let max val of n<=20
//To check n(n+1)/2
boolean nFlag = false;
for(int n=1;n<=20;n++){
if(arrLength == (n*(n+1))/2){
nFlag = true;
}
}
if(!nFlag){
System.out.println("Length of array is not in the form of (n*(n+1))/2");
}else{
int arr[] = new int[arrLength];
System.out.println("Enter the elements of array - ");
for(int i=0;i<arr.length;i++){
arr[i] = Integer.parseInt(c.readLine());
}
System.out.println("Returned value = "+isTestArray(arr));
}
}
//Logic Implementation
public static int isTestArray(int[] arr){
int sum = 0;
int noOfElements=0;
for(int i=0;i<arr.length;){
noOfElements++;
sum=0;
for(int j=1;j<=noOfElements;j++){
sum=sum+arr[i];
i++;
}
if(arr[0] == sum){
flag = true;
}else{
flag = false;
break;
}
}
if(flag){
return 1;
}else{
return 0;
}
}
}

Java method to sum any number of ints

I need to write a java method sumAll() which takes any number of integers and returns their sum.
sumAll(1,2,3) returns 6
sumAll() returns 0
sumAll(20) returns 20
I don't know how to do this.
If your using Java8 you can use the IntStream:
int[] listOfNumbers = {5,4,13,7,7,8,9,10,5,92,11,3,4,2,1};
System.out.println(IntStream.of(listOfNumbers).sum());
Results: 181
Just 1 line of code which will sum the array.
You need:
public int sumAll(int...numbers){
int result = 0;
for(int i = 0 ; i < numbers.length; i++) {
result += numbers[i];
}
return result;
}
Then call the method and give it as many int values as you need:
int result = sumAll(1,4,6,3,5,393,4,5);//.....
System.out.println(result);
public int sumAll(int... nums) { //var-args to let the caller pass an arbitrary number of int
int sum = 0; //start with 0
for(int n : nums) { //this won't execute if no argument is passed
sum += n; // this will repeat for all the arguments
}
return sum; //return the sum
}
Use var args
public long sum(int... numbers){
if(numbers == null){ return 0L;}
long result = 0L;
for(int number: numbers){
result += number;
}
return result;
}
import java.util.Scanner;
public class SumAll {
public static void sumAll(int arr[]) {//initialize method return sum
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
System.out.println("Sum is : " + sum);
}
public static void main(String[] args) {
int num;
Scanner input = new Scanner(System.in);//create scanner object
System.out.print("How many # you want to add : ");
num = input.nextInt();//return num from keyboard
int[] arr2 = new int[num];
for (int i = 0; i < arr2.length; i++) {
System.out.print("Enter Num" + (i + 1) + ": ");
arr2[i] = input.nextInt();
}
sumAll(arr2);
}
}
public static void main(String args[])
{
System.out.println(SumofAll(12,13,14,15));//Insert your number here.
{
public static int SumofAll(int...sum)//Call this method in main method.
int total=0;//Declare a variable which will hold the total value.
for(int x:sum)
{
total+=sum;
}
return total;//And return the total variable.
}
}
You could do, assuming you have an array with value and array length: arrayVal[i], arrayLength:
int sum = 0;
for (int i = 0; i < arrayLength; i++) {
sum += arrayVal[i];
}
System.out.println("the sum is" + sum);
I hope this helps.

Categories