Hi all I want to find out second Largest no in Array accept negative numbers. I have used following code and this display second largest no of only positive no.So please suggest me how to do this.
class ArrayExample {
public static void main(String[] args) {
int secondlargest = 0;
int largest = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter array values: ");
int arr[] = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = input.nextInt();
if (largest < arr[i]) {
secondlargest = largest;
largest = arr[i];
}
if (secondlargest < arr[i] && largest != arr[i])
secondlargest = arr[i];
}
System.out.println("Second Largest number is: " + secondlargest);
}
}
The problem comes from the fact that you initialize your two variables to 0 in the lines:
int secondlargest = 0;
int largest = 0;
You should instead initialize them to Integer.MIN_VALUE and then it will also work for negative values.
Initialize the variables secondlargest and largest with the smallest negative values.
Use this code:
class ArrayExample {
public static void main(String[] args) {
int secondlargest = Integer.MIN_VALUE;
int largest = Integer.MIN_VALUE;
Scanner input = new Scanner(System.in);
System.out.println("Enter array values: ");
int arr[] = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = input.nextInt();
if (largest < arr[i]) {
secondlargest = largest;
largest = arr[i];
}
if (secondlargest < arr[i] && largest != arr[i])
secondlargest = arr[i];
}
System.out.println("Second Largest number is: " + secondlargest);
}
}
Initialize largest and secondLargest to Integer.MIN_VALUE instead of zero.
This works for me, for both positive and negative values. Before the loop, you need to initialize the largest and secondlargest variables with very small values, by doing this you can be (almost) sure that all the other values in the array will be greater than them:
int largest = Integer.MIN_VALUE;
int secondlargest = Integer.MIN_VALUE;
Inside the loop:
if (arr[i] > largest) {
secondlargest = largest;
largest = arr[i];
}
else if (arr[i] != largest && arr[i] > secondlargest) {
secondlargest = arr[i];
}
After the loop:
if (secondlargest != Integer.MIN_VALUE)
System.out.println("Second Largest number is: " + secondlargest);
Notice that the last check is required for the (rather unlikely) case where all the elements in the array happen to be Integer.MIN_VALUE.
package com.demo.mum;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* #author cyruses
*
*/
public class SecondLargest {
public static int largest = Integer.MIN_VALUE;
public static int secondLargest = Integer.MIN_VALUE;
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Size of Array:");
int n = Integer.parseInt(br.readLine());
int a[] = new int[n];
System.out.println("Enter the elements on array:");
for (int i = 0; i < a.length; i++) {
a[i] = Integer.parseInt(br.readLine());
}
System.out.println("Elements you entered are:");
for (int i = 0; i < a.length; i++) {
System.out.println("a[" + i + "]" + "=" + a[i]);
}
if (a.length <= 2) {
if (a[0] == a[1]) {
System.out.println("Theres no second largest number in your array");
} else {
System.out.println("SecondLargest:" + secondLargest(a));
}
} else {
System.out.println("SecondLargest:" + secondLargest(a));
}
}
private static int secondLargest(int[] a) {
for (int i = 0; i < a.length; i++) {
if (a[i] > largest) {
secondLargest = largest;
largest = a[i];
} else if (a[i] > secondLargest) {
secondLargest = a[i];
}
}
return secondLargest;
}
}
I think this method may be useful it takes around n+log(n)-2 comparisons
import java.util.ArrayList;
public class SecondLargest {
static ArrayList<ArrayList<Integer>> level = new ArrayList<ArrayList<Integer>>();
public static void main(String[] args) {
int input[]={9,8,7,4,5,6,1,2,3,1,1,21,33,32,1,2,3,12,3,2,1};
ArrayList<Integer> arr= new ArrayList<Integer>();
for(int i=0;i<input.length;i++){
arr.add(input[i]);
}
level.add(arr);
seconLarger(arr);
System.out.println(SecondLarge(level));
}
private static ArrayList<Integer> seconLarger(ArrayList<Integer> arr) {
ArrayList<Integer> tmp= new ArrayList<Integer>();
if (arr.size()==1)
{
return arr;
}
if(arr.size()%2==0)
{
for(int i=0;i<arr.size();i=i+2)
{
if(arr.get(i)>arr.get(i+1))
{
tmp.add(arr.get(i));
}
else
{
tmp.add(arr.get(i+1));
}
}
}
else
{
for(int i=0;i<arr.size()-1;i=i+2)
{
if(arr.get(i)>arr.get(i+1))
{
tmp.add(arr.get(i));
}
else
{
tmp.add(arr.get(i+1));
}
}
tmp.add(arr.get(arr.size()-1));
}
level.add(tmp);
return seconLarger(tmp);
}
private static int SecondLarge(ArrayList<ArrayList<Integer>> li)
{
int li_size=li.size();
int large=li.get(li_size-1).get(0);
int secondlarge=0;
int tmp=0;
for(int i=li_size-2;i>=0;i--)
{
ArrayList<Integer> arr = li.get(i);
if(large==arr.get(tmp))
{
if(tmp+1<arr.size())
{
if(secondlarge<arr.get(tmp+1))
{
secondlarge=arr.get(tmp+1);
}
}
}
else
{
if(secondlarge<arr.get(tmp))
{
secondlarge=arr.get(tmp);
}
tmp=tmp+1;
}
tmp=tmp*2;
}
return secondlarge;
}}
Or here is a gimmicky Java implementation which doesn't rely on Integer.MIN_VALUE
int findSecondHighest(int[] arr){
if(arr == null || arr.length < 2){
throw new IllegalArgumentException();
}
int fh,sh;
if(arr[0]>=arr[1]){
fh = arr[0];
sh = arr[1];
}else{
fh = arr[1];
sh = arr[0];
}
for (int i = 2; i < arr.length; i++) {
if(fh < arr[i]){
sh = fh;
fh = arr[i];
}else if(sh < arr[i]){
sh = arr[i];
}
}
return sh;
}
Instead of initializing the second largest number to min value or zero. You can follow below code to get second largest number.
import java.util.Scanner;
public class SecondLargestNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] a;
int n;
System.out.println("Enter number of elements");
n = scanner.nextInt();
a = new int[n];
for(int i=0; i<n; i++) {
a[i] = scanner.nextInt();
}
int secondLargestNumber = a[0];
int largestNumber = a[0];
int count = 1;
for(int i=1; i<a.length; i++) {
if(a[i] >= largestNumber) {
if(a[i] == largestNumber) {
count++;
} else {
count = 1;
}
secondLargestNumber = largestNumber;
largestNumber = a[i];
} else {
if(secondLargestNumber == largestNumber && count == 1) {
secondLargestNumber = a[i];
} else if(a[i] > secondLargestNumber) {
secondLargestNumber = a[i];
}
}
}
System.out.println("Second Largest Number: " + secondLargestNumber);
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter array size = ");
int size=in.nextInt();
int[] n = new int[size];
System.out.println("Enter "+ size +" values ");
for(int i=0;i<n.length;i++)
n[i] = in.nextInt();
int big=n[0],sbig=n[0];
// finding big, second big
for(int i=0;i<n.length;i++){
if(big<n[i]){
sbig=big;
big=n[i];
}else if(sbig<n[i])
sbig=n[i];
}
// finding second big if first element itself big
if(big==n[0]){
sbig=n[1];
for(int i=1;i<n.length;i++){
if(sbig<n[i]){
sbig=n[i];
}
}
}
System.out.println("Big "+ big+" sBig "+ sbig);
in.close();
}
Related
Getting output of 0 each time when im ment to get 3 looked over my code my not sure where i have gone wrong i can do it without using a method i know but just trying to practice java
public class App {
public static int second(int a[],int n) {
int[] arr = new int [n];
int temp;
for(int i=0;i<n;i++) {
for(int j=i+1;j<n;j++) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr[n-2];
}
public static void main(String[] args) {
int[] arr = {1,3,2,5,3};
int n = 5;
int result = second(arr,n);
System.out.println(result);
}
}
You could change the array parameter name arr and remove the declaration or copy the values from a to arr.
public static int second(int arr[],int n) {
int temp;
for(int i=0;i<n;i++) {
for(int j=i+1;j<n;j++) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr[n-2];
}
The reason you get zero is because the primitive int cannot be null. So, when you create the array of length 5, it starts out filled with zeroes.
Doing it by using streams:
public static int second(int a[]) {
return Arrays.stream(a)
.sorted()
.skip(a.length - 2)
.findFirst()
.getAsInt();
}
I removed the second argument. It sorts your array and skips all the elements prior to the one you want, before picking the now first element.
public static int second(int[] arr) {
int highest = arr[0];
int second = 0;
for (int i = 1; i < arr.length; i++) {
int j = arr[i];
if (j >= highest) {
highest = j;
} else if (j > second) {
second = j;
}
}
return second;
}
public static void main(String[] args) {
int[] arr = {1, 3, 2, 5, 3};
int result = second(arr);
System.out.println(result);
}
Here is one way that doesn't require sorting.
int[] arr = { 10, 2, 3, 19, 2, 3, 5 };
System.out.println(second(arr));
prints
10
set largest to the first value in the array
set secondLargest to the smallest possible
now iterate thru the array.
if the current value is greater than largest:
replace secondLargest with Largest
replace largest with current value
else check to see if current value is greater than secondLargest and assign if true.
public static int second(int arr[]) {
int largest = arr[0];
int secondLargest = Integer.MIN_VALUE;
for (int i = 1; i < arr.length; i++) {
if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
} else if (arr[i] > secondLargest) {
secondLargest = arr[i];
}
}
return secondLargest;
}
public static int second(int arr[],int n) {
int temp;
if(arr.length < 2) {
return -1;
}
else {
for(int i=0;i<n;i++) {
for(int j=i+1;j<n;j++) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr[n-2];
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[] = {23,14,56,77,66,67};
int high = 0;
int sec = 0;
for(int i = 0 ; i <a.length; i++){
if(high < a[i]){
sec = high;
high = a[i];
}
else if(sec < a[i]){
sec = a[i];
}
}
System.out.println("the first highest number is " + high);
System.out.println("the second highest number is " + sec);
}
}
public static int sec(){
int arr[] = {12,3,67,4,5,65};
int high = 0;
int low = 0;
for(int i = 0 ; i < arr.length ; i ++){
if(high < arr[i]){
low = high;
high = arr[i];
}
else if(low < arr[i]){
low = arr[i];
}
}
return low;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
sch obj = new sch();
int a = obj.sec();
System.out.println(a);
}
}
package com;
public class FindSecondHighestNumberInArray {
public static void main(String[] args) {
int []arrayOfIngeger = {-23,-989,-878,-2,-5,-3,-4,-123,-345,-98,-675,-98};
int highestNumber = arrayOfIngeger[0];
int secHighestNumber = 0;
for(int i = 1; i < arrayOfIngeger.length; i++ ) {
if(highestNumber < arrayOfIngeger[i]) {
secHighestNumber = highestNumber;
highestNumber = arrayOfIngeger[i];
}else if(secHighestNumber < arrayOfIngeger[i] && arrayOfIngeger[i] != highestNumber) {
secHighestNumber = arrayOfIngeger[i];
}
}
System.out.println("second Highest Number in Array : "+secHighestNumber);
}
}
I am working with the following code that allows the user to enter 9 numbers and it displays the mean and median of the numbers back to the user. I am trying to figure out the best way to revise my code so that before displaying the mean and median it will also show the 9 numbers the user entered. Thanks so much for any help in this matter!
import java.util.*;
class MeanMedian
{
private static float mean(int arr[]){
int n = arr.length;
float sum = 0;
for(int i = 0;i<n;i++){
sum += arr[i];
}
return sum / n;
}
public static void selectionSort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
int lowindex = i;
for (int j = array.length - 1; j > i; j--)
if (array[j] < (array[lowindex]))
lowindex = j;
int temp = array[i];
array[i] = array[lowindex];
array[lowindex] = temp;
}
}
private static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
private static float median(int arr[]){
selectionSort(arr);
if(arr.length%2 == 0){
return arr[(arr.length/2)-1];
}
else{
return arr[arr.length/2];
}
}
public static void main(String args[]){
int n = 9;
Scanner scanner = new Scanner(System.in);
int arr[] = new int[n];
System.out.print("Enter "+ n +" integers: ");
for(int i = 0;i<n;i++){
arr[i] = scanner.nextInt();
}
System.out.println("mean: "+ mean(arr));
System.out.println("median: "+ median(arr));
}
}
I am trying to figure out the best way to revise my code so that
before displaying the mean and median it will also show the 9 numbers
the user entered.
Something like:
// ... previous code ...
System.out.println("You entered: ");
for(int i : arr) {
System.out.println(i);
}
System.out.println("mean: "+ mean(arr));
System.out.println("median: "+ median(arr));
The following code worked perfectly and passed all checks I ran on it :)
import java.util.*;
class MeanMedian
{
private static float mean(int arr[]){
int n = arr.length;
float sum = 0;
for(int i = 0;i<n;i++){
sum += arr[i];
}
return sum / n;
}
public static void selectionSort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
int lowindex = i;
for (int j = array.length - 1; j > i; j--)
if (array[j] < (array[lowindex]))
lowindex = j;
int temp = array[i];
array[i] = array[lowindex];
array[lowindex] = temp;
}
}
private static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
private static float median(int arr[]){
selectionSort(arr);
if(arr.length%2 == 0){
return arr[(arr.length/2)-1];
}
else{
return arr[arr.length/2];
}
}
public static void main(String args[]){
int n = 9;
Scanner scanner = new Scanner(System.in);
int arr[] = new int[n];
System.out.print("Enter "+ n +" integers: ");
for(int i = 0;i<n;i++){
arr[i] = scanner.nextInt();
}
System.out.println("You entered: ");
for(int i : arr) {
System.out.println(i);
}
System.out.println("mean: "+ mean(arr));
System.out.println("median: "+ median(arr));
}
}
I have a java code to read the length of an integer array, output the range, length of the gap, and any distinct elements inside. Additionally, it will output the numbers again with none repeated.
I would like to shorten the length of my main method.
My code produces the correct output, it is just very lengthy. Additionally, is there a way I can edit this main method to where it won't require a drastic change to my other methods? Thank you so much!
package ArrayPrograms;
import java.util.Scanner;
public class WIP{
static int LargestGap(int [] a, int n)
{
int diff = Math.abs(a[1] - a[0]);
for(int i = 1; i < a.length-1; i++)
if(Math.abs(a[i+1]-a[i]) > diff)
diff = Math.abs(a[i+1] - a[i]);
return diff;
}
int range(int a[], int n)
{
int max1 = Integer.MIN_VALUE;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (Math.abs(a[i] - a[j]) > max1)
{
max1 = Math.abs(a[i] - a[j]);
}
}
}
return max1;
}
int numberOfDistinctElement(int a[], int n)
{
int num = 1;
for (int i = 1; i < n; i++)
{
int j = 0;
for (j = 0; j < i; j++)
if (a[i] == a[j])
break;
if (i == j)
num++;
}
return num;
}
int[] distinctElements(int a[], int n,int numberofDistinct)
{
int index = 0;
int[] distinct= new int[numberofDistinct];
for (int i = 0; i < n; i++)
{
int flag = 0;
for (int j = 0; j < i; j++){
if (a[i] == a[j]){
flag = 1;
break;
}
}
if (flag == 0){
distinct[index] = a[i];
index++;
}
}
return distinct;
}
***public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num;
WIP obj=new WIP();
System.out.print("Enter the length of the array:");
num = in.nextInt();
int array[] = new int[num];
System.out.print("Enter the elements of the array: ");
for(int i = 0; i < num; i++)
{
array[i] = in.nextInt();
}
System.out.println("The largest gap in the array is "+WIP.LargestGap(array,num)+".");
System.out.println("The range of the array is "+obj.range(array,num)+".");
int numberofDistinct=obj.numberOfDistinctElement(array,num);
System.out.println("The number of distinct elements is "+numberofDistinct+".");
int[] distinctArray=obj.distinctElements(array,num,numberofDistinct);
System.out.print("The array of distinct elements is [");
for (int i = 0; i < distinctArray.length; i++)
if(i== distinctArray.length-1)
{
System.out.print(distinctArray[i]+"]");
}
else {
System.out.print( distinctArray[i]+ ",");
}
in.close();
}
}***
Sure thing. Here you go:
package arrayprograms;
import java.util.Scanner;
public class WIP{
static int LargestGap(int [] a, int n)
{
int diff = Math.abs(a[1] - a[0]);
for(int i = 1; i < a.length-1; i++)
if(Math.abs(a[i+1]-a[i]) > diff)
diff = Math.abs(a[i+1] - a[i]);
return diff;
}
int range(int a[], int n)
{
int max1 = Integer.MIN_VALUE;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (Math.abs(a[i] - a[j]) > max1)
{
max1 = Math.abs(a[i] - a[j]);
}
}
}
return max1;
}
int numberOfDistinctElement(int a[], int n)
{
int num = 1;
for (int i = 1; i < n; i++)
{
int j = 0;
for (j = 0; j < i; j++)
if (a[i] == a[j])
break;
if (i == j)
num++;
}
return num;
}
int[] distinctElements(int a[], int n,int numberofDistinct)
{
int index = 0;
int[] distinct= new int[numberofDistinct];
for (int i = 0; i < n; i++)
{
int flag = 0;
for (int j = 0; j < i; j++){
if (a[i] == a[j]){
flag = 1;
break;
}
}
if (flag == 0){
distinct[index] = a[i];
index++;
}
}
return distinct;
}
static void showResults(int[] array, int num, WIP obj){
System.out.println("The largest gap in the array is "+WIP.LargestGap(array,num)+".");
System.out.println("The range of the array is "+obj.range(array,num)+".");
int numberofDistinct=obj.numberOfDistinctElement(array,num);
System.out.println("The number of distinct elements is "+numberofDistinct+".");
int[] distinctArray=obj.distinctElements(array,num,numberofDistinct);
System.out.print("The array of distinct elements is [");
for (int i = 0; i < distinctArray.length; i++)
if(i== distinctArray.length-1)
{
System.out.print(distinctArray[i]+"]");
}
else {
System.out.print( distinctArray[i]+ ",");
}
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num;
WIP obj=new WIP();
System.out.print("Enter the length of the array:");
num = in.nextInt();
int array[] = new int[num];
System.out.print("Enter the elements of the array: ");
for(int i = 0; i < num; i++)
{
array[i] = in.nextInt();
}
in.close();
showResults(array, num, obj );
}
}
There's not a whole lot you can do, like most of the comments say, but you can remove and edit some of the braces around that aren't necessary for the bodies. Here is a rough draft of it. The only things you could change besides that is to store all of the WIP.tests in variables in one code block and then print them all out in another code block; which would improve readability.
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
WIP obj = new WIP();
System.out.print("Enter the length of the array:");
int num = in.nextInt();
int array[] = new int[num] ;
System.out.print("Enter the elements of the array: ");
for(int i = 0; i < num; i++)
array[i] = in.nextInt();
System.out.println("The largest gap in the array is " + WIP.LargestGap(array,num) + ".");
System.out.println("The range of the array is " + obj.range(array,num) + ".");
int numberofDistinct = obj.numberOfDistinctElement( array, num );
System.out.println("The number of distinct elements is "+numberofDistinct+".");
int[] distinctArray = obj.distinctElements(array,num,numberofDistinct);
System.out.print("The array of distinct elements is [");
for (int i = 0; i < distinctArray.length; i++)
if(i== distinctArray.length-1)
System.out.print(distinctArray[i]+"]");
else
System.out.print( distinctArray[i]+ ",");
in.close();
}
I have this professor that wants us to make a using the method header
Public static int[] eliminateDuplicates(int[] arr)
The program uses a randomly generated array to see if there are duplications but the user gives a limit on how many indexes's the random array has. Here is what I have but it's not working.
import java.util.Random;
import java.util.Scanner;
public class Dublicates
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Random generator = new Random();
System.out.println("Enter array length: ");
int[] a = new int[input.nextInt()];
for (int i = 0; i<a.length; i++)
{
a[i] = generator.nextInt(a.length*2);
}
int[] result = eliminateDuplicates(a);
System.out.println("The new numbers are: " + result.length);
System.out.println("The double numbers were:");
for (int b : result)
{
System.out.println(b + " ");
}
}
public static int[] eliminateDuplicates(int[] arr)
{
int[] temp = new int[arr.length];
int size = 0;
for (int i = 0; i < arr.length; i++) {
if (linearSearch(temp, arr[i]) == -1) {
temp[size] = arr[i];
size++;
}
int[] result = new int[size];
for (int i = 0; i < size; i++) {
result[i] = temp[i];
}
{
return result;
}
}
}
public static int linearSearch(int[] arr, int key)
{
for(int i = 0; i<arr.length; i++)
{
if (key == arr[i])
return i;
}
return -1;
}
}
As your statements making the final result is inside the for loop, the statements inside for will only run once and will not give the right answer.
So you have to change your code as follows.
public static int[] eliminateDuplicates(int[] arr)
{
int[] temp = new int[arr.length];
int size = 0;
for (int i = 0; i < arr.length; i++) {
if (linearSearch(temp, arr[i]) == -1) {
temp[size] = arr[i];
size++;
}
}
int[] result = new int[size];
for (int i = 0; i < size; i++) {
result[i] = temp[i];
}
return result;
}
The default values in the integer array is 0, The Random.nextInt() can generate 0 random value, When you run linear search then 0 will not be included in the final resultant array.
I have modify Random.nextInt() so that it will not generate 0 random number:
import java.util.Random;
import java.util.Scanner;
public class HelloCodiva
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Random generator = new Random();
System.out.println("Enter array length: ");
int[] a = new int[input.nextInt()];
for (int i = 0; i<a.length; i++){
a[i] = generator.nextInt(a.length*2)+1;//So that 0 is not generated
}
int[] result = eliminateDuplicates(a);
for (int originalValue: a){
System.out.println(originalValue+ " ");
}
System.out.println("The new numbers are: " + result.length);
System.out.println("The double numbers were:");
for (int b : result){
System.out.println(b + " ");
}
}
public static int[] eliminateDuplicates(int[] arr)
{
int[] temp = new int[arr.length];
int size = 0;
for (int i = 0; i < arr.length; i++) {
if (linearSearch(temp, arr[i]) == -1) {
temp[size] = arr[i];
size++;
}
}
int[] result = new int[size];
System.arraycopy(temp, 0, result, 0, size);
return result;
}
public static int linearSearch(int[] arr, int key)
{
for(int i = 0; i<arr.length; i++)
{
if (key == arr[i])
return i;
}
return -1;
}
}
I am a beginner coder, and I am trying to find the largest value of n, but I am having trouble. I have tried to use a for loop to search each element of the array I created, but the code returns 0 every time. Is this method correct? I have tried entering the values of n into an array, but I am not sure if this is the correct method to go about solving this goal.
import java.util.*;
public class CollatzConjecture {
private static int max;
public CollatzConjecture(int maximum){
int max=maximum;
}
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<Integer>();
Scanner scan = new Scanner(System.in);
System.out.print("Type an integer: ");
int n = scan.nextInt();
int count = 0;
while(n>1)
{
if(n%2 == 0)
{n = n/2;}
else
{n = 3*n + 1;}
System.out.println(n + " ");
count++;
arr.add(n);
arr.get(n);
}
for(int i = 0; i<arr.size()-1; i++)
{
if(arr.get(i) > max)
{
int max = arr.get(i);
}
}
System.out.println(arr);
System.out.println("Terminated after " + count + " steps");
}
}
Made some changes, but here you go:
public class CollatzConjecture {
private int max;
public CollatzConjecture() {
ArrayList<Integer> arr = new ArrayList<Integer>();
Scanner scan = new Scanner(System.in);
System.out.print("Type an integer: ");
int n = scan.nextInt();
int count = 0;
while (n > 1) {
if (n % 2 == 0) {
n = n / 2;
} else {
n = 3 * n + 1;
}
System.out.println(n);
count++;
arr.add(n);
}
for (int i = 0; i < arr.size(); i++) {
if (arr.get(i) > max) {
this.max = arr.get(i);
}
}
System.out.println(arr);
System.out.println("Largest value of n: " + this.max);
System.out.println("Terminated after " + count + " steps");
scan.close();
}
public static void main(String[] args) {
new CollatzConjecture();
}
}
So if I understand your question correctly, you are just trying to find the maximum value in an array? If so:
int max = arr.stream().max(Integer::compare).get();
or
int max = arr.get(0);
for (int i = 1; i < arr.size(); i++)
max = Integer.max(max, arr.get(i));