I have some trouble when I try to code a program.
double max = 0, min = 0;
int i;
double array[] = new double[10];
Scanner input = new Scanner(System.in);
for (i = 0; i < 10; i++) {
System.out.println("Give the " + (i + 1) + " number");
array[i] = input.nextDouble();
}
for (i = 0; i < 10; i++) {
if (array[i] > max) {
max = array[i];
}
for (i = 0; i < 10; i++) {
if (array[i] < min) {
min = array[i];
}
}
}
System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);
When I type 10 numbers that include one largest number and one smallest number,
the result is
The Max is : largest number
The Min is : 0.0
Always the Smallest I get the 0.0 whatever I type. No 2 I will type, No 4 I will type as a smallest number (always on separate launch), every time I get 0.0.
Your initial value for minimum is zero, and I assume your data has nothing that is less than zero.
Try setting your min initial value to Double.MAX_VALUE
you Initializing max and min before entering number into the array , when tring to find the max and the min , first enter the numbers to the array then compare them with the array[0].
second thing is that you dont need to for loops to check whether you need to change max or min , you can do it in one for loop .
try this :
double array[] = new double[10];
int i;
Scanner input = new Scanner(System.in);
for (i = 0; i < 10; i++) {
System.out.println("Give the " + (i + 1) + " number");
array[i] = input.nextDouble();
}
double max = array[0], min = array[0];
for (i = 0; i < 10; i++) {
if (array[i] > max) {
max = array[i];
}
if (array[i] < min) {
min = array[i];
}
}
System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);
Two simple corrections:
You just have to set initialized min and max to some values in array. (e.g. array[0] for your problem)
there is no need to 3 for loops to find the min and max, just use one.
see below code:
int i;
double array[] = new double[10] ;
Scanner input = new Scanner (System.in) ;
System.out.println("Give the " + (1) + " number") ;
array[0] = input.nextDouble();
double max = array[0], min = array[0];
for (i = 1; i < 10; i++)
{
System.out.println("Give the " + (i+1) + " number") ;
array[i] = input.nextDouble();
if(array[i] > max)
max = array[i] ;
if (array[i] < min)
min = array[i];
}
System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);
Your curly braces are not proper. You are ending the max loop before the SYSOUT.
double max = 0, min = 0;
int i;
double array[] = new double[10] ;
Scanner input = new Scanner (System.in) ;
for (i = 0; i < 10; i++)
{
System.out.println("Give the " + (i+1) + " number") ;
array[i] = input.nextDouble();
}
max = array[0];
min = array[0];
for (i = 0; i < 10; i++) {
if (array[i] > max) {
max = array[i];
}
}
for (i = 0; i < 10; i++) {
if (array[i] < min) {
min = array[i];
}
}
System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);
Run this. It will give the proper result.
Related
import java.util.Arrays;
public class Swap
{
public static void main(String args[])
{
Scanner console = new Scanner(System.in);
System.out.print("What is the size of your array? ");
int myArray = console.nextInt();
int[] size = new int[myArray];
int sum = 0;
int max = 0;
int min = 100;
int temp = 0;
for (int i = 0; i < size.length; i++)
{
System.out.print("Array index " + (i) + ": ");
size[i] = console.nextInt();
sum += size[i];
if (size[i] > max) max = size [i];
if (size[i] < min) min = size [i];
}
System.out.println ("\nmaximum value is: " + max);
System.out.println ("\nminimum value is: " + min);
System.out.println (Arrays.toString(size));
temp = size[max];
size[max] = size[min];
size[min] = temp;
System.out.println (Arrays.toString(size));
}
}
I am having trouble swapping the min and max value in the array, I am able to find those values fine, and I even found a way to swap in with the temp variable, but I can't translate that into the array.
You're using max and min as array index to swap your values.That is not correct.Instead you've to keep min and max indexes,and use them to swap in the array. I suggest you to complete your code like that:
import java.util.Arrays;
public class Swap
{
public static void main(String args[])
{
Scanner console = new Scanner(System.in);
System.out.print("What is the size of your array? ");
int myArray = console.nextInt();
int[] size = new int[myArray];
int sum = 0;
int max = 0;
int min = 100;
int maxIndex=0;
int minIndex=0;
int temp = 0;
for (int i = 0; i < size.length; i++)
{
System.out.print("Array index " + (i) + ": ");
size[i] = console.nextInt();
sum += size[i];
if (size[i] > max){
max = size [i];
maxIndex=i;
}
if (size[i] < min) {
min = size [i];
minIndex=i;
}
}
System.out.println ("\nmaximum value is: " + max);
System.out.println ("\nminimum value is: " + min);
System.out.println (Arrays.toString(size));
temp = size[maxIndex];
size[maxIndex] = size[minIndex];
size[minIndex] = temp;
System.out.println (Arrays.toString(size));
}
}
Only the part for max and min.
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int iAtMax = -1;
int iAtMin = -1;
for (int i = 0; i < size.length; i++) {
if (iAtMax == -1 || max < size[i]) {
iAtMax = i;
max = size[i];
}
if (min <= size[i]) {
iAtMin = i;
min = size[i];
}
}
if (iAtMax != -1) {
int temp = size[iAtMax];
size[iAtMax] = size[iAtMin];
size[iAtMin] = temp;
}
You could initialize max and min so that an update in the loop always updates. Then you have to use <= max resp. >= min to update the indices. (See min above) or you can check whether there already is a max and min.
If the array is empty (or size 1) you cannot (resp. need not) swap.
I'm getting an error message (java.util.NoSuchElementException) in thread main when attempting to compile the following code with the input 3, then 4, 5, and 7. I've tried to tweak the code, but there's something I'm missing. I was thinking it may be due to my use of arrays since I am just learning how to use those, but I've tried to look closely at them and I didn't see anything I did wrong, but I definitely missed something. Any help would be appreciated. Thanks!
import java.util.Scanner;
public class ArrayMethods2 {
public static int[] findMinAndMax(int[] x) {
int i;
int min = x[0];
int max = x[0];
for (i = 0; i < x.length; i++) {
if (x[i] < min) {
min = x[i];
}
if (x[i] > max) {
max = x[i];
}
}
int [] minAndMax = new int[2];
minAndMax[0] = min;
minAndMax [1] = max;
return minAndMax;
}
public static double averageWithDrop(int[] x) {
int i;
int min = x[0];
int minIndex1 = 0;
int minIndex2 = 0;
int sum = 0;
for (i = 0; i < x.length; i++) {
if (x[i] < min) {
minIndex1 = i;
}
}
for (i = 0; i < x.length; i++) {
if (x[i] < min) {
if (i != minIndex1)
minIndex2 = i;
}
}
for (i = 0; i < x.length; i++) {
if (i == minIndex1) {
sum = sum + 0;
}
else if (i == minIndex2) {
sum = sum + 0;
}
else {
sum = sum + x[i];
}
}
double average = sum / (x.length - 2);
return average;
}
public static void main (String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.print("How many numbers would you like to enter? (must be at least 3) ");
int userValue = scnr.nextInt();
System.out.println(userValue);
while (userValue < 3) {
System.out.println("Invalid value, must be at least 3. Please try again ");
userValue = scnr.nextInt();
System.out.println(userValue);
}
int x = 0;
int indexVal;
int [] userArray = new int [userValue];
while (x <= userValue) {
System.out.print("Enter value for index " + x + ": ");
indexVal = scnr.nextInt();
System.out.println(indexVal);
userArray[x] = indexVal;
x++;
}
int [] minAndMaxVal = new int [2];
minAndMaxVal = findMinAndMax(userArray);
System.out.println("Min value: " + minAndMaxVal[1] + ", Max value: " + minAndMaxVal[2]);
double avg = averageWithDrop(userArray);
System.out.println("Average excluding two lowest values: " + avg);
}
}
Running your code, I did not get any NoSuchElementException, however I got IndexOutOfBoundsException. Check the class your are running.
Please remember arrays are 0 based.
In the main method change while (x <= userValue)to while (x < userValue)
Again, arrays are 0 based, change:
System.out.println("Min value: " + minAndMaxVal[1] + ", Max value: " + minAndMaxVal[2]);
to
System.out.println("Min value: " + minAndMaxVal[0] + ", Max value: " + minAndMaxVal[1]);
There are few problems in the code :
Update this (x <= userValue) to (x<userValue) , else it will give array index out of bounds exception
Start the for loop in minMaxFunction from 1 , since you have already stored the value of arr[0] to min and max like below . This is just an optimization in the code.
for (i = 1; i < x.length; i++) {
if (x[i] < min) {
min = x[i];
}
if (x[i] > max) {
max = x[i];
}
}
This line in main method should have index 0 and index 1 . There is no index 2 since you have declared the array of length 2 , else it will give array index out of bounds exception
minAndMaxVal = findMinAndMax(userArray);
System.out.println("Min value: " + minAndMaxVal[0] + ", Max value: " + minAndMaxVal[1]);
I'm trying to find the largest and smallest number in my array however, it only seems to print out the largest and not the smallest, I'm fairly new so all help is appreciated, thank you.
import java.util.Scanner;
public class Ex1 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int[] numbers = new int[11];
int largest = numbers[0];
int smallest = numbers[0];
System.out.println("Enter 10 numbers = ");
for (int i = 1; i < numbers.length; i++) {
numbers[i] = keyboard.nextInt();
System.out.println("Number " + i + " = " + numbers[i]);
for (int y = 1; y < numbers.length; y++) {
if (numbers[y] > largest)
{
largest = numbers[y];
}
}
for (int x = 1; x < numbers.length; x++)
{
if (numbers[x] < smallest)
{
smallest = numbers[x];
}
}
}
System.out.println("Largest number = " + largest);
System.out.println("Smallest number = " + smallest);
} // main
} // class
It doesn't print out the smallest number because you set it in the beginning to 0, set it to Integer.MAX_VALUE instead.
Also to make sure your program works for negative numbers, set the value of largest to Integer.MIN_VALUE.
int smallest = numbers[0];
This is creating problem. This assigns value 0 in the beginning hence you are not getting smallest number.
Also your test dataset must be containing only positive numbers.
Solution
int largest = Integer.MIN_VALUE;
int smallest = Integer.MAX_VALUE;
There are some code issues other than correctly finding min and max of input numbers.
You don't have to write nested for loops for this. Check below code and that will simply find you min and max numbers,
Scanner keyboard = new Scanner(System.in);
int[] numbers = new int[11];
int largest = numbers[0];
int smallest = numbers[0];
System.out.println("Enter 10 numbers = ");
for (int i = 1; i < numbers.length; i++) {
numbers[i] = keyboard.nextInt();
System.out.println("Number " + i + " = " + numbers[i]);
if (i == 1) {
largest = numbers[i];
smallest = numbers[i];
}
if (numbers[i] > largest) {
largest = numbers[i];
}
if (numbers[i] < smallest) {
smallest = numbers[i];
}
}
System.out.println("Largest number = " + largest);
System.out.println("Smallest number = " + smallest);
try this,
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int[] numbers = new int[10];
System.out.println("Enter 10 numbers = ");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = keyboard.nextInt();
System.out.println("Number " + (i + 1) + " = " + numbers[i]);
}
int largest = numbers[0];
int smallest = numbers[0];
for (int y = 0; y < numbers.length; y++) {
if (numbers[y] >= largest)
{
largest = numbers[y];
}
if (numbers[y] <= smallest)
{
smallest = numbers[y];
}
}
System.out.println("Largest number = " + largest);
System.out.println("Smallest number = " + smallest);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the max number:");
int max = input.nextInt();
int[]arr1 = new int[max+1];
int[]arr2 = new int[max+1];
int[]arr3 = new int[max+1];
int i = 1;
// For-loop to calculate
for (i = 1;i <= max;i++)
arr1[i] = arr1[i-1] + i;
i = 1;
// While-loop to calculate
while (i <= max) {
arr2[i] = arr2[i-1] + i;
i++;
}
i = 1;
// Do-While-loop to calculate
do
arr3[i] = arr3[i-1] + i;
while (++i <= max);
for (i = 0; i <= max; i++)
System.out.println("Arr1 " + arr1[i] + " Arr2 " + arr2[i] + " Arr3 " + arr3[i]);
System.out.println("Sum of All is " + arr1[max]);
}
I have this for doing sums but I am stuck when it comes to getting it to square
You seem to have 3 identical array objects?
Anyway, it's pretty straightforward to print the square of all numbers from 1 to max:
for (int i = 1; i <= max; i++) {
System.out.println(i + ": " + i * i);
}
There are also some fun ways to sum up the numbers from 1 to max, such as:
System.out.println(IntStream.range(1, max + 1).sum());
I'm new to Java and I'm trying to make a program that allows the user to input 100 numbers and if the user writes '0', then the program is suppose to print the smallest, largest, sum and all the numbers. I got all that to work but not to exit and print it all. My teacher said something about using a while loop, but how is that possible when you have a for loop?
Regards
public static void main(String[] args) {
int[] list = new int[100];
int min = 0;
int max = 0;
int sum = 0;
boolean first = true;
Scanner scan = new Scanner(System.in);
while(list[i] != 0) {
for (int i = 0; i < list.length; i++) {
System.out.print("Enter number (0 to exit) " + (1 + i) + ":");
list[i] = scan.nextInt();
}
for (int i = 0; i < list.length; i++) {
if (first == true) {
min = list[i];
first = false;
}
if (list[i] < min) {
min = list[i];
}
else if (list[i] > max) {
max = list[i];
}
sum = list[i] + sum;
}
if (list[i] == 0) {
System.out.print("Numbers are: " + list[0] + ", ");
for (int i = 1; i < list.length; i++)
System.out.print(list[i] + ", ");
System.out.println();
System.out.println("Smallest number is: " + min);
System.out.println("Largest numeber is: " + min);
System.out.println("Sum is: " + sum);
}
}
}
}
You only need one while loop to do this and additionally a for loop just to print the array if you want:
Scanner scan = new Scanner(System.in);
int i = 0;
int sum = 0;
int maxValue = Integer.MIN_VALUE;
int[] history = new int[100];
System.out.println("INPUT:");
int option = scan.nextInt();
while (option != 0 && i <= 100)
{
if (option > maxValue)
maxValue=option;
sum += option;
history[i] = option;
option = scan.nextInt();
i++;
}
System.out.println("OUTPUT: \n" + "SUM: " + sum + "\n MAX VALUE: " + maxValue);
for (int x : history)
System.out.print(x + "");
Here's the body of the method which will do what you've been asked. I have not used a while loop (but in fact, a for-loop is a kind of a while-loop internally).
int size = 100; // Set the number of numbers to input.
int[] list = new int[size]; // Create an array with 'size' elements.
int min = Integer.MAX_VALUE; // Set the highest possible integer as start value.
int max = 0; // Set the minimum to zero, assuming that the user won't input negative numbers.
int sum = 0; // Initialize the sum of the numbers in the list.
Scanner scan = new Scanner(System.in);
for (int i = 0; i < size; i++) { // Run 'size' times the process of inputting a number.
System.out.print("Enter number (0 to exit) " + (i + 1) + ": ");
int number = scan.nextInt();
if (number == 0) { // Quit program if input equals '0'
System.out.println("Exiting...");
break;
}
list[i] = number; // Add the current number to the list
sum += number; // Add the number to the total
if (number < min) { // If the number is smaller than the previous one, set this number as the smallest
min = number;
}
if (number > max) { // If the number is greater than the previous smallest number, set this number as the greatest
max = number;
}
}
// Output all numbers in the list
for (int i = 0; i < list.length; i++) {
if (list[i] != 0) {
System.out.print((i == 0 ? "" : ", ") + list[i]);
}
}
// You see the snippet (i == 0 ? "" : ", ")
// That is a shorthand if-else statement:
// If i equals 0, then "" (empty string), else ", " (comma and space).
// The statement
// System.out.print((i == 0 ? "" : ", ") + list[i])
// is the same as
// if (i == 0) {
// System.out.println("") + list[i];
// }
// else {
// System.out.println(", ") + list[i];
// }
System.out.println("Smallest number is: " + min);
System.out.println("Largest numeber is: " + max);
System.out.println("Sum is: " + sum);
You have muddled code. Better to use a pattern like this:
while (true) {
// read next
if (input == 0)
break;
}