import java.util.Scanner;
public class maxnuminarray {
public static void main(String[] args) {
int temp;
System.out.print("please insert the size for array:");
Scanner input = new Scanner(System.in);
int size = input.nextInt();
int[] nums = new int[size];
for (int i = 0; i < size; i++) {
System.out.print("please insert your desired nums:");
nums[i] = input.nextInt();
}
for (int i = 1; i < size; i++)
for (int j = 0; j < size - i; j++)
if (nums[i] > nums[i + 1]) {
temp = nums[i];
nums[i] = nums[i + 1];
nums[i + 1] = temp;
}
System.out.print(nums[size - 1]);
}
}
Though it gets all the values for the array, it still doesn't print the max number which is the last num in the array.
The error I get for size=5:
Exception in thread "main": java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at maxnuminarray.main(maxnuminarray.java:15)
Once you read in the values, iterate over the array like this.
int max = Integer.MIN_VALUE;
for (int n : nums) {
max = Math.max(max, n);
}
You're trying to get a value with an index that doesn't exist. For instance, at if (nums[i] > nums[i + 1]). Let's say you have 3 numbers in total, your array size will be 3, but your index starts at 0.
Index 0
Index 1
Index 2
5
10
21
If you try to get i + 1 when i = 2 you get an error since i = 3 does not exist.
Also, if you're trying to get the largest number out of the array, you only need to go through the array once.
int[] nums = new int[]{1, 10, 3};
int max = nums[0];
for (int i = 1; i < nums.length; i++)
if (max < nums[i])
max = nums[i];
Or you can use Collections with the Integer[] array.
int max = Collections.max(Arrays.asList(num));
If you are just looking to find the maximum in the array, #Nouredine's code should do the trick.
Your code is comparing consecutive numbers one by one through the array, and swapping them in a bubble sort kind of way.
But if you are really looking to move the maximum in the array to the last position in the array, you can use this piece of code.
The issue in your code is you are accessing 5th index in an array of size 5, where only 0,1,2,3,4 are allowed.
for (int i = 1; i < size; i++)
if (nums[i - 1] > nums[i]) {
temp = nums[i - 1];
nums[i - 1] = nums[i];
nums[i] = temp;
}
}
import java.util.Scanner;
public class maxnuminarray {
public static void main(String[] args) {
int temp;
System.out.print("please insert the size for array:");
Scanner input = new Scanner(System.in);
int size = input.nextInt();
int[] nums = new int[size];
for (int i = 0; i < size; i++) {
System.out.print("please insert your desired nums:");
nums[i] = input.nextInt();
}
int max = nums[0];
for (int i = 1; i < size; i++)
if(max < nums[i])
max = nums[i];
}
System.out.println("Max " + max);
}
Related
I am taking 10 elements and performing a bubble sort on them. I want to add an algorithm that repeats the sort until no swaps are needed to make this more efficient.
Essentially I want to:
repeat until no swaps done in a pass
For elements 1 to (n-1)
compare contents of element value 1 with the contents of the next value
if value 1 is greater than value 2
then swap the values
This is what I have done so far :
{
//create array
int[] iList = new int[10];
Scanner sc = new Scanner(System.in);
//takes in array input for 10 numbers
System.out.println("Enter a array of numbers ");
for(int i = 0; i< 10; i++ )
{
int num = i + 1;
System.out.println("Enter number " + num);
iList[i] = sc.nextInt();
}
//Bubble sorts the array
System.out.println("The array =");
for(int a = 0; a < iList.length; a++ )
{
for(int b = a+1; b < iList.length; b++)
{
if(iList[a] > iList[b])
{
int iTemp = iList[a];
iList[a] = iList[b];
iList[b] = iTemp;
}
System.out.println("Progress = " + Arrays.toString(iList) );
}
}
} ```
Here is my implementation :
public static void sort(int[] nums) {
boolean isSwapped;
int size = nums.length - 1;
for (int i = 0; i < size; i++) {
isSwapped = false;
for (int j = 0; j < size - i; j++) {
if (nums[j] > nums[j+1]) {
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
isSwapped = true;
}
}
if (!isSwapped) break;
}
System.out.println("Sorted Array: " + Arrays.toString(nums));
}
public class Bonus1{
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int[] numbers = new int[n];
for (int i = 0; i < n; i++ ) {
numbers[i] = i;
}
for (int i = 0; i < n; i++ ) {
int r = i + (int)(Math.random() * (n - i));
int tmp = numbers[i];
numbers[i] = numbers[r];
numbers[r] = tmp;
System.out.print(numbers[i]);
}
int min = Integer.MAX_VALUE;
int count = 0;
while(data.hasNext()){
int y = data.nextInt();
if(y < min){
min = y;
count += 1;
}
}
System.out.println(count);
}
}
this code isn't complete, the first 2 for-loops will generate an array between 0 to a given number in the commandline -1
So for example java Bonus1 10 would first generate an array between 0-9 and then it will shuffle these numbers around so that it creates a random permutation.
the while loop is something I've used before to read input and determine how many times a new lowest number is detected. so for example if I get the permutation 7 8 2 3 4 5 1 0 6 9 it will count 7 as the lowest, then 2 as the lowest and then 1 as the lowest and finally 0 as the lowest, making the total amount of times a new lowest number has been detected 4.
but this only works if I use inputs, I need to use the previously generated output as the input in the same file, is there a clever way to do that?
You should iterate for the array numbers like this.
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int[] numbers = new int[n];
for (int i = 0; i < n; i++) {
numbers[i] = i;
}
for (int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int tmp = numbers[i];
numbers[i] = numbers[r];
numbers[r] = tmp;
System.out.print(numbers[i]);
}
System.out.println();
int min = Integer.MAX_VALUE;
int count = 0;
for (int i = 0; i < n; ++i) {
int y = numbers[i];
if (y < min) {
min = y;
++count;
}
}
System.out.println(count);
}
output:
6457098123
3
First of all I'm sorry if there is any mistake in the title of this question. I just don't know how to put it in a question. The following code rolls a dice thousand times and displays how many times a number on the dice is rolled. I want to print the index of the largest number not the element.
import java.util.Random;
public class apples {
public static void main(String args[]){
Random rand = new Random();
int a[] = new int[7];
for(int i = 1; i<1001; i++){
++a[rand.nextInt(6) + 1];
}
System.out.println("Roll\tTimes");
for(int j=1; j<a.length; j++){
System.out.println(j + "\t\t" + a[j]);
}
int max = a[0];
for (int i : a) {
if (max < i) {
max = i;
}
}
System.out.println("The winning number is " + max);
}
}
EDIT:
I figured how to get the index but is there an easier way to do it?
import java.util.Random;
public class apples {
public static void main(String args[]){
Random rand = new Random();
int a[] = new int[7];
int winner = 0;
for(int i = 1; i<1001; i++){
++a[rand.nextInt(6) + 1];
}
System.out.println("Roll\tTimes");
for(int j=1; j<a.length; j++){
System.out.println(j + "\t\t" + a[j]);
}
int max = a[0];
for (int i : a) {
if (max < i) {
max = i;
}
}
for(int j=0; j<a.length; j++){
if(max==a[j]){
winner = j;
}
}
System.out.println("The winning number is " + winner);
}
}
You will not be able to get the index of the array (directly) if you use for-each loop (like how you did), rather you need to use normal for loop as shown below in the code with comments:
int max = a[0];
int maxIndex = 0;//take a variable & Initialize to 0th index
for (int i=0; i<a.length;i++) {//normal for loop, not for each
if (max < a[i]) {
max = a[i];
maxIndex = i;//capture the maxIndex
}
}
System.out.println(": maxIndex :"+maxIndex);//print the maxIndex
You have to change your foreach to indexed for loop and keep a track of index of largest number.
Change this part to
int max = a[0];
for (int i : a) {
if (max < i) {
max = i;
}
}
Change it with
int max = a[0];
int index = 0;
for (int j = 0, aLength = a.length; j < aLength; j++) {
int i = a[j];
if (max < i) {
max = i;
index = j;
}
}
System.out.println("The winning number is " + max);
System.out.println("The winning index is " + index);
This will print the lasrgest number in which roll it was achieved.
Here's the question:
Write a program that that reads ten integers into an array and
computes the sum of the array of values, except for the largest one.
(Hint: Find the difference between the sum and the largest value of the
array)
And this is the given sample that you have to achieve:
Please input 10 integers: 3 4 1 9 2 10 8 6 7 5
Sum without the max: 45
The program beneath is my personal attempt:
import java.util.Scanner;
public class SumWithoutMax {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.print("Please input 10 integers: ");
int [] x = new int [10];
for (int i = 0; i < x.length; i++) {
x[i] = in.nextInt();
}
int max = x[0];
int sum = 0-max;
for (int i = 0; i < x.length; i++) {
if(x[i] > max) {
max = x[i];
}
}
for (int i = 0; i < x.length; i++) {
sum = sum + x[i];
}
System.out.println("Sum without the max: " +sum);
}
}
And the result of my attempt is just like this:
Please input 10 integers: 3 4 1 9 2 10 8 6 7 5
Sum without the max: 52
What's wrong with the program actually? Can somebody help me find it out and teach me how to solve it? Thanks:)
Problem with your code is you are subtrating x[0] value (which assume max at initial).
Even You can achive the with single for-loop.
int max = x[0];
int sum = 0;
for (int i = 0; i < x.length; i++) {
if(x[i] > max) {
max = x[i];
}
sum = sum + x[i];
}
sum -=max;
You are subtracting the maximum before you know it. Move int sum = 0-max; after the loop that seeks it.
The first sum=0-max; is wrong because max is not known yet. You need to do it after you find the max.
for (int i = 0; i < x.length; i++) {
sum = sum + x[i];
}
sum -= max;
int sum = -max;
When loop find the maximum number.
Move this line:
int sum = -max;
after the loop that finds the max.
import java.util.Scanner;
public class SumWithoutMax {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.print("Please input 10 integers: ");
int [] x = new int [10];
for (int i = 0; i < x.length; i++) {
x[i] = in.nextInt();
}
int max = x[0];
int sum = 0;
for (int i = 0; i < x.length; i++) {
if(x[i] > max) {
max = x[i];
}
}
for (int i = 0; i < x.length; i++) {
sum = sum + x[i];
}
sum = sum - max;
System.out.println("Sum without the max: " +sum);
}
}
A possible answer in JAVA 8 :
Integer sum = Arrays.asList(3,4,1,9,2,10,8,6,7,5).stream().sorted(Comparator.reverseOrder()).skip(1).reduce(
0,(a, b) -> a + b);
OK, I have been at it for a long time now. I have looked after similar problems here in stack-overflow and I still can't make it work. I need to find the maximum values within an array and minimum values. Trying to find the minimum is the problem. I have literately tried everything from writing separate methods and so on and still the output in 0. Here is what I have tried:
import java.util.Scanner;
class ArrayMin {
public static void main(String args[]) {
#SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
int a[] = new int[10];
int max = a[0];
int min = a[0];
System.out.println("Enter elements of array :");
for (int i = 0; i < 10; i++) {
a[i] = scanner.nextInt();
if (i == 9)
break;
}
for (int i = 1; i < a.length; i++) {
if (a[i] > max)
max = a[i];
else if (a[i] < min)
min = a[i];
}
System.out.println("Result is max is :" + (max)); //if I input 1-10, output is 10
System.out.println("Result is min is :" + (min)); //whatever number I input the output is always 0
}
}
When you declare your array, it's initialized to all zeroes. Then you assign the min to your first element, which is zero. Presumably all values are >= to 0 once they're assigned, so the min is still zero, but the max is correct.
Establish your max and min after the for loop where you assign input values to the array.
for (int i = 0; i < 10; i++) {
a[i] = scanner.nextInt();
if (i == 9)
break;
}
// Moved HERE.
int max = a[0];
int min = a[0];
Replace this.
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
...
for (int i = 0; i < a.length; i++) {
if (a[i] > max)
max = a[i];
if (a[i] < min)
min = a[i];
}
...