Bubble sorting issues in java - java

So I currently am having, this issue when I run my program it repeats the second display line. ("unsorted line")
I also am having trouble with the alignment when I run the program
What I need this program to do:
Generate 10 random integer numbers between 1 and 100, and place each random number in a different element of a single-dimension array starting with the first number generated.
Locate the largest of the 10 numbers and display its value.
Display the array's contents in the order the numbers are initially inserted. This is called an unsorted list.
Using the bubble sort, now sort the array from smallest integer to the largest. The bubble sort must be in its own method; it cannot be in the main method.
This is what I currently have programmed.. I just need help on adjustments when its ran.
import java.util.Arrays;
public class Chpt7_Project2 {
//Ashley Snyder
public static void main(String[] args) {
//create an array of 10 integers
int[] list = new int[10];
//initialize array of 10 random integers between 0 and 100
for (int i = 0; i < list.length; i++) {
list[i] = (int) (Math.random() * 100 + 1);
}
//Find the maximum of the list of random numbers generated
int maximum = -1;
int minimum = 999;
for (int i = 0; i < list.length; i++) {
if (maximum < list[i])
maximum = list[i];
if (minimum > list[i])
minimum = list[i];
}
//Display the maximum from the randTen array
System.out.println("The largest value is: " + maximum);
//Display the unsorted list of numbers from the randTen array
for (int i = 0; i < list.length; i++) {
System.out.print(list[i] + "The unsorted list is: ");
}
//Display the sorted array numbers
bubbleSort(list);
System.out.println("The sorted list is: " + Arrays.toString(list) + " ");
}
public static void bubbleSort(int[] list) {
//Sort randomly generated integers in randArray from lowest to highest
int temp;
for (int i = list.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (list[j] > list[j + 1]) {
temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
}
}

You're really close to making this work. Please notice that System.out.print("The unsorted list is: " + list[i]); is inside a loop. That means that "The unsorted list is" will print 10 times. You probably want to move the label part of the output before the loop while keeping the list[i] inside the loop. Then don't forget to put a System.out.println after the loop finishes. You will then see that each item is pushed together. To fix that just put list[i] + " " as part of the print.
It appears that your are a bit confused about two separate items. First is writing (printing) to the console. System.out.print("whatever"); and System.out.println("something");. The first one will write a line of text to the console but will not go to the next line. The second one writes and then goes (advances) to the next line.
Secondly, and really importantly is for. Whenever you see for (...) { whatever }; think that something (the whatever) is going to be repeated. The number of times that it will repeat is mostly / usually determined by the part in parenthesis. The thing that is repeated is between the braces {}.
I think this is what you want:
//Display the unsorted list of numbers from the randTen array
System.out.print("The unsorted list is: ");
for (int i = 0; i < list.length; i++) {
System.out.print(list[i] + " ");
}
System.out.println();
Please notice that the first System.out.print does not output to a new line, nor does the second one. The second System.output.print is repeated 10 times. Finally, System.out.println() starts a new line of output.

Related

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.

How to calculate average from command line? Homework excercize

I have to make a program which calculates the average, the modal value and the median of some numbers insert on command line. The numbers have to be in a range [1,10] I can't understand why it stops. Where am I wrong? This is the code:
import java.lang.Integer;
import java.util.Arrays;
class Stat{
public static void main(String[] args){
int i,median,modalValue = 0;
float average, sum = 0;
int repetition[] = new int[args.length];
Integer allNumbers[] = new Integer[args.length];
//check numbers range
try{
//reading args from command line
for( i = 0; i < args.length; i++){
//if not in range --> exception
if(Integer.parseInt(args[i]) < 1 || Integer.parseInt(args[i]) > 10)
throw new Exception("Exception: insert number out of range. Restart the programm.");
//put numbers in an array
allNumbers[i] = new Integer(args[i]);
}
//sorting the array
Arrays.sort(allNumbers);
//calculate average
for( i = 0; i < allNumbers length; i++ ){
sum += allNumbers[i];
}
average = sum / (i + 1) ;
System.out.println("Average: " + average);
//calcolate modal value (most frequent number)
for( i = 0; i < repetition.length; i++){ //counting numbers occurrences
repetition[allNumbers[i]]++;
}
for( i = 1; i < repetition.length; i++){ //checking which number occurrences the most
if(repetition[i] >= repetition[i-1])
modalValue = repetition[i];
}
System.out.println("Modal Value: " + modalValue);
//calculating median value
if((allNumbers.length) % 2 == 0){ //even
median = allNumbers.length/2;,
}else{ //odd
median = (allNumbers.length/2) + 1;
}
System.out.println("Median: " + allNumbers[median]);
}catch(Exception e) { //out of range
System.out.println(e.getMessage());
}
}
}
First Step
You will get more information about errors if you remove that try/catch. By catching the exception and printing out just its message, you are missing out on its stack trace, which will tell you exactly which line the error occurs on.
So firstly, remove the try/catch, and allow your main method to throw exceptions by changing its declaration to: public static void main(String[] args) throws Exception {. Compile and run it again, to allow the exception to crash the program.
What type of exception is thrown? What line number does it say?
Second Step
Next, let's look at some of your code that helps calculate the modal value:
int repetition[] = new int[args.length];
for (i = 0; i < repetition.length; i++) {
repetition[allNumbers[i]]++;
}
The first line will create an array with the same number of elements as numbers provided on the command line. For example, if you provide numbers 5 8 9, that's three numbers, so the array will have three elements. Array indexes start at zero, so the indexes will be 0, 1 and 2.
The for loop will then take the first number, allNumbers[0] which in my example is a 5, and increment the value in the array at index 5. This causes an exception because the array does not have an index 5. That would be "outside the bounds" of the array.
The problem here is how you create the repetition array. Creating it with only three elements is not enough. You need to think about how to create it so that it will be able to handle any number in the range of [1, 10] that you were given.

Print sum of unique values of an integer array in Java

I am yet again stuck at the answer. This program prints the unique values but I am unable to get the sum of those unique values right. Any help is appreciated
public static void main(String args[]){
int sum = 0;
Integer[] numbers = {1,2,23,43,23,56,7,9,11,12,12,67,54,23,56,54,43,2,1,19};
Set<Integer> setUniqueNumbers = new LinkedHashSet<Integer>();
for (int x : numbers) {
setUniqueNumbers.add(x);
}
for (Integer x : setUniqueNumbers) {
System.out.println(x);
for (int i=0; i<=x; i++){
sum += i;
}
}
System.out.println(sum);
}
This is a great example for making use of the Java 8 language additions:
int sum = Arrays.stream(numbers).distinct().collect(Collectors.summingInt(Integer::intValue));
This line would replace everything in your code starting at the Set declaration until the last line before the System.out.println.
There's no need for this loop
for (int i=0; i<=x; i++){
sum += i;
}
Because you're adding i rather than the actual integers in the set. What's happening here is that you're adding all the numbers from 0 to x to sum. So for 23, you're not increasing sum by 23, instead, you're adding 1+2+3+4+5+....+23 to sum. All you need to do is add x, so the above loop can be omitted and replaced with a simple line of adding x to sum,
sum += x;
This kind of error always occures if one pokes around in low level loops etc.
Best is, to get rid of low level code and use Java 8 APIs:
Integer[] numbers = {1,2,23,43,23,56,7,9,11,12,12,67,54,23,56,54,43,2,1,19};
int sum = Arrays.stream(numbers)
.distinct()
.mapToInt(Integer::intValue)
.sum();
In this way there is barely any space for mistakes.
If you have an int array, the code is even shorter:
int[] intnumbers = {1,2,23,43,23,56,7,9,11,12,12,67,54,23,56,54,43,2,1,19};
int sumofints = Arrays.stream(intnumbers)
.distinct()
.sum();
So this is my first time commenting anywhere and I just really wanted to share my way of printing out only the unique values in an array without the need of any utilities.
//The following program seeks to process an array to remove all duplicate integers.
//The method prints the array before and after removing any duplicates
public class NoDups
{
//we use a void static void method as I wanted to print out the array without any duplicates. Doing it like this negates the need for any additional code after calling the method
static void printNoDups(int array[])
{ //Below prints out the array before any processing takes place
System.out.println("The array before any processing took place is: ");
System.out.print("{");
for (int i = 0; i < array.length; i++)
{
System.out.print(array[i]);
if (i != array.length - 1)
System.out.print(", ");
}
System.out.print("}");
System.out.println("");
//the if and if else statements below checks if the array contains more than 1 value as there can be no duplicates if this is the case
if (array.length==0)
System.out.println("That array has a length of 0.");
else if (array.length==1)
System.out.println("That array only has one value: " + array[0]);
else //This is where the fun begins
{
System.out.println("Processed Array is: ");
System.out.print( "{" + array[0]);//we print out the first value as it will always be printed (no duplicates has occured before it)
for (int i = 1; i < array.length; i++) //This parent for loop increments once the all the checks below are run
{
int check = 0;//this variable tracks the amount of times an value has appeared
for(int h = 0; h < i; h++) //This loop checks the current value for array[i] against all values before it
{
if (array[i] == array[h])
{
++check; //if any values match during this loop, the check value increments
}
}
if (check != 1) //only duplicates can result in a check value other than 1
{
System.out.print(", " + array[i]);
}
}
}
System.out.print("}"); //formatting
System.out.println("");
}
public static void main(String[] args)
{ //I really wanted to be able to request an input from the user but so that they could just copy and paste the whole array in as an input.
//I'm sure this can be done by splitting the input on "," or " " and then using a for loop to add them to the array but I dont want to spend too much time on this as there are still many tasks to get through!
//Will come back and revisit to add this if I remember.
int inpArray[] = {20,100,10,80,70,1,0,-1,2,10,15,300,7,6,2,18,19,21,9,0}; //This is just a test array
printNoDups(inpArray);
}
}
the bug is on the line
sum += i;
it should be
sum += x;

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.

Enhanced For Loop Exception [duplicate]

This question already has answers here:
Enhanced 'for' loop causes an ArrayIndexOutOfBoundsException
(2 answers)
Closed 5 years ago.
Created the below code whilst playing with loops. The code below stores the Fibonacci values into an array and then prints them using for loops.
int [] numbers;
numbers = new int[25];
numbers[0] = 1;
numbers[1] = 1;
System.out.println("Initializing the array values");
for(int i = 2; i < numbers.length; i++)
{
numbers[i] = numbers[i-1] + numbers[i-2];
}
System.out.println("Printing out Fibonacci values");
for(int i = 0; i < numbers.length; i++)
{
System.out.print(numbers[i] + ", ");
}
The above code works fine. The first time I threw it together though, I used an enhanced for loop to print out the values (the second for loop in the code). This compiles fine, but when I run it I get the following;
Initializing the array values
Printing out Fibonacci values
1, 1, 2, 3, 8, 34, 377, 17711, Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 34
at ArrayDemo.main(ArrayDemo.java:21)
I don't get what went wrong. Changing the second loop shouldn't change the values (you'll notice the fibonacci values are wrong (ie missing values)). And I don't get why a simple enhanced for loop would skip indexes. Now, this isn't really a big deal because this isn't for a project or anything, it just bugs me that I can't figure out why it's doing it. Any clues?
The enhanced for loop just looked like this;
for(int i : numbers)
{
System.out.print(numbers[i] + ", ");
}
for(int i : numbers)
{
System.out.print(numbers[i] + ", ");
}
i here is the elements in the array, not the indexes. It could be bigger than numbers.length.
For example, if numbers = {1,2,3,9} then i will be 1, 2, 3, 9. But its length is 4, so when you loop on the elements inside it, you're trying to do numbers[9] which exceeds its size.
You probably want to System.out.print(i + ", ");
for(int i = 0; i <= numbers.length; i++) should be
for(int i = 0; i < numbers.length; i++)
In java, arrays are 0 based indexing. It means that your first element should be accessed at the index 0 and obviously the last at the length of your array minus 1.
int tab[] = new int[3]; //tab of length 3
tab[0] = 11;
tab[1] = 24;
tab[2] = 5;
Here you access the last element by calling tab[2] or tab[tab.length-1], which is equivalent.
Apologies, that was just a mistake in the code I put up in the
question.
The problem is that you should do : System.out.print(i + ", ");
You should read this and this about enhanced for loop.
The for statement also has another form designed for iteration through
Collections and arrays This form is sometimes referred to as the
enhanced for statement, and can be used to make your loops more
compact and easy to read. To demonstrate, consider the following
array, which holds the numbers 1 through 10:
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
The following program, EnhancedForDemo, uses the enhanced for to loop through the array:
class EnhancedForDemo {
public static void main(String[] args){
int[] numbers =
{1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println("Count is: " + item);
}
}
}
In this example, the variable item holds the current value from the numbers array.
So item holds the current value from the numbers array and not the current index. That's why you get an IOOBE.
for(int i : numbers)
{
System.out.print(numbers[i] + ", ");
}
should be
for(int i : numbers)
{
System.out.print(i + ", ");
}
You don't need to use indexes in enhanced for-loop.

Categories

Resources