Reversing user input array in Java - java

I'm trying to shift the user number input from right to left. It seems to be working except for not registering the first number. I think because for the reverse portion I have count is 1. I've tried using 0 and vice verse, but it results in an error. Any ideas on how to shift the user numbers?
The desired output is the reverse of what the user inputs. Example: User inputs 3 numbers. 3.0 2.0 1.0. Reverse 1.0. 2.0. 3.0.
// import Scanner
import java.util.Scanner;
public class Arrays {
public static void main (String [] args){
int count=0;
//introduce Scanner
Scanner input = new Scanner(System.in);
//printout question asking for user input and use count as input variable
System.out.println("Please input the size of array");
count=input.nextInt();
//create array and connect count to it
double[] numbers = new double [count];
System.out.println("Please input "+ numbers.length+ " double numbers");
//create for loop for original number order
for ( count=0; count<numbers.length; count++){
numbers[count] = input.nextDouble();
System.out.print( +numbers[count] + " ");
}
//print out the reverse order
System.out.print("\n After Reverse Order " );
//create for loop for reversed number order
for (count = 1; count< numbers.length; count++){
numbers[count-1]=numbers[count];
System.out.println ( "\n"+ numbers[count] );
}
}
}

If you want to reverse the order of elements, that's REVERSE ORDER not SHIFT. "Shift" correctly would shift them all one to the right or left, either dropping the end element or or (possibly) rotating it round to the other end.
So first thing is, to know what you're actually talking about.
Reversing the order of integers in an array:
int i = 0;
int j = numbers.length - 1; // corresponding index at opposite end of array.
// stop when half the array has been swapped.. with the other half.
while (i < j) {
// swap between ends.
int swap = numbers[i];
numbers[i] = numbers[j];
numbers[j] = swap;
// advance indices.
i++; j--;
}

Try this:
Double[] numbers = new Double[count];
...
Collections.reverse(Arrays.asList(numbers));

Related

Why is the average of the scores I imput not showing?

