I'm a beginner at java and I have a hopefully simple question.
I can get the numbers in order, but only a certain amount of numbers are added to the array. When there is a number less than the smallest number, it replaces that smallest number (the previous smallest gets removed from array). What can I do so that all of the array spots can be filled in?
public class apples {
public static void main(String[] args) {
System.out.print("How many numbers: ");
int num=IO.readInt();
double array[]=new double[num];
double temp;
boolean fixed=false;
while (fixed==false){
fixed=true;
for(int j=0; j<num;j++){
double x = IO.readDouble();
array[j] = x;
for (int i = 0; i < ( num - 1 ); i++) {
for (j = 0; j < num - i - 1; j++) {
if (array[j] > array[j+1]) {
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
fixed=false;
}
}
}
System.out.println("Sorted list of integers:");
for (int i = 0; i < num; i++)
System.out.println(array[i]);
}
}
}
}
First read in the numbers, then sort the array (and it's an array of double not int). Something like,
public static void main(String[] args) {
System.out.print("How many numbers: ");
int num = IO.readInt();
double array[] = new double[num];
for (int j = 0; j < num; j++) {
System.out.printf("Please enter double %d:%n", j + 1);
array[j] = IO.readDouble();
}
System.out.println("unsorted array: " + Arrays.toString(array));
Arrays.sort(array); // <-- or however you want to sort the array.
System.out.println("sorted array: " + Arrays.toString(array));
}
public static void main(String[] args) {
System.out.print("How many numbers: ");
int num = IO.readInt();
double array[] = new double[num];
for (int i = 0; i < num; i++) {
System.out.print("["+i+"]Please enter your double");
array[i] = IO.readDouble();
}
//Sort
double temp = 0;
for (int i = 0; i < num - 1; i++) {
for (int j = i + 1; j < num ; j++) {
if (array[j] > array[j]) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
//Result
for(int i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
}
}
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc =new Scanner(System.in);
int n =sc.nextInt();
int arr[]=new int [n];
for (int i =0;i<n;i++){
arr[i]=sc.nextInt();}
Arrays.sort(arr);
//if(n%2==0){median}
System.out.println( Arrays.toString(arr));
}
}
Related
So I have everything working fine up until the point in which I need to search. I'm really new to this so my code is probably awful I'm sorry in advance. Anyway, its a user input array, and the user should be able to search for a number in an array. Im getting the error for a duplicate variable on line 50 (int i, get 1).
import java.util.Scanner;
class SearchingSorting {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println ("How many numbers would you like to input?");
int num = input.nextInt();
double[] array = new double[num];
for (int i = 0; i < num; i++) {
System.out.println ("Input number " + (1 + i) + ":");
array[i] = input.nextDouble();
}
for (double temp1 : array){
System.out.print (temp1 + "\t");
}
input.close();
int pass;
int i;
int hold;
for(pass = 1; pass < array.length; pass++)
{
for(i = 0; i < array.length - 1; i++)
{
if(array[i] > array[i+1])
{
hold = (int) array[i];
array[i] = array[i+1];
array[i+1] = hold;
}
}
System.out.println("\nSorted number is: ");
for(i = 0; i < array.length; i++)
System.out.print(" " + array[i]);
}
int i, get1;
Scanner keyboard = new Scanner(System.in);
int[] numbers = new int[10];
for(i = 0; i < numbers.length; i++)
{
numbers[i] = i * 10;
}
System.out.print("Enter search number: ");
get1 = keyboard.nextInt();
SearchMethod(numbers, get1);
}
public static void SearchMethod(int[] num, int get2)
{
int i ;
boolean j = false;
for(i = 0; i < num.length; i++)
{
if(num[i] == get2)
{
j = true;
break;
}
}
if(j == true)
System.out.println(get2 + " is found at num[" + i + "]");
else
System.out.println(get2 + " is not found in an array");
}
}
You are trying to declare a new variable with the same name ("i") in the same scope.
Rename your variable i on line 50.
I'm trying to create a program that asks the user to input a number which is how many random numbers between 1-100 will be generated in an array. Then I want the largest number to be swapped with the last number and the smallest number to be swapped with the first number. Here is my code so far:
import java.util.Scanner;
import java.util.Random;
public class smallbig
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random randomGenerator = new Random();
int num = scan.nextInt();
int[] myArray = new int[num];
for (int i = 0; i < myArray.length; ++i) {
int randomInt = randomGenerator.nextInt(100);
myArray[i] = randomInt;
}
int smallest = myArray[0];
int largest = myArray[0];
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] > largest) {
largest = myArray[i];
}
if (myArray[i] < smallest) {
smallest = myArray[i];
}
}
for (int j = 1; j < myArray.length; j++) {
int first = myArray[0];
myArray[0] = smallest;
smallest = first;
int temp = largest;
int last = myArray.length;
myArray[last - 1] = largest;
temp = myArray[last - 1];
System.out.print(myArray[j] + " ");
}
}
}
I can't seem to get the numbers to properly swap. I created a loop which determines the smallest and largest numbers from the ones generated and these are stored. Then I create a loop which performs the necessary swaps but I can't seem to get it to work properly. It works fine for swapping the largest number with the last number but most of the time(not always) the outputted last number is also present somewhere else in the array. Here is what I mean:
input: 10
output: 62 48 34 0 91 14 64 60 91
I know there is a swapper method that I could use but I want to do it by manually swapping the numbers. Any help is appreciated, thanks.
you have one simple mistake, your loop should start from '0' when you perform the swap
for (int j = 0; j < myArray.length; j++) {
int first = myArray[0];
myArray[0] = smallest;
smallest = first;
int temp = largest;
int last = myArray.length;
myArray[last - 1] = largest;
temp = myArray[last - 1];
System.out.print(myArray[j] + " ");
Instead of a loop do
//find and stores poition of small
int smallPos = myArray.indexOf(small);
//stores tge values at 0
int tempSmall = myArray[0];
//swaps the values
myArray[0] = small;
myArray[smallPos] = smallTemp;
Just repeat this with the largest value and print it using a for loop. Tell me if it works.
I just tried this. Hope this helps.
public class App {
static int[] a = new int[100];
public static void main(String[] args) {
int i;
for(i = 0; i<a.length;i++)
a[i] = (int)(java.lang.Math.random() * 100);
int smallest = 0, largest = 0;
for(i =1; i<a.length; i++){
if(a[i] < a[smallest])
smallest = i;
if(a[i] > a[largest])
largest = i;
}
swap(0,smallest);
swap(a.length-1,largest);
for(i =0; i<a.length;i++)
System.out.print(a[i] + " ");
}
public static void swap(int i, int j){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
Your last loop doesn't do anything loopy. It just does the same thing over and over. And what it does is not correct. It is swapping the smallest into the first element but it's not moving the first element anywhere: it's gone.
You need to keep track of where the largest and smallest elements were. Your swap logic doesn't take that into consideration.
Write this code
import java.util.Scanner;
import java.util.Random;
public class smallbig
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random randomGenerator = new Random();
int num = scan.nextInt();
int[] myArray = new int[num];
for (int i = 0; i < myArray.length; ++i) {
int randomInt = randomGenerator.nextInt(100);
myArray[i] = randomInt;
}
int smallest = myArray[0];
int largest = myArray[0];
int pos1,pos2;
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] > largest) {
largest = myArray[i];
pos1=i;
}
if (myArray[i] < smallest) {
smallest = myArray[i];
pos2=i;
}
}
myArray[pos1]=myArray[myArray.length-1];
myArray[myArray.length-1]=largest;
myArray[pos2]=myArray[0];
myArray[0]=smallest;
for (int j = 1; j < myArray.length; j++) {
System.out.print(myArray[j] + " ");
}
}
}
i would advise against using a scanner or random values for testing since the result cannot be reproduced (at least not in an easy way). Be careful with what is an arrays index and what is the value at a specific index. This can lead to confusion very quickly. ^^
import java.util.Scanner;
import java.util.Random;
public class smallbig
{
private static int[] myArray;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random randomGenerator = new Random();
//int num = scan.nextInt(); //skip this for testing ^^-d
int num = 10;
myArray = new int[num];
for (int i = myArray.length-1; i > 0; i--) {
//int randomInt = randomGenerator.nextInt(100);
int randomInt = i; //use test condition that can be reproduced!
myArray[i] = myArray.length-i;
}
int smallest = 0;
int largest = 0;
int smallestIndex = 0;
int largestIndex = 0;
for (int i = 0; i < myArray.length; i++) {
if (myArray[i] > largest) {
largest = myArray[i];
largestIndex = i;
}
if (myArray[i] < smallest) {
smallest = myArray[i];
smallestIndex = i;
}
}
switchIndexOfmyArray(0, smallestIndex);
switchIndexOfmyArray(myArray.length-1, largestIndex);
for (int j = 0; j < myArray.length; j++) {
System.out.print(myArray[j] + " ");
}
}
public static void switchIndexOfmyArray(int index, int switchWithIndex){
int temp = myArray[index];
myArray[index] = myArray[switchWithIndex];
myArray[switchWithIndex] = temp;
}
}
Yielding
0 1 8 7 6 5 4 3 2 9
I admit i was slow on this one since i am hungry and tired xD
Happy coding! ^^
You did well by finding smallest and largest. Issue was in swap. I refactor the swap method. May be it works.
import java.util.Scanner;
import java.util.Random;
public class smallbig
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random randomGenerator = new Random();
int num = scan.nextInt();
int[] myArray = new int[num];
for (int i = 0; i < myArray.length; ++i) {
int randomInt = randomGenerator.nextInt(100);
myArray[i] = randomInt;
}
for(int k=0; k < myArray.length; k++)
{
System.out.print(myArray[k] + " ");
}
System.out.println();
int smallest = myArray[0];
int largest = myArray[0];
int sIndx = 0;
int lIndx = 0;
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] > largest) {
largest = myArray[i];
lIndx = i;
}
if (myArray[i] < smallest) {
smallest = myArray[i];
sIndx = i;
}
}
System.out.println();
System.out.println("Smallest = "+smallest);
System.out.println("largest = "+largest);
System.out.println("Smallest Index = "+sIndx);
System.out.println("largest Index = "+lIndx);
swapSmallAndLargest(num, myArray, sIndx, lIndx);
for(int k=0; k < myArray.length; k++)
{
System.out.print(myArray[k] + " ");
}
}
private static void swapSmallAndLargest(int num, int[] myArray, int sIndx, int lIndx) {
int temp = 0;
temp = myArray[sIndx];
myArray[sIndx] = myArray[0];
myArray[0] = temp;
temp = myArray[lIndx];
myArray[lIndx] = myArray[num-1];
myArray[num-1] = temp;
}
}
I need to take input from the user and if the user enters string the program should keep integer in descending order and the position of the string should be in constant position. I am not being able to keep only integer in descending order.
public class sort {
public static void main(String[] args) {
int num;
int i, j, temp;
String nu;
int y;
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of character to be sort:");
String num = input.nextLine();
int length = num.length();
String result = "";
for (i = 0; i < length; i++) {
Character character = num.charAt(i);
if (Character.isDigit(character)) {
result += character;
}
}
int array[] = new int[num];
System.out.println("Enter " + num + " character ");
for (i = 0; i < num; i++)
array[i] = input.nextInt();
for (i = 0; i < (num - 1); i++) {
for (j = 0; j < num - i - 1; j++) {
if (array[j] < array[j + 1]) {
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
System.out.println("Sorted list of integers:");
for (i = 0; i < num; i++)
System.out.println(array[i]);
}
}
I've made some modifications to your code that might help. For one, Integer.ParseInt works better than nextInt() because nextInt() leaves a carriage return on nextLine(). Also I feel a while loop would work better for your bubble sort algorithm.
import java.util.*;
public class sort {
public static void main(String[] args) {
int num;
int i, temp;
String nu;
int y;
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of character to be sort:");
num = Integer.ParseInt(input.nextLine());
int[] arr = new int[num];
System.out.println("Enter " + num + " character ");
for (i = 0; i < num; i++)
arr[i] = Integer.ParseInt(input.nextLine());
int swaps;
while (swaps == 0) {
swaps = 0;
for (i = 0; i < arr.Length; i++) {
if (arr[j] < arr[i + 1]) {
temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swaps++;
}
}
}
System.out.println("Sorted list of integers:");
for (i = 0; i < num; i++)
System.out.println(array[i]);
}
}
I changed a few things. First of all, you declared num twice, and had a String = input.nextInt() which doesn't match. The try...catch checks if it's an int input, otherwise it converts it from a char to an int. Your algorithm to put them in descending order worked fine, but populating the array wasn't working.
import java.util.InputMismatchException;
import java.util.Scanner;
public class sort {
public static void main(String []args) {
int i, j, temp;
int y;
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of character to be sort:");
String num = input.nextLine();
int length = Integer.parseInt(num);
String result = "";
int array[] = new int[length];
System.out.println("Enter " + num + " character ");
for (i = 0; i < length; i++) {
try{
array[i]=input.nextInt();
}catch(InputMismatchException e){
Character c = input.next().charAt(0);
array[i]=(int)(c.charValue());
}
}
for (i = 0; i < ( length- 1 ); i++) {
for (j = 0; j < length - i - 1; j++) {
if (array[j] < array[j+1])
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
System.out.println("Sorted list of integers:");
for (i = 0; i < length; i++)
System.out.println(array[i]);
}
}
This is what i have so far but the output for both arrays is the same randomly generated numbers instead of different ones for each array.
import java.util.Scanner;
public class Prog2_b {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Program #2b, Breanna Bergado, mascID 1885");
System.out.println("Please enter number of elements for a 1D array:");
int userVal = scnr.nextInt();
//System.out.println(((Object)userVal).getClass().getName();
double[] array = new double[userVal];
double [] array2 = new double[userVal];
double dotProd = 0;
for(int i = 0; i < userVal; i++) {
array[i] = Math.random();
array2[i] = Math.random();
}
for (int j = 0; j < 2; j++){
System.out.println("a"+(j+1)+"[]");
System.out.println("----------------");
for (int i = 0; i < userVal; i++) {
System.out.println(array[i] + " ");
}
System.out.println();
}
for(int i = 0; i < userVal; i++) {
dotProd = dotProd + array[i]* array2[i];
}
System.out.println("Dot Product is " + dotProd);
}
}
You should update your printing logic to:
for (int i = 0; i < userVal; i++) {
System.out.println(array[i] + " ");
}
System.out.println();
for (int j = 0; j < userVal; j++) {
System.out.println(array2[j] + " ");
}
Your current logic just prints the first array twice. You could also use nested arrays as one of the comments suggested, but the above code will work with what you have so far.
This is my code for the Bubble Sort. I cannot get the actual sorted values to output. The program reads the inputted numbers, but does not print it sorted.
I'm not sure what I have to do to make them sort.
Any advice or suggestions would be helpful.
package sortingalgorithm2;
import java.util.Scanner;
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Scanner read = new Scanner (System.in);
int[] num = new int[15];
int size = 15;
System.out.println("Enter 15 numbers: ");
for (int i=0; i <= size-1; i++)
{
num[i] = read.nextInt();
}
for (int i=0; i <= size-1; i++)
{
if (num[i] >=1 && num[i] <= 1000)
{
System.out.println("The numbers you entered are: ");
System.out.println(+num[0]);
System.out.println(+num[1]);
System.out.println(+num[2]);
System.out.println(+num[3]);
System.out.println(+num[4]);
System.out.println(+num[5]);
System.out.println(+num[6]);
System.out.println(+num[7]);
System.out.println(+num[8]);
System.out.println(+num[9]);
System.out.println(+num[10]);
System.out.println(+num[11]);
System.out.println(+num[12]);
System.out.println(+num[13]);
System.out.println(+num[14]);
}
else
{
System.out.println("Data input is invalid. Enter a number between "
+
"1 and 1000.");
break;
}
}
BubbleSort (num);
for (int i=0; i < num.length; i++)
{
System.out.println("The sorted numbers are: ");
System.out.print(num[i]+ " ");
}
}
private static void BubbleSort(int[] num)
{
for (int i=0; i <= num.length; i++)
for (int x=1; x <= num.length; x++)
if (num[x] > num[x+1])
{
int temp = num[x];
num[x] = num[x+1];
num[x+1] = temp;
}
}
}
Try this Bubble sort :
private static void BubbleSort(int[] num) {
for (int i = 0; i < num.length; i++) {
for (int x = 1; x < num.length - i; x++) {
if (num[x - 1] > num[x]) {
int temp = num[x - 1];
num[x - 1] = num[x];
num[x] = temp;
}
}
}
}
You are printing the actual numbers in the order the user entered. Try this instead:
int[] sortedNumbers = new int[15];
sortedNumbers = BubbleSort (num);
for (int i=0; i < sortedNumbers.length; i++)
{
System.out.println("The sorted numbers are: ");
System.out.print(sortedNumbers[i]+ " ");
}
public static int[] BubbleSort(int [] num)
{
int temp;
for (int i=1; i<num.length; i++)
{
for(int j=0; j<num.length-i; j++)
{
if (num[j] > num [j+1])
{
temp = num [j];
num [j] = num [j+1];
num [j+1] = temp;
}
}
}
return num;
}
Try this :
for (int i = 0; i < num.length; i++) {
for (int j = i + 1; j < num.length; j++) {
if (num[i] > num[j]) {
num[i] = num[i] + num[j] - (num[j] = num[i]);
}
}
}
you are passing the array variable num (which is not static) to BubbleSort()(which does not returns a value and shadows the global num variable with its own) and trying to use the same num variable to access your sorted array from your main method which is not right.
The genuine fix to this is to declare your variable num as static just before the main method( in the class declaration). So I have made the changes in the program and here is the solution.
import java.util.Scanner;
public class sol {
static int num [] =new int [15]; //declaring num as static in the class definition.
public static void main(String[] args)
{
Scanner read = new Scanner (System.in);
int size = 15;
System.out.println("Enter 15 numbers: ");
for (int i=0; i <= size-1; i++)
{
num[i] = read.nextInt();
}
read.close();
/*for (int i=0; i <= size-1; i++)
{
if (num[i] >=1 && num[i] <= 1000)
{
System.out.println("The numbers you entered are: ");
System.out.println(+num[0]);
System.out.println(+num[1]);
System.out.println(+num[2]);
System.out.println(+num[3]);
System.out.println(+num[4]);
System.out.println(+num[5]);
System.out.println(+num[6]);
System.out.println(+num[7]);
System.out.println(+num[8]);
System.out.println(+num[9]);
System.out.println(+num[10]);
System.out.println(+num[11]);
System.out.println(+num[12]);
System.out.println(+num[13]);
System.out.println(+num[14]);
}
else
{
System.out.println("Data input is invalid. Enter a number between "
+
"1 and 1000.");
break;
}
}*/ //I have disabled this just to check with the sort method.
BubbleSort ();//no need to pass the array as it is static and declared as a //class variable hence can be used to by all the methods of that class
System.out.println("The sorted numbers are: ");
for (int i=0; i < num.length; i++)
{
System.out.print(num[i]+ " ");
}
}
private static void BubbleSort()
{
for (int i=0; i < num.length; i++)// required changes in the looping
for (int x=0; x < num.length-i-1; x++)
if (num[x] > num[x+1])
{
int temp = num[x];
num[x] = num[x+1];
num[x+1] = temp;
}
}
}