My assignment is to edit the following code to use a while-loop instead of a for loop to find the maximum in an array.
public static void main(String[] args) {
int[] numbers = {23, 101, 8, 25, 77, 5};
int max = 0;
for(int i=0; i<numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
System.out.println(max);
}
So far, this is what I've been trying to do and have not come up with the solution.
public static void main(String[] args) {
int[] numbers = {23,101,8,25,77,5};
int i = 0;
int max = numbers[0];
while(i<=numbers.length) {
i=i+1;;
if (numbers[i] > max) {
max = numbers[i];
}
}
If anyone could provide me with some insight as to what I'm doing wrong I would appreciate it. I have little experience with while-loops.
Change the while condition slightly and move the i increment to after the actual loop body:
while(i < numbers.length) {
if (numbers[i] > max) {
max = numbers[i];
}
i = i + 1; // or simply i++;
}
Remove the <= in your while loop condition and move incrementing i to end of the loop.
while (i < numbers.length) {
if (numbers[i] > max) {
max = numbers[i];
}
i = i + 1;
}
The while loop is correct. Remove the double semicolon as that is a syntax error and use (sizeof(numbers.length)/sizeof(int)); line to obtain list length.
Related
I am given the array measurements[]. I am supposed to write a for loop that goes through all the numbers and each time a number maximum is reached, the variable maximum is replaced. In the code I have so far, the output is saying that it cannot find the symbol i, but I thought that was the symbol I am supposed to use within a for-loop. Here is my code:
double maximum = measurements[0];
for (i = 0; i < measurements.length; i++) {
if (array[i] > largest) {
largest = array[i];
}
}
System.out.println(maximum);
You can also do this using Java stream api :
double maximum = Arrays.stream(measurements).max();
System.out.println(maximum);
Or a more concise code:
double maximum = Double.MIN_VALUE;
for(double measurement : measurements) {
maximum = Math.max(maximum, measurement);
}
System.out.println(maximum);
Or, sort the array and return the last one
Arrays.sort(measurements);
System.out.println(measurements[measurements.length-1]);
you can try this -
class MaxNumber
{
public static void main(String args[])
{
int[] a = new int[] { 10, 3, 50, 14, 7, 90};
int max = a[0];
for(int i = 1; i < a.length;i++)
{
if(a[i] > max)
{
max = a[i];
}
}
System.out.println("Given Array is:");
for(int i = 0; i < a.length;i++)
{
System.out.println(a[i]);
}
System.out.println("Max Number is:" + max);
}
}
You have not declared i inside the for loop or before the for loop.
double maximum = measurements[0];
for (int i = 0; i < measurements.length; i++) { //You can declare i here.
if (array[i] > largest) {
largest = array[i];
}
}
System.out.println(maximum);
You can also declare i before the for loop also
I am trying to create a program that prints the highest integers from a collection of student's grades array, but the code keeps returning me the same values each time it returns me a value.
So far this is the code:
class BestGrades {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int grade[] = new int[6];
int best[] = new int[3];
System.out.println("Enter the student's grade...");
for(int i = 0; i < grade.length; i++){
grade[i] = sc.nextInt();
for(int a = 0; a < best.length; a++){
if(grade[i] > best[a]){
best[a] = grade[i];
}
}
}
for(int i = 0; i < best.length; i++){
System.out.println("Best degrees are: "+best[i]);
}
}
}
As I said, the code will always return me the same highest value 3x.
Pardon me for any mistakes, first time asking here.
for(int a = 0; a < best.length; a++){
if(grade[i] > best[a]){
for(int b = a + 1; b < best.length; b++){
best[b] = best[b - 1];
}
best[a] = grade[i];
break;
}
}
You have to keep a track of which is the lower grade in you best array an replace just that one
class BestGrades {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int grade[] = new int[6];
int best[] = new int[3];
System.out.println("Enter the student's grade...");
for(int i = 0; i < grade.length; i++){
grade[i] = sc.nextInt();
boolean better = false;
int lowerIndex = 0;
for(int a = 0; a < best.length; a++){
if(grade[i] > best[a]){
better = true;
}
if(best[a] < best[lowerIndex]){
lowerIndex = a;
}
}
if(better){
best[lowerIndex] = grade[i];
}
}
for(int i = 0; i < best.length; i++){
System.out.println("Best degrees are: "+best[i]);
}
}
}
I haven't tested it, but something like this should work. It finds the minimum value in your best array, and if the new value is greater than that, it is one of the best values and replaces that original min value. Similar to David's answer, but a little simpler.
// Start best values at negative infinite so that the worst grade
// is still better that what's initially stored
best = {Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE};
for(int i = 0; i < grade.length; i++){
grade[i] = sc.nextInt();
// find min value of the max values
// start by setting first value as the min
int minIndex = 0;
for(int a = 1; a < best.length; a++){
if(best[a] < best[minIndex]) {
minIndex = a;
}
}
// place new grade into best array if it is better
// than the worst best value
if(grade[i] > best[minIndex])
best[minIndex] = grade[i];
}
The way to attack a problem like this is to break it into smaller pieces. One way is top-down - when something looks too hard to do in-line, call a method (that doesn't exist) to do it. Then write that method.
for( grade : grades) {
replaceLowestIfHigher(grade, best);
}
Now we just need to write replaceLowestIfHigher():
public void replaceLowestIfHigher(int grade, int[] target) {
int indexOfLowest = findIndexOfLowest(target);
if(grade > target[indexOfLowest]) {
target[indexOfLowest] = grade;
}
}
... and now we have to write findIndexOfLowest():
public int findIndexOfLowest(int[] array) {
int indexOfLowest=0;
for(int i=1; i<array.length; i++) {
if(array[i] < array[indexOfLowest]) {
indexOfLowest = i;
}
}
return indexOfLowest;
}
The only problem with this is that you hunt through the destination array for the lowest value even though it's likely you've done it before for the same values. There are various ways you could store this knowledge - for example, you could create a class to manage the "best" array, that remembers where the lowest is, and only recalculates when the data changes:
public class BestGrades {
private int[] grades = new int[3];
private int indexOfLowest = 0;
public int[] getGrades() {
return grades;
}
public void replaceLowestIfHigher(int grade) {
if(grade > grades[indexOfLowest]) {
grades[indexOfLowest] = grade;
updateIndexOfLowest();
}
}
private void updateIndexOfLowest() {
indexOfLowest = 0;
for(int i=1; i<target.length; i++) {
if(grades[i] < grades[indexOfLowest]) {
indexOfLowest = i;
}
}
}
}
However, most mature Java programmers would use a sorted collection to achieve this.
You could try to solve this problem in a functional style. Using the previously described strategy:
iterate through array and find if current element is superior to one of the items in the best note array.
if so then find the smallest best note in the array and capture its position
copy the current item to the best note array using the position found in 2.
This is the functional alternative which can capture N best notes:
public static int[] findNHighest2(int[] array, int limit) {
return IntStream.range(0, array.length).boxed().collect(() -> new int[limit], (a, i) -> { // collect in array with specified size.
IntStream.range(0, limit).boxed().filter(j -> array[i] > a[j]).findFirst().ifPresent(k -> { // finding if there is an item larger than the best ones
int minPos = findMinPos(a, limit); // find the minimum of the best ones
a[minPos] = array[i]; // copy the new best item to our best item array
});
}, (a, i) -> {});
}
private static int findMinPos(int[] array, int limit) {
return IntStream.range(0, limit)
.reduce((i,j) -> array[i] > array[j] ? j : i)
.getAsInt();
}
Usage:
public static void main(String[] args) throws IOException {
int[] arr = {9, 3,1, 9, 2, 7, 11, 2, 1, -1, 100, 8, 9, 199, 2};
System.out.println(Arrays.toString(findNHighest(arr.clone(), 6)));
}
The result on the console:
[9, 199, 11, 9, 100, 9]
I'm trying to invoke the getScore() method in my StudentScore class to determine the min and max over elements in an ArrayList, within the printStat() method presented below. I'm getting an ArrayIndexOutOfBoundException. What does that mean, and how can I fix the problem?
public class ScoreCalculator{
private int[] scoreCounter;
ArrayList<StudentScore> scores ;
public ScoreCalculator(int maxScore) {
scoreCounter = new int[maxScore];
scores = new ArrayList<StudentScore>(maxScore);
}
public void printStat() {
System.out.println("Score Report for " + scores.size() + " Students ");
min = 0;
max = 0;
int j=0;
for ( j = 0; j < scores.size(); j++) {
if (scores.get(j).getScore() < scores.get(j - 1).getScore()) {
min = scores.get(j).getScore();
}
if (scores.get(j).getScore() > scores.get(j - 1).getScore()) {
max = scores.get(j).getScore();
}
}
System.out.println(min);
System.out.println(max);
}
If your loop starts form j=0, and you access the element at j-1 in the list, you will see where the issue is.
When j=0, you try to access -1. There is no index -1. Hence the error. Starting from j=1 solves this.
Does this help in any way?
please,
change from
for(j=0;j<scores.size();j++){
to
for(j=1;j<scores.size();j++){
You cannot find the min/max of a sequence by only comparing neighboring values.
You have to compare values to the min/max-so-far.
if (scores.isEmpty())
throw new IllegalStateException("No scores found");
int min = scores.get(0).getScore();
int max = min;
for (int j = 1; j < scores.size(); j++) {
int score = scores.get(j).getScore();
if (score < min)
min = score;
if (score > max)
max = score;
}
I am trying to display the odd numbers in an array, but only once per number (i.e. numbers[3] = 3,3,1; would only display 3 and 1 instead of 3, 3 and 1.)
this is the code that I have as of now, the program completely will create an with the specific length entered by the user and then will calculate the max min, and odd values in the array.
import java.util.Scanner;
public class ArrayLab
{
static Scanner input = new Scanner (System.in);
public static void main(String[] args)
{
System.out.println("Enter the number of numbers: ");
final int NUMBER_OF_ELEMENTS = input.nextInt();
double[] numbers = new double[NUMBER_OF_ELEMENTS];
System.out.println("Enter the numbers: ");
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
numbers[i] = input.nextDouble();
}
input.close();
double max = numbers[0];
double min = numbers[0];
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
if (numbers[i] > max)
{
max = numbers[i];
}
}
System.out.println("The max is: " + max);
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
if (numbers[i] < min)
{
min = numbers[i];
}
}
System.out.println("The min is: " + min);
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
if (numbers[i] % 2 != 0)
{
System.out.println ("The odd numbers are: " + numbers[i]);
}
}
}
}
thanks for any help.
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
if (numbers[i] % 2 != 0)
{
set.add(numbers[i]);
}
}
System.out.println ("The odd numbers are: " +set);
This can be done a lot simpler using Java8:
double[] d = Arrays.toStream(numbers).filter(d -> (d % 2) == 1).distinct().toArray();
for(double tmp : d)
System.out.println(tmp);
System.out.println("min: " + Arrays.toStream(numbers).min((a , b) -> new Double(a).compareTo(b)));
System.out.println("max: " + Arrays.toStream(numbers).max((a , b) -> (new Double(a).compareTo(b))));
For you're solution: you never eliminate repeating numbers, thus the duplicates remain in the array until you print all odd numbers and the maximum-number.
This elimination can be done in several ways:
Using Java8 as above
add all values to a Set, since these don't allow duplicate values
eliminate them in your own way (i won't provide any code for this since it's rather complicated to design an efficient solution for this)
Updated solution for what you need. And Please use a better coding standard. Do note the condition check !oddNumbers.contains(numbers[i]) is not very necessary as HashSet never takes any duplicate values.
import java.util.HashSet;
import java.util.Scanner;
public class ArrayLab {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter the number of numbers: ");
final int NUMBER_OF_ELEMENTS = input.nextInt();
double[] numbers = new double[NUMBER_OF_ELEMENTS];
System.out.println("Enter the numbers: ");
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
numbers[i] = input.nextDouble();
}
input.close();
HashSet<Double> oddNumbers = new HashSet<Double>(NUMBER_OF_ELEMENTS);
double max = numbers[0];
double min = numbers[0];
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
if (numbers[i] < min) {
min = numbers[i];
}
if (numbers[i] % 2 != 0 && !oddNumbers.contains(numbers[i])) {
oddNumbers.add(numbers[i]);
}
}
System.out.println("The max is: " + max);
System.out.println("The min is: " + min);
System.out.println("The odd numbers are: " + oddNumbers);
}
}
A more meaningful solution to your approach would be as follows:
int[] tempArray; //temporary array to store values from your original "array"
int count=0;
for(int i=0; i<numbers.length; i++) {
if(numbers[i]%2 != 0) {
count++;
}
}
tempArray = new int[count]; //initializing array of size equals to number of odd digits in your array
int j = 0;
for(int i=0; i<numbers.length; i++) {
boolean check = true;
for(int k=0; k<j; k++) {
if(tempArray[k] == numbers[i]) {
check = false; //this will prevent duplication of odd numbers
}
}
if(numbers[i]%2 != 0 && check) {
tempArray[j]=numbers[i];
j++;
}
}
//Now print the tempArray which contains all the odd numbers without repetition
A few people have mentioned sets, but there is a different way as well. Simply sort the array, then scan through it, checking each number against the last one printed. i.e.,
int lastPrinted = 0;
// Sort the array
Arrays.sort(numbers);
System.out.print("The odd numbers are: ");
// Scan through the array
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
// if it's odd and doesn't match the last one...
if (numbers[i] % 2 != 0 && numbers[i] != lastPrinted)
{
// ...print it and update lastPrinted
System.out.print( "" + numbers[i] );
lastPrinted = numbers[i];
}
}
System.out.println("");
As a side note, you really don't have to scan through the array twice to find your max and min, you can do that in one go.
I think you can use inbuilt hashmap class and its method to achieve the task without affecting the complexity of algorithm to any great extent .
import java.util.HashMap;
public class Hashing {
public static void main(String[] args) {
//declare a new hasmap
HashMap<Integer, Integer> map = new HashMap<>();
//consider Arr as your Array
int Arr[] = {3,3,1,4,5,5,7,8};
//traverse through the array
for(int i=0;i<Arr.length;i++){
//check if the required condition is true
if(Arr[i]%2==1){
/*now we insert the elements in the map but before
that we have to make sure that we don't insert duplicate values*/
if(!map.containsKey(Arr[i])){// this would not affect the complexity of Algorithm since we are using hashMap
map.put(Arr[i], Arr[i]);//We are storing the Element as KEY and as VALUE in the map
}
}
}
//now We can get these element back from map by using the following statement
Integer[] newArray = map.values().toArray(new Integer[0]);
//All the required elements are now present in newArray
for(int ele:newArray){
System.out.println(ele);
}
}
}
The following code is supposed to read through some numbers and put ' <== Smallest number' next to the smallest. What's my problem here? It doesn't seem to be working! Every time it seems to assign the wrong number as the minimum.
import java.util.ArrayList;
import java.util.Scanner;
public class arrayex1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<Integer>();
System.out.println("Enter numbers: ");
for (int i = 0; i < 10; i++) {
int num = input.nextInt();
numbers.add(num);
}
for (int i = 0; i < numbers.size(); i++) {
if (numbers.get(findMin(numbers)) == i) { // If the 'smallest' index value is equal to i.
System.out.println(numbers.get(i) + " <== Smallest number");
} else {
System.out.println(numbers.get(i));
}
}
}
public static int findMin(ArrayList<Integer> n) {
int min = 0; // Get value at index position 0 as the current smallest.
for (int i = 0; i < n.size(); i++) {
if (n.get(i) < min) {
min = i;
}
}
return min;
}
}
if (numbers.get(findMin(numbers)) == i) { // If the 'smallest' index value is equal to i.
By calling numbers.get() you fetch the value of the slot at i.
The variable min in findMin() is actually the index of the minimum number in n.
Change this:
if (n.get(i) < min)
to:
if (n.get(i) < n.get(min))
Store the return value of findMin() before entering the for loop:
final int min_idx = findMin(numbers);
for (int i = 0; i < numbers.size(); i++) {
if (min_idx == i) { // If the 'smallest' index value is equal to i.
System.out.println(numbers.get(i) + " <== Smallest number");
} else {
System.out.println(numbers.get(i));
}
}
You can use collection sort method for sorting an list. Documentation
After the sort first element will be the smallest one
Here is an improved, working sample (though without the Scanner inputs for easy testing):
public static void main(String[] args){
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(7);
numbers.add(3);
int minIndex = findMin(numbers);
for(int i = 0; i < numbers.size(); i++){
if(minIndex == i){ // If the 'smallest' index value is equal to i.
System.out.println(numbers.get(i) + " <== Smallest number");
}else{
System.out.println(numbers.get(i));
}
}
}
public static int findMin(ArrayList<Integer> n){
int minValue = Integer.MAX_VALUE; // Get value at index position 0 as the current smallest.
int minIndex = -1;
for(int i = 0; i < n.size(); i++){
if(n.get(i) < minValue){
minIndex = i;
}
}
return minIndex;
}
There was some confusion as to if the findMin method returned the minimum value, or the minimum index. It now returns the minimum index. findMin is also now called only once, not for every iteration in the loop, which is a little cleaner (and slightly faster).
if (n.get(i) < min)
should be:
if (n.get(i) < n.get(min))
See it
Just change the following code and it will work for sure.
**if (numbers.get(findMin(numbers)) == numbers.get(i))**
{ // If the 'smallest' index value is equal to i.
System.out.println(numbers.get(i) + " <== Smallest number");
}
and
public static int findMin(ArrayList<Integer> n)
{
int min = 0; // Get value at index position 0 as the current smallest.
for (int i = 0; i < n.size(); i++)
{
**if (n.get(i) < n.get(min))**
{
min = i;
}
}
return min;
}
You see the unexpected behavior because you don't obey the contract for List.get(). The method expects an index as argument and returns you the value. You should not compare the value returned by get() to an index.
Also, in your findMin() method you should initialize min to Integer.MAX_VALUE.