Finding Maximum Value of Array - java

I'm trying to loop through my array to find the maximum value and print the value. However, nothing is being printed to the console. Can you please take a look at my code below to see what I've done incorrectly.
for (c = 0; c < n; c++) //loops through array until each index has had a value input by the user
array[c] = in.nextInt();
maxInt = array[0];
minInt = array[0];
for (c = 0; c < n; c++) {
if (array[c] > maxInt) {
maxInt = array[c];
}
else {
break;
}
}
System.out.println("Max int is: " + maxInt);
}
EDIT:
Full class:
import java.util.Scanner;
public class MaxMinOfArray {
public static void main(String[] args) {
int c, n, search, array[];
int maxInt, minInt;
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt(); //asks user to specify array size
array = new int[n]; //creates array of specified array size
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++) //loops through array until each index has had a value input by the user
array[c] = in.nextInt();
maxInt = array[0];
minInt = array[0];
for (c = 1; c < n; c++) {
if (array[c] > maxInt) {
maxInt = array[c];
}
}
System.out.println("Max int is: " + maxInt);
}
}

Remove:
else {
break;
}
And start from c=1

Remove your this part of code.
else {
break;
}
Because when c==0 in that time array[c] == maxInt. So it goes to else part and break your for loop.

As others indicated, you don't want to do
else {
break;
}
That means that it'll stop looping as soon as it finds a number that isn't larger than the current max. Since you're starting with the first item in the list, which trivially isn't larger than itself, you break immediately.
Even if you changed it to start at c = 1, the only case where this code could possibly work as written is if the user entered numbers in ascending order. (In that case, doing a linear search like this would be pointless anyway since you could literally just find the last item in the array and know that it'll be the largest item).
Also, you should check to see if array[c] is smaller than the current minimum value in your for loop; there's no reason at all to do this in a separate loop.
Remember, if you're doing a linear search for the max value of an unsorted array, you always must go through the entire array to make sure you didn't miss a greater value. For example, if you only search half of the array, how do you know that the half that you didn't search doesn't contain the max value?

Your second loop compares for each element in array if it is greater than maxInt, but maxInt has just been set to the first element of array. This fails the condition on the first iteration of the loop, executing the break in the else block, which ends the loop.
Taking out the else block fixes this:
for (c = 0; c < n; ++c)
{
if (array[c] > maxInt)
maxInt = array[c];
}
Or alternatively:
for (c = 0; c < n; ++c)
maxInt = Math.max(maxInt, array[c]);
As for the console message not appearing, make sure the code is properly executed by setting a breakpoint and stepping through the code (depends on the IDE you're using).

Related

Java Accessing the value in array

i don't understand what is the way to access the data in the array and use it as a condition the condition is to stop looping after the content exceeds 4,000,000 and also store and add the value if its value is an even number!
int[] a=new int[40];
int add=0;
a[0]=1;
a[1]=2;
int i=2;
do{
a[i]=a[i-1]+a[i-2];
System.out.println(a[i]);
if(a[i]%2==0)
{
add=add+a[i];
}
i++;
}
while(i<32);
System.out.println(add);
Just put a check for your variable add to see if its value is greater than 4,000,000 and break out of the loop. Do something like this:
if(add > 4000000) {
break;
}
So your final code will look like this:
int[] a=new int[40];
int add=0;
a[0]=1;
a[1]=2;
int i=2;
do{
a[i]=a[i-1]+a[i-2];
System.out.println(a[i]);
if(a[i]%2==0){add=add+a[i];}
if(add > 4000000) {
break; //this will get you out of your loop
}
i++;
}while(i<32);
System.out.println(add);
I would just throw this out there: Using a do-while loop may be making this harder than it has to be. The first part of your code is totally reasonable, but the while i > 32 is less than clear.
I'd look at it this way. After you initialize your array and its first two values with
int[] a = new int[40];
a[0] = 1;
a[1] = 2;
You know that you've accounted for one even value (2). So just initialized add to 2.
Now for the loop. You want to start at i = 2, and iterate as long as add is less than or greater than 4,000,000, right? So make a for loop to express it:
for (int i = 2; add <= 4000000; i++) {
a[i] = a[i - 2] + a[i -1];
if (a[i] % 2 == 0) {
add += a[i];
}
}
No need for the i < 32, and no need for any break statements!
As a matter of interest, this is a good application for Java 8 streams.
class Fib implements IntSupplier {
private int current = 1;
private int previous = 0;
public int getAsInt() {
int next = current + previous;
previous = current;
current = next;
return current;
}
IntStream.generate(new Fib())
.limit(4000000)
.filter(n - > n % 2 == 0)
.sum();

Error when testing for the max value of a table?

I have an error when I try to run a loop that will test the max value of a table.
The table is tabl with a length of c.
int a=0;
int b=0;
while (a<=c) {
int d = tabl[a];
int e = tabl[a+1];
if(d < e)
b = e;
else
b = d;
a++;
}
It's pretty easy, it starts with comparing tabl[0] and tabl[1], and saves the bigger one, and then keeps going until a = c which is the length of the table and then finishes the loop saving the biggest value of the table in b.
But when I run this I get an java.lang.ArrayIndexOutOfBoundsException error code, can anyone help please? thanks!
When you reach a = c - 1 in your loop, your code is looking for the value of tabl[c-1]and tabl[c]. However, since your table is of length c, this causes an java.lang.ArrayIndexOutOfBoundsException. Beware that in Java, arrays are 0-indexed, that is to say, the first element is at index 0 and the last at index (length - 1).
You could write something like that, using a for-each construct :
int max = 0;
for (int element : tabl) {
if (element > max) {
max = element;
}
}
or a simple for loop
int max = 0;
for (int i = 0; i < tabl.length; i++) {
int element = tabl[i];
if (element > max) {
max = element;
}
}
The problem is you are going one past the end of the array. Arrays are zero indexed, so the item at c is going to be IndexOutOfBounds.
Also because you are accessing a + 1, this means that on the loop when a = c - 2, a + 1 will access the last element of the array.
Try:
int a=0;
int b=0;
while (a < c - 1){
int d = tabl[a];
int e = tabl[a+1];
if(d<e) { b=e;} else { b=d; }
a++;
}
NB: The change is to say a < c - 1 rather than a <= c to ensure that a is never = c when indexing into the array.
You're going out of the bounds of your array when trying to reach tabl[a+1] when a equals c
Your whole algorithm doesn't really make sense: you don't have to compare the current index's value to the next one to find out the max of the array, but rather the current value to the previous maximum value you found out.
A common way to find the maximum value of an array is that one:
int max = table[0];
for(int i = 1; i < c; i++)
if(table[i] > max)
max = table[i];
This way, max will contain the highest value of the array (though the code will throw an Exception if the table is empty).
Please, indent your code better, and use more meaningful variable names (people understand max better than b)

adding element to stack

I create a method in stack call adding in this method I want to add element after the element is specific form use for example if the number in stack is "1 2 3 5" and I choose number 3 and enter number 4 the stack should be "1 2 3 4 5" this my trying
int a[] = new int[6];
int Top = -1;
public void push() {
if (Top > 6) {
System.out.println(" the Stack Ovelflow");
} else {
Top = Top + 1;
String m = JOptionPane.showInputDialog("enter the element stack");
a[Top] = Integer.parseInt(m);
}
}
public void adding() {
String s = JOptionPane.showInputDialog("enter the element u want to add after it");
int x = Integer.parseInt(s);
String s2 = JOptionPane.showInputDialog("enter the element u want to add to stack");
int d = Integer.parseInt(s2);
for (int i = 0; i < a.length; i++) {
if (a[i] == x) {
a[i + 1] = d;
}
}
}
You need to make sure that your backing array a has enough space, so you can insert a new element.
int[] a= new int[]{1,2,3,5}; // this has only 4 elements, you can't add a 5th
So you could do:
public void adding(){
// ask user for input.... and all that
// you need an array with one more element than a. lets call it b
int[] b = new int[a.length + 1];
// now you need to search for x. (this is, if x is a number in your array and not an index..it wasn't clear to me)
// so if x is a number in the array (and not the index) you need to get the index of that number:
int index = 0;
for (; index < a.length; index++) { // your index variable will increment on each step
if (a[index] == x) {
break; // and you break out of the loop once you found x
}
}
// now you know the index of x
// first make a copy of the partial array after x (in your example its just {5})
int[] c = Arrays.copyOfRange(a, index, a.length); // this will copy all elements of a from "index" to "length"
// and here the loop that will actually insert the new number and move the rest:
int cIndex=0; // we need that counter later to loop through the new array c
for (int i = 0; i < b.length; i++) { // loop through every element of b
if (i <= index) { // if i is currently smaller than your wanted index (there where you will find x)
b[i] = a[i]; // then just copy the contents of a
} else if (i == index+1) { // we just stepped over x
b[i] = d; // so you can add your new number here
} else {
b[i] = c[cIndex]; // and here you copy the rest into b (the partial array we called c earlier)
cIndex++; // we need that new index, to get always the next element
}
}
And that's it. looks complicated and is by far not the best or most efficient solution. But it works and I hope it helps you getting further!

finding the number of pairs of numbers in an array that add up to a number

I am trying to come up with a program that will search inside of an array that is given a length by the user that picks out whether there is a pair of numbers that sum to 7. The idea is that if there is k amount of dice being thrown, how many pairs of numbers out of those dice thrown add up to 7. So far this is all that I could come up with but I am very stuck.
This is the driver class for the program. I have to write a class that will make this driver function properly.
import java.util.Scanner;
public class SevenDriver{
public static void main(String[] args){
System.out.println("Enter number of dice to toss");
Scanner s = new Scanner(System.in);
int diceCount = s.nextInt();
SevenTally t = new SevenTally(diceCount);
int experiments = 1000000;
int wins = 0;
for(int j = 0; j < experiments; j++)
if(t.experiment()) wins++;
System.out.println((double)wins/experiments);
}
}
This is what I have so far. It does not currently work or compile. I am just looking for some ideas to get me going. Thanks!
public class SevenTally{
private int diceCount;
public SevenTally(int die){
diceCount = die;
}
public int genDice(){
return 1 + (int)(Math.random()*6);
}
public boolean experiment(){
boolean[] nums = new boolean[diceCount];
int ranNum;
int sum = 7;
for(int i = 0; i < nums.length; i++){
ranNum = genDice();
if (nums[ranNum] == sum){
return true;
}
}
int left = 0;
int right = nums.length - 1;
while(left<right){
int tempSum = nums[left] + nums[right];
if(tempSum == 7){
return true;
}
else if(tempSum>7){
right--;
}
return false;
}
}
First populate your array of length k with random int in [1;6]
The number of possible pairs in an array of length k is the number of 2-combinations in the array, which is (k-1)*k/2 (http://en.wikipedia.org/wiki/Combination)
You can test all the possible pairs (i,j) in your array like so:
int win = 0;
int tally = 7;
for(int i=0; i<k-1; i++){
for(int j=i+1; j<k; j++){
if(array[i]+array[j] == tally){
win++;
}
}
}
What this does is that it sets the first element of the pair to be the first element of the array, and sums it with the other elements one after the other.
It pairs array[0] with array[1] to array[k-1] at the first pass of the i for loop, that's k pairs.
Then k-1 pairs at second pass, and so on.
You end up with (k)+(k-1)+(k-2)+...+1 pairs, and that's exactly (k-1)*k/2 pairs.
done =]
edit: sorry, haven't read the whole thing. the method experiment() is supposed to return a boolean. you can return win>0?true:false; for example...
This Wiki page has some algorithms to do that. Its not a trivial problem...
You're generating a random number in ranNum, and then using it as an index into the array nums. Meanwhile, nums never gets filled, so no matter which box you index into, it never contains a 7.
What you want to do, if I understand your problem correctly, is fill each space in the array with the result of a die roll, then compare every two positions (rolls) to see if they sum to seven. You can do that using a nested for loop.
Essentially, you want to do this: (written in pseudocode as I'm not a java programmer)
int[] results[numrolls]
for (count = 0 to numrolls-1) { results[numrolls]=dieRoller() }
for (outer = 0 to numrolls-2)
for (inner = outer+1 to numrolls-1)
if (results[outer] + results[inner] == 7) return true
return false;
However, in this case there's an even easier way. You know that the only ways to get a sum of 7 on 2d6 are (1,6),(2,5),(3,4),(4,3),(5,2),(6,1). Set up a 6-length boolean array, roll your dice, and after each roll set res[result] to true. Then return (1-based array used for simplicity) ( (res[1] && res[6]) || (res[2] && res[5]) || (res[3] && res[4]) ).
ArrayIndexOutOfBoundsException means you are trying to access an element of the array that hasn't been allocated.
In your code, you create a new array d of length diceCount, but then you genDice() on always 6 elements.

Program Terminates Before Reaching Essential Code

A little background, I saw a question on here a while back about creating a program that asks how many people are in the room, and then you 'interview' each person on their age, assign them to an age group, and then print their age group and the amount of people in that age group. I decided to take a shot at it off of needing an idea for a practice program, unfortunately the code terminates before getting the first for statement and i'm not exactly sure why. I assume it would be a syntax error but I honestly have no idea, so any help is greatly appreciated.
import java.util.Scanner;
public class UnkownProjects {
public static void main(String[] args){
Scanner stringInput = new Scanner(System.in);
Scanner numInput = new Scanner(System.in);
System.out.println("How many people are in the room?");
int amountOfPeople = numInput.nextInt();
int[] totalPeople = new int[amountOfPeople];
System.out.println("Test");
for(int index = 0; index == totalPeople.length; index++){
System.out.println("Please enter an age for each person in the room:");
int ageOfPerson = numInput.nextInt();
ageOfPerson = totalPeople[index];
System.out.println("Test");
}
for(int index = 0; index == totalPeople.length; index++){
if(totalPeople[index] < 20 && totalPeople[index] > 0){
int[] underTwenty = null;
underTwenty[index] = totalPeople[index];
System.out.println("Test");
}
}
}
}
I also know the spacing is a bit off but I just copy/pasted and tried to make it look pretty for you all, so don't worry. Oh and the 'println' statements were just there to check and see where the program terminates.
Output:
How many people are in the room?
(A number you would've entered here)
Test
Ninja Edit:
Decided that I should come back to this post and place the finished code here for anyone who comes across this question and would like to take a look at the finished product.
import java.util.InputMismatchException;
import java.util.Scanner;
public class InterviewClass {
public static void main(String[] args){
try{
Scanner numInput = new Scanner(System.in);
System.out.println("How many people are in the room? (Ex: 5, 10, 24)");
int totalPeopleInRoom = numInput.nextInt();
int[] agesOfPeopleInRoom = new int[totalPeopleInRoom];
int youngPeople = 0, middleAged = 0, oldPeople = 0, deadPeople = 0;
System.out.println("Please enter an age for " + totalPeopleInRoom + " people (Ex: 17, 21, 45):");
for(int index = 0; index < agesOfPeopleInRoom.length; index++){
int tempAgePlaceHolder = numInput.nextInt();
agesOfPeopleInRoom[index] = tempAgePlaceHolder;
if((index + 1) == (totalPeopleInRoom/2)){
System.out.println("Half way there!");
}
}
System.out.println("Age Group\tAmount In Group");
for(int index = 0; index < agesOfPeopleInRoom.length; index++){
if(agesOfPeopleInRoom[index] < 30 && agesOfPeopleInRoom[index] > 0){
youngPeople = youngPeople + 1;
}
if(agesOfPeopleInRoom[index] < 60 && agesOfPeopleInRoom[index] > 30){
middleAged = middleAged + 1;
}
if(agesOfPeopleInRoom[index] < 115 && agesOfPeopleInRoom[index] > 60){
oldPeople = oldPeople + 1;
}
else if(agesOfPeopleInRoom[index] < 0 || agesOfPeopleInRoom[index] > 115){
deadPeople = deadPeople + 1;
}
}
System.out.println("Young People:\t" + youngPeople);
System.out.println("Middle Aged:\t" + middleAged);
System.out.println("Old People:\t" + oldPeople);
System.out.println("Dead People:\t" + deadPeople);
System.out.print("Total People:\t");
System.err.println(totalPeopleInRoom);
}catch(InputMismatchException inputException){
System.err.println("[ERROR] Wrong type of input used: " + inputException);
}
}
}
This is a bad for loop: for(int index = 0; index == totalPeople.length; index++)
Instead do: for(int index = 0; index < totalPeople.length; index++)
Let's break the for loop down:
The first part of the loop, int index = 0 is the initial condition. It tells the loop what the index should be set to when the loop starts.
The 2nd item in the for loop, in your loop you have index == totalPeople.length, is the condition statement that tells the for loop whether to keep looping if true or to stop looping if false. Your statement will be false when the loop tries to begin, and so the loop will never begin. So this is where your problem is. Instead you want to tell it to continue looping as long as the index is less than the length of the array, or in Java, index < totalPeople.length.
The 3rd item in the loop, here index++, tells the loop what to do with the index at the completion of each loop. Here you're telling it to increase by one, which is good.
The for loop condition must be true for it to iterate; it breaks out when it's false. In your case, it's false right away, so it never executes.
Instead of
for(int index = 0; index == totalPeople.length; index++){
try
for(int index = 0; index < totalPeople.length; index++){
And similarly for the other for loop.
In the Java tutorial on for loops, it states this:
When the termination expression evaluates to false, the loop terminates.
for(int index = 0; index == totalPeople.length; index++){
The second part in the parentheses is not a stopping condition, it is a check to continue. Use:
for(int index = 0; index < totalPeople.length; index++){
for(int index = 0; index == totalPeople.length; index++) should be
for(int index = 0; index < totalPeople.length; index++)
otherwise the boolean condition is evaluated to false and hence the loop doesn't execute
You should read this.
The general form of the for statement can be expressed as follows:
for (initialization; termination;
increment) {
statement(s) }
When using this version of the for statement, keep in mind that:
1. The initialization expression initializes the loop; it's executed once, as the loop begins.
2. When the termination expression evaluates to false, the loop terminates.
3. The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment
or decrement a value.
Your for loops are saying
Continue doing this code while index is equal to the arrays length
What you mean to say is continue doing this code while index is less than the arrays length

Categories