I'm very new at Java, and somehow my code is not giving me the average, but it doesnt throw me errors, so I dont know where it's wrong.
System.out.println("Please enter the amount of students: ");
Scanner sc = new Scanner(System.in);
int len = sc.nextInt();
int students[] = new int[len];
for (int i = 0; i < students.length; i++) {
System.out.println("Enter the scores from the first examen of the student " + (i + 1) + " ");
students[i] = sc.nextInt();
}
System.out.println("The scores of the students are:" + Arrays.toString(students));
float scores[] = new float[len];
int sumScores = 0;
int count = 0;
for (int i = 0; i < scores.length; i++) {
scores[i] = sc.nextInt();
sumScores += scores[count];
int average = sumScores / len;
System.out.println("The average of all the scores are: " + average);
There are a couples things that don't make sense here. I think we can agree the average is equal to the sum of all elements divided by the number of elements.
In your for loop, you are iterating through the loop and using count as the index, instead of i, which is redundant already, but you also never increment count. So it's also incorrect. So, just use i - that's part of the reason we do a for loop this way instead of for element : list.
// this
sumScores += scores[count]; // this is essentially scores[0] over and over
// should become this
sumScores += scores[i];
Next, move your "summarizing" prints outside of the loops. You don't want to print this every time.
Next tip: call sc.nextLine() after every call to sc.nextInt(), because nextInt() does not consume the newline character.
I was going to give you a working block of code - however it's not clear to me if you want to have one exam per student, or multiple exams, and an average of averages or something. If you're casting to a float I assume you want decimal places - so maybe look up how to do that type conversion without losing precision and decide where the best place to make that cast is. Cheers.
If arrays and loops confuse you, you could also give functional programming a try.
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the amount of students: ");
int len = sc.nextInt();
double average = IntStream.generate(() -> {
System.out.println("Enter the scores from the first examen of the student");
return sc.nextInt();
}).limit(len).average().orElse(0.0);
System.out.println("The average of all the scores are: " + average);

How to traverse through a one dimensional array in java [duplicate]

This question already has answers here:
Finding the minimum value of int numbers in an array (Java)
(10 answers)
Closed 5 years ago.
This is my first question on this site.
Anyways i'm making a program that will prompt the user for how many grades to enter. Then prompt the user to enter grades between 0 and 100 and store them in a array. Finally traverse the array to find the highest grade entered and display it to the user.
The problem i'm encountering is i have no clue on how to traverse through an array to compare two indexs in a array.
import java.util.*;
public class HighestGrade {
public static void main(String[] args) {
//Declare and Initialize Arrays and Scanner
Scanner scan = new Scanner(System.in);
int num = 0;
int[] array1;
int highestgrade = 0;
//Prompt user on how many grades they want to enter
System.out.print("How many grades do you want to enter: ");
num = scan.nextInt();
array1 = new int[num];
for(int i = 0; i < array1.length; i++){
System.out.print("Enter grade out of 100: ");
array1[i] = scan.nextInt();
}
//Traverse the array to find the highest grade entered
for (int i = 0; array1[0] < array1[i]; i++){
System.out.print("Higher");
}
//Display the results to the user
System.out.print("The highest grade is " + highestgrade + ".");
//Close scanner
scan.close();
}
}
To traverse through an array you can use a loop. For loop or while loop or do while loop.
To traverse through an array and keep track of the highest value you can maintain a variable and update it after each iteration if a value larger than that is encountered.
Speaking in terms of code..
int max = arr[0];
for ( int i = 0; i < arr.length; i++) {
if (arr[i] > max)
max = arr[i];
}
System.out.println("Largest is : "+max);
Hope this helps..!!
Also you can use Recursion to traverse an array. But it is not recommended as it will lead to stack related issues..
Another approach to get the highest value without traversing can be seen like this..
Step 1 : Sort the array in ascending order
Step 2 : Highest value will be at the end of the array, Use it as highest value
In codes..
Arrays.sort(arr);
System.out.println("Highest Value is : "+arr[arr.length - 1]);
To traverse the array you need to change your for loop like this:
for (int i = 0; i < array1.length; i++){
// do something with array1[i]
}
Is actually what you already did to fill it. Just do the same to use its values. But there is an alternative to get the highest value, you can use Arrays.sort:
Arrays.sort(array1); // sort values in ascending order.
System.out.println(array1[array1.length-1]); // get the element in the last position (the greatest)

Modification of Bubblesort program with user input

I have created a program previously using the BubbleSort method that works to sort numbers in a list that already exists, however, I am having difficulty with trying to manipulate this program in order to allow a user to input the list of numbers to be sorted instead. So far I have:
import java.util.Scanner;
public class MedianValue {
public static void main(String[] args) {
//use scanner to input list of numbers to sort
Scanner scan = new Scanner(System.in);
int[] numbers = new int[] {scan.nextInt()};
//nested for loop
//outer loop just iterating
//inner loop going through and flipping
//checking if out of order (if statement)
int counter = 0;
//outer loop: keep doing this until it's sorted
for(int i = 0; i < numbers.length - 1; i = i + 1)
//put in a inner loop number.length times minus one because we don't want to swap the last element
for(counter = 0; counter < numbers.length - 1; counter = counter + 1)
{
if (numbers [counter] > numbers [counter + 1])
{
int temporary = numbers [counter];
numbers [counter] = numbers [counter + 1];
numbers [counter + 1] = temporary;
}
}
for(int i =0; i < numbers.length; i = i + 1)
{
System.out.print(numbers[i] + " ");
}
}
}
But, in this program, instead of sorting the inputted numbers, the program simply prints the first number that is inputted by the user. I am not sure if I need to move where my scanner function is placed, or add on to it within the loop for it to sort all of the numbers as I want it to do. I am lost on where to change the program if that is the case.
That's because int[] numbers = new int[] {scan.nextInt()}; is a single assigment. scan read a single input and assign to number[0].
You actually need to modify your code for scan to read n numbers and store in n-sized numbers.
something like.
int[] numbers = new int[scan.nextInt()];
for( int i = 0; i < numbers.length; i++)
numbers[i] = scan.nextInt();
The code int[] numbers = new int[] {scan.nextInt()}; will always create an array (not a List) of size 1.
Usually in these kinds of assignments you get n + 1 numbers, for example 5 3 6 2 4 1 would mean "I'm going to give you five numbers. Oh here they are: 3 6 2 4 and 1!"
You probably want something like int[] numbers = new int[scan.nextInt()]; - then loop from 0 to numbers.length to fill the array.

Class ArrayIndexOutOfBoundsException - trying to get rid of it

I am writing a program that will take user input for a random number and number of iterations. I am attempting to do a bubble sort on this (for my class I am required to do it with bubble and selection sorts). My initial code did fine till I worked to add in the portion to do iterations and then the selection sort. Now when I run my code, it will stop and give an error noted in the title of my post. The line it stops at is if randomArray[d]>randomArray[d+1] (the last line in the code below).
From what I have researched in my attempts to resolve this, it says the error is usually thrown when the array has been accessed by illegal index... or the index is negative or greater than the size of the array. I have attempted a few different things to fix this, but at the moment I am at a wall. If anyone can provide some direction, I would greatly appreciate it!
Thanks
Scanner input = new Scanner (System.in);
System.out.println("Enter a number please: ");
int n = input.nextInt();
//Get user input for number if iterations
System.out.println("Enter a number of iterations please: ");
int numIfor = input.nextInt();
//create array of random numbers
int[] randomArray = new int[n];
Random bubbleRandom = new Random();
//fill in the array of random numbers
for(int i=0; i < n; i++) {
randomArray[i] = bubbleRandom.nextInt(100);
}
//Printing the array before the sort
System.out.println("The numbers before the Bubble Sort: ");
for(int i=0; i < n; i++) {
System.out.print(randomArray[i] + " ");
}
System.out.println();
//Printing the array out after the Bubble Sort
int bubble = 0;
int sort = 0;
long startTime = System.currentTimeMillis();
for (int c=0; c < (numIfor - 1); c++)
{
for (int d=0; d < numIfor - c -1; d++)
{
if (randomArray[d]>randomArray[d+1])
{
bubble = randomArray[d];
randomArray[d] = randomArray[d+1];
randomArray[d+1] = bubble;
sort++;
}
}
}
long endTime = System.currentTimeMillis();
long runningTime = endTime-startTime;
System.out.println("The total number of iterations is: " + numIfor);
System.out.println("The total count of numbers sorted is: " + sort);
System.out.println("The total time elapsed was: " + runningTime);
System.out.println("The numbers after the Bubble Sort: ");
for(int i=0; i < n; i++){
System.out.print(randomArray[i] + " ");
}
}
}
What is probably happening is that d+1 is becoming larger than the last position of the array. You can make sure it only goes up to the end of the array by changing the last for loop as such:
The problem here is that you are looping to numIfor, which is a completely independent value from the length of the array (n). This means that if the user enters a numIfor and n, such that numIfor > n, then your code is bound to throw the exception.
The solution to this is using the actual length of the array as the limiter value instead, as such:
for (int c=0; c < randomArray.length-1; c++)
{
for (int d=0; d < randomArray.length-c-1; d++)
{
if (randomArray[d]>randomArray[d+1])
This is assuming that you want d to go through all the values of the array. But the real takeaway here is that you should always try to loop to less than the length of the array (the -1 is there because you are checking for array[d+1]). This works best if you are trying to reach all the values in the array because it guarantees that you don't go out of bounds.

Gets out of bounds exception whenever my column is larger than my rows

I have been beating my head against the wall with my code. I finally got my code to allow me to input whatever numbers the user desires depending on how many rows and columns they want, but for some reason whenever I try to type in a larger column number than row number, I get an error. I've read over my loop tens of times, inserting -1 where I think the program is over counting, but it still won't work. I'm assuming this is the appropriate way to write a multidimensional array when it is completely dependent on the user, but if not, please tell me how to make my code more efficient. Thanks!
public class MultiPractice {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompts user to insert desired rows and columns
System.out.print("Enter how many rows you want in your array: ");
int rowSize = input.nextInt();
System.out.print("Enter hwo many columns you want in your array: ");
int colSize = input.nextInt();
// Asks users to insert desired numbers for the multi-array
System.out.print("Enter " + (rowSize*colSize) + " integers: ");
// Creates the multidimensional array
int[][] multi = new int[rowSize][colSize];
// Runs the for loop to put numbers where they belong in array
for (int i = 0; i < multi.length; i++) {
for (int j = 0; j < multi[colSize].length; j++) {
multi[i][j] = input.nextInt();
System.out.print(multi[i][j] + " ");
}
System.out.println();
}
}
}
multi[colSize].length should be multi[0].length or multi[i].length (since you have a rectangular array, these have the same value).
multi[colSize].length is the length of row colSize. Therefore, if you have less than colSize+1 rows (since they start from 0), this is out-of-bounds.
It's .length that's screwing you up here. Multi[colSize].length is not the same as colSize; in fact, it's colSize + 1 (since length starts counting at 1).
My Solution: Instead of using multi.length, you can use i < rowSize. You can also swap out the multi[colSize] with < colSize.

Categories

Resources