I am doing a project in which the user enters a number, x ,it will then generate x amount of random numbers and add them to an arraylist. In one text field, it will display however many random integers are in the array, I then have to make it so in another textfield, it sorts those numbers through a selection sorting. I'm pretty sure I have the code for it right, I'm just not sure how to get the sorted numbers to display on the text field #2. Heres what I have:
ArrayList <Integer> Numbers = new ArrayList <Integer>();
....
String input;
int int1,int2 = 0, min = -1000, max = 1000,j, maximum;
input = Input.getText();
int1 = Integer.parseInt(input);
Random number = new Random();
while(int2 < int1){
for (int i = 0; i < int1; i++){
int randomInt = number.nextInt(max - min + 1) + min;
Numbers.add(randomInt);
int1--;
}
}
if(Selection.isSelected() && Ascending.isSelected()){
for (int i = 0; i<Numbers.size()-1; i++){
maximum = i;
for(j = i+1; j<=Numbers.size()-1;j++){
if(j < i){
int temp = i;
i = j;
j = temp;
}
}
}
}
Output1.setText("Unsorted Numbers " + Numbers);
Output2.setText("Sorted Numbers " + //what here? );
Numbers.clear();
Thanks for any help you might be able to offer.
what about this ?
public static void main(String[] args) {
//min and max value
int min = -1000;
int max = 1000;
//collection to store numbers
ArrayList<Integer> numbers = new ArrayList<Integer>();
Random random = new Random();
//receive input
Scanner myScanner = new Scanner(System.in);
int numberFromUser = Integer.parseInt(myScanner.nextLine());
for (int i = 0; i < numberFromUser; i++) {
numbers.add(random.nextInt(max - min + 1) + min);
}
System.out.println("Unsorted :" + numbers);
// sort the numbers
Collections.sort(numbers);
System.out.println("Sorted :" + numbers);
numbers.clear();
}
You should prepare a string:
String sortedNumbersOutput = "";
for (int i = 0; i < sortedNumbers.size(); i++) {
sortedNumbersOutput += sortedNumbers.get(i) + (i != sortedNumbers.size() - 1 ? "," : "");
}
Output2.setText("Sorted Numbers " + sortedNumbersOutput );
On a separate note, I don't believe you are sorting your list...
You are comparing on the indices and not the values at those indices.
Maybe you want to try:
boolean changes = true;
int temp;
while (changes) {
changes = false;
for (int i = 0; i < Numbers.size()-1; i++){
if (Numbers.get(i) > Numbers.get(i+1)) {
temp = Numbers.get(i);
Numbers.set(i, Numbers.get(i+1));
Numbers.set(i+1, temp);
changes = true;
}
}
}
which is called a bubble sort
Related
I am trying to develop a program to delete all the median values from an array (the middle value if it has an odd number of elements, the two middle values if it has an even number of elements) until there are only two elements left, elements [0] and [1]. For example, if the user inputs 1, 2, 3, 4, 5, the program will return [1, 5]. I put down what I thought logically might help, but my array x isn't copying myArray in the for loops. I am not looking for someone to completely do the code for me, just to point out where I am wrong. Here is my code:
import java.util.*;
public class Deletion
{
public static void main(String[]args)
{
Scanner kb = new Scanner(System.in);
System.out.println("Please enter the array length:");
int [] myArray = new int[kb.nextInt()];
int [] x = new int[myArray.length - 1];
int index1 = 0;
int index2 = 0;
int index3 = 0;
if(myArray.length < 3)
{
System.out.println("Please make sure array length is greater than two. Run again.");
System.exit(0);
}
else
{
for(int i = 0; i < myArray.length; i++)
{
System.out.println("Please enter a number for position " + i + ":");
myArray[i] = kb.nextInt();
}
for(int i = 0; i < myArray.length; i++)
{
while(myArray.length > 2)
{
if(myArray.length%2 != 0)
{
index1 = (myArray.length/2);
for(int j = 0, r = 0; j < myArray.length; j++)
{
if(j != index1)
{
x[r++] = myArray[j];
myArray = x;
}
}
x = new int[myArray.length - 1];
}
else
{
index2 = (myArray.length/2);
index3 = (myArray.length/2 - 1);
for(int j = 0, r = 0; j < myArray.length; j++)
{
if(j != index2 && j != index3)
{
x[r++] = myArray[j];
myArray = x;
}
}
x = new int[myArray.length - 1];
}
}
}
}
System.out.println(Arrays.toString(myArray));
}
}
You must create the array and populate it, else it's using the same memory address, hence won't work. Use the following:
myArray = ArrayUtils.clone(x);
When you are doing do “myArray = x”, your are actually merely assigning a reference to the array. Hence, if you make any change to one array, it would be reflected in other arrays as well because both myArray and x are referring to the same location in memory.
Thus, what you need is
myArray = x.clone();
I cleaned up your code a bit. According to what you described, what really matters is pulling in the minimum and maximum values in the array - everything else will be deleted, so you simply need a single traversal through the array to find those two values.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean isValid = false;
int validLength = 0;
System.out.println("Please enter the array length:");
while (!isValid) {
int length = scanner.nextInt();
if (length < 3) {
System.out.println("Please make sure array length is greater than two. Try again.");
}
else {
isValid = true;
validLength = length;
}
}
int minimumValue = Integer.MAX_VALUE, maximumValue = Integer.MIN_VALUE;
for (int i = 0; i < validLength; i++) {
System.out.println("Please enter a number for position " + i + ":");
int nextInt = scanner.nextInt();
if (nextInt < minimumValue) minimumValue = nextInt;
else if (nextInt > maximumValue) maximumValue = nextInt;
}
System.out.println(Arrays.toString(new int[] {minimumValue, maximumValue}));
}
Edit: made another revision as using an array is unnecessary. Just keep track of the minimum and maximum values as they are being entered.
The final output will show who has the highest grade and who has the lowest grade.
I'm lost on how to call the lowest name/grade to the final output.
In the code I have some comments on where I'm stuck with the "currentMinIndex", the "currentMaxIndex" works just fine and will show it to the final output. I tried to mirror it but it isn't going how I expected. Not sure if something with "(int k = 1; k>= m; k++)" is incorrect.
import java.util.*;
public class MyArrayEX {
// Sort grades lowest on top
public static int[] reverseInt(int[] array) {
int[] input = new int[array.length];
for (int i = 0, j = input.length - 1; i < array.length; i++, j--) {
input[j] = array[i];
}
return input;
}
public static void main(String[] args) {
// Scanners
Scanner input = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
// Input amount
System.out.print("\nEnter number of students: ");
int numOfStu = input.nextInt(); // Number of Students
int[] grades = new int[numOfStu];
String[] names = new String[numOfStu];
// Start loop, amount is based off of "numOfStu"
for (int i = 0; i < numOfStu; i++) {
System.out.print("\rEnter student first name: ");
String name = keyboard.next();
System.out.print("Enter the students grade: ");
int grade = input.nextInt();
// Assigning i
names[i] = name;
grades[i] = grade;
//System.out.println("");
}
// This is the area that sorts it from least to greatest
// i is the indexed value of the last number in array
for (int i = grades.length - 1; i > 0; i--) {
// Resets both to 0 to start at the beginning of the array
int currentMax = grades[0];
int currentMaxIndex = 0;
// i is back-limit that gets chopped off by one each time
for (int k = 1; k <= i; k++) {
if (currentMax < grades[k]) {
currentMax = grades[k];
currentMaxIndex = k;
}
}
// This is where im lost on how to call the min value
// Trying to mirror the one above but using it
// to show the minimum grade along with the name
for (int m = grades.length - 1; i > 0; i--) {
int currentMin = grades[0];
int currentMinIndex = 0;
// Min grades
for (int k = 1; k >= m; k++) {
if (currentMin < grades[m]) {
currentMin = grades[m];
currentMinIndex = m;
}
}
// After largest number is found, assign that number to i
// Im trying to have the final output show the min/max grade with who has it
// Would the MinIndex be assigned to a different variable?
grades[currentMaxIndex] = grades[i];
grades[currentMinIndex] = grades[m];
grades[i] = currentMax;
grades[m] = currentMin;
String highName = names[currentMaxIndex];
String lowName = names[currentMinIndex];
names[currentMaxIndex] = names[i];
names[currentMinIndex] = names[m];
names[i] = highName;
names[m] = lowName;
// This shows the name and grade for the highest number
System.out.print("\rThe highest grade is " + highName + " with a " + currentMax);
// Unsure how to call this.
System.out.println("\r and the Lowest grade is " + lowName + " with a " + currentMin);
}
}
input.close();
keyboard.close();
}
}
Your code has multiple problems. First is with the 2 scanners that you are using for same System.in input stream and second you are using nested loops to find the min/max values which is totally unnecessary. Since the question is about finding the min/max so I will focus on that part only and for the scanner I would say remove the keyboard scanner and use only input scanner. Anyways, use the following code block to find the maximum and minimum grades with names:
int currentMaxIndex = 0;
int currentMinIndex = 0;
// Get min max
for (int i = 1; i<grades.length; i++) {
if (grades[currentMaxIndex]<grades[i]) {
currentMaxIndex=i;
}
if (grades[currentMinIndex]>grades[i]) {
currentMinIndex=i;
}
}
String highName = names[currentMaxIndex];
String lowName = names[currentMinIndex];
int currentMax = grades[currentMaxIndex];
int currentMin = grades[currentMinIndex];
System.out.print("\rThe highest grade is " + highName + " with a " + currentMax);
System.out.println("\r and the Lowest grade is " + lowName + " with a " + currentMin);
The approach is quite simple. We first aasume that the first element in the grades array is min and max then we loop to the remaining elements from 1 to grades.length and compare the index min/max to the current index element values and accordingly change our min/max indices. If the current index value is greater than currentMaxIndex then we copy it to currentMaxIndex and same but opposite for currentMinIndex. So in the end we will have the highest and lowest value indices of grades array. The complete code is here https://ideone.com/Qjf48p
I know this may stand for a silly question but I have got a lot of problems with this.
I will first explain how it should work :
1)Generate random Array with size in range <4,7>
2)Fill it with random elements in range <100, 999>
3)Print the index of three numbers with biggest digit sum
So the question is-how? I know I should implement this:
SumOfDigits += ElementFromArray % 10;
ElementFromArray /= 10;
But i have got no idea where. I tried to add this as a if (i>0) loop inside for loop-but its not working.
Also how at the end im going to print the proper elements? Should I use Arrays.sort(tab) and then System.out.println(tab[tab.length - 1]) (and so on with -2, -3 for 3 last elements)?
import java.util.Arrays;
import java.util.Random;
public class Ex1 {
public static void main(String[] args) {
Random rand = new Random();
int size = rand.nextInt(4) + 4;
int tab[] = new int[size];
for (int i = 0; i < tab.length; i++) {
int elements = rand.nextInt(900) + 100;
tab[i] = elements;
}
System.out.println(Arrays.toString(tab));
}
}
If we aim for a solution using only arrays I would use a 2d array to hold the sum of digits and the index of the corresponding number in the tab array
So first create the array based on the size of the original array
int[][] sums = new int[size][2];
then in the for loop, calculate the sum of the random number and store it and the index
sums[i][0] = elements / 100 + (elements / 10) % 10 + elements % 10;
sums[i][1] = i;
Then sort the sums array using a custom comparator
Arrays.sort(sums, new Comparator<int[]>() {
#Override
public int compare(int[] o1, int[] o2) {
return Integer.compare(o2[0], o1[0]);
}
});
And finally print the index and number of the numbers of the top 3
for (int i = 0; i < 3; i++) {
System.out.printf("%d: %d\n", sums[i][1], tab[sums[i][1]]);
}
Just use while loop: here is a quick and dirty solution:
private static void main10(String[] args) {
Random rand = new Random();
int size = rand.nextInt(4) + 4;
int[] tab = new int[size];
for (int i = 0; i < tab.length; i++) {
int element = rand.nextInt(900) + 100;
tab[i] = element;
}
System.out.println(Arrays.toString(tab));
// calculate digits:
int[] digitsums = new int[size];
for (int i = 0; i < tab.length; i++) {
int element = tab[i];
int sumOfDigits = 0;
while (element > 0) {
sumOfDigits += element % 10;
element /= 10;
}
digitsums[i] = sumOfDigits;
}
System.out.println(Arrays.toString(digitsums));
int[] copyOfdigitsums = Arrays.copyOf(digitsums, digitsums.length);
for (int i = 1; i <= 3; i++) {
int j = getIndexOfLargest(copyOfdigitsums);
System.out.println("index of " + i + "largest is " + j + ", with a digitsum of " + copyOfdigitsums[j]);
copyOfdigitsums[j] = 0;
}
}
static int getIndexOfLargest(int[] digitsums) {
int largest = 0;
int index = 0;
for (int i = 0; i < digitsums.length; i++) {
int d = digitsums[i];
if (largest < d) {
largest = d;
index = i;
}
}
return index;
}
I'm trying to write a part of a program that I have for an assignment. This part of the program should take 8 user inputed integers to fill however if the user inputs a digit that has already been inputed an error is displayed and the user is asked to input a different number. As of yet I haven't written the error code and second attempt part of the code because I am having issues with the checking for duplicates part. At present the out put is True no matter what I put in.
int maxNum = 8;
int[] arrayIn = new int[maxNum];
boolean duplicates = false;
// Run while not true
while (!duplicates) {
// For loop for input into array
for (int j = 0; j < maxNum; j++) {
System.out.println("Enter digit " + digCounter + ":");
arrayIn[j] = in1.nextInt();
digCounter++;
// Check for duplicates
for (int a = 0; a < maxNum; a++) {
for (int k = a + 1; k < maxNum; k++) {
if (k != a && arrayIn[k] == arrayIn[a]) {
// Quit loop if duplicate found
duplicates = true;
}
}
}
}
System.out.println(duplicates);
}
You should look into a collection called Set. There is a pretty handy function Set.contains that will return true or false depending if a number is already in the Set or not. Something like this would do the trick:
Scanner scanner = new Scanner(System.in);
int maxNum = 8;
Set<Integer> numbers = new HashSet<>();
int digCounter = 1;
//Run while we need numbers
while (digCounter <= maxNum) {
System.out.println("Enter digit " + digCounter + ":");
int tempNumber = scanner.nextInt();
if (numbers.contains(tempNumber)) { //If number is already chosen
System.out.println("Sorry that number has already been added");
} else { //If new number
digCounter++;
numbers.add(tempNumber);
}
}
System.out.println(numbers);
Or if you HAVE to use only arrays you can do something like this:
Scanner scanner = new Scanner(System.in);
int maxNum = 8;
int[] arrayIn = new int[maxNum];
boolean duplicate;
int digCounter = 1;
// Run while we need numbers
while (digCounter <= maxNum) {
//reset duplicate
duplicate = false;
//Get user input
System.out.println("Enter digit " + digCounter + ":");
int temp = scanner.nextInt();
for (int i = 0; i <= digCounter - 2; i++) { //Loop through accepted numbers
if (temp == arrayIn[i]) { //We have found a match
duplicate = true;
break;
}
}
//Check if duplicate
if (duplicate) {
System.out.println("Sorry that number has already been added");
} else {
arrayIn[digCounter - 1] = temp;
digCounter++;
}
}
System.out.println(Arrays.toString(arrayIn));
Hope this helps!
This code will also work if you don't want to use set.
// creating the array
int[] array = new int[10];
// Taking the first number
System.out.println("Please enter your numbers: ");
array[0] = input.nextInt();
// taking other inputs
int count;
for (count = 1; count < array.length; count++) {
int num = input.nextInt();
// Scanning the array for the number
int n;
for (n = 0; n < count; n++) {
while (array[n] == num) { // This will also work if the user
// wants to give duplicate after
// duplicate
System.out.println("You have entered this number before! Add another..");
num = input.nextInt();
n = 0;
}
}
array[count] = num;
}
Ok so this is my code. I'm supposed to gather 10 numbers of input and then sort them in descending order by the number of which they appear.
Ex. {0,0,1,2,2,2]
My output would be "Mode=2 and then have 2 appears 3 times, 0 appears two times, 1 appears once."
My code can gather the 10 integers and find the mode but I'm having issues trying to sort the numbers in that way. This is what I have so far and I'm stuck.
import java.util.*;
class question2
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] arrTwo = new int[10];
int x=0;
for (int i = 0; i < 10; i++)
{
System.out.println("Enter number: " + (i + 1));
arrTwo[i] = scan.nextInt();
}
mode(arrTwo);
int temp;
int bs[] = new int[10];
for ( x=0 ; x<=8 ; ++x )
{
if (bs[x]>bs[x+1])
{
temp=bs[x];
bs[x]=bs[x+1];
bs[x+1]=temp;
x=-1;
}
}
for(int i = 0; i <= bs.length-1; i++)
{
for(int index=0; index <= 99 ; index++)
{
if (i == i)
{
bs[i] +=1;
}
}
System.out.println("The number " + i + " is generated " +arrTwo[i] + " times");
}
}
public static void mode(int[] array)
{
int modeTrack[] = new int[10];
int max =0; int number =0;
for (int i = 0; i < array.length; i++)
{
modeTrack[array[i]] += 1;
}
int maxIndex = 0;
for (int i = 1; i < modeTrack.length; i++)
{
int newNum = modeTrack[i];
if (newNum > modeTrack[maxIndex])
{
maxIndex = i;
}
}System.out.println("The mode is: "+maxIndex);
}
My output isn't listing my numbers, just 0-9 and the generated times is just going from 1-9 with no basis or order.
this code:
int bs[] = new int[10];
for ( x=0 ; x<=8 ; ++x ){
if (bs[x]>bs[x+1]) {
temp=bs[x];
bs[x]=bs[x+1];
bs[x+1]=temp;
x=-1;
}
}
does nothing. On initialization bs is filled with zeroes bs[x-1] is never greater than bs[x] because all values are the same.
also
if (i == i){
is always true