Java Program to Insert Element in Array - java

private static int i;
public static void main(String[] args)
{
int n,num1,num3;
int arr[] = new int[50];
Scanner scan = new Scanner(System.in);
System.out.print("Enter number you want in array:");
n = scan.nextInt();
int a[] = new int[n];
System.out.println("Enter any number:");
for (int i = 0; i < n; i++)
{
a[i] = scan.nextInt();
}
for (int i = 0; i < n; i++)
{
for (int num = i + 1; num < n; num++)
{
if (a[i] > a[num])
{
num1 = a[i];
a[i] = a[num];
a[num] = num1;
}
}
}
System.out.print("Ascending Order:");
for (int i = 0; i < n - 1; i++)
{
System.out.print(a[i] + ",");
}
System.out.println(a[n-1]);
System.out.println("Enter Last number:" );
num1= scan.nextInt();
System.out.print("New Array Position: ");
for(i=0; i<n+1; i++)
{
System.out.print(arr[i] + " ");
}
}
}
Output:
Enter number you want in array:5
Enter any number: 5 2 3 1
Ascending Order: 1 2 3 5
Enter last number: 4
New Array Position: 0 0 0 0
it should be like this 1 2 3 4 5 can guys help me thanks

Couple of things:
1.While printing arr[i] in the last for loop, you have never touched array arr after declaration
i.e. int arr[] = new int[50]; Therefore, output 0 0 0 0 is as expected.
2.After reading the last number i.e. num1= scan.nextInt();, you have not used it anywhere moving forward. How do you think you array will come to know about the last element which is to be added ? :)
Something of this sort will work:
1.After sorting array a, copy it into array arr:
for(int i=0;i<n;i++){
arr[i] = a[i];
}
2.Once you have all the old elements in array arr, read last element in array arr i.e. arr[n+1] = scan.nextInt();
3.Here you can again sort the array arr to take last element to the appropriate place.
4.Print array arr:
for(int j=0;j<n+1;j++){
System.out.print(arr[j]+" ");
}
NOTE: Make sure your n is less than 50. Otherwise you will run into java.lang.ArrayIndexOutOfBoundsException

There are several problems in your code,
This answer based on the output given
1) you are going to specify a size of your array:
According to the output it is: 5
but actually you are going to get 4 numbers from the command line, so the first for loop should be only for the 4 elements (Assume that you are going to add last element again, so all elements count in array = 5)
for (int i = 0; i < n-1; i++)
{
a[i] = scan.nextInt();
}
2) Second for loop should be goes until 4 elements
for (int i = 0; i < n-1; i++)
{
for (int num = i + 1; num < n-1; num++)
{
if (a[i] > a[num])
{
num1 = a[i];
a[i] = a[num];
a[num] = num1;
}
}
}
3) Ascending order of the array contains only 4 elements, therefore it also goes until 4 elements
for (int i = 0; i < n-1 ; i++)
{
System.out.print(a[i] + ",");
}
4) You are going to get last element from the command line, it should assign to the array
a[n-1] = num1= scan.nextInt();
5)You have to again re arrange the array
for (int i = 0; i < n; i++)
{
for (int num = i + 1; num < n; num++)
{
if (a[i] > a[num])
{
num1 = a[i];
a[i] = a[num];
a[num] = num1;
}
}
}
6) Then you have to print the array :
for(i=0; i<n; i++)
{
System.out.print(a[i] + " ");
}
Full code:
public class MyClass {
private static int i;
public static void main(String[] args)
{
int n,num1,num3;
int arr[] = new int[50];
Scanner scan = new Scanner(System.in);
System.out.print("Enter number you want in array:");
n = scan.nextInt();
int a[] = new int[n];
System.out.println("Enter any number:");
for (int i = 0; i < n-1; i++)
{
a[i] = scan.nextInt();
}
for (int i = 0; i < n-1; i++)
{
for (int num = i + 1; num < n-1; num++)
{
if (a[i] > a[num])
{
num1 = a[i];
a[i] = a[num];
a[num] = num1;
}
}
}
System.out.print("Ascending Order:");
for (int i = 0; i < n-1 ; i++)
{
System.out.print(a[i] + ",");
}
System.out.println("");
System.out.println("Enter Last number:" );
a[n-1] = num1= scan.nextInt();
for (int i = 0; i < n; i++)
{
for (int num = i + 1; num < n; num++)
{
if (a[i] > a[num])
{
num1 = a[i];
a[i] = a[num];
a[num] = num1;
}
}
}
System.out.print("New Array Position: ");
for(i=0; i<n; i++)
{
System.out.print(a[i] + " ");
}
}
}
Output:
Enter number you want in array:5
Enter any number:
5
3
2
1
Ascending Order:1,2,3,5,
Enter Last number:
4
New Array Position: 1 2 3 4 5

Related

Array program not running correctly. How do I fix it?

Trying to write a program that asks the a user for 10 integers as input. The program
places the even integers into an array called evenList, the odd integers into
an array called oddList, and the negative numbers into an array called
negativeList. The program displays the contents of the three arrays after
all of the integers have been entered.
This is my code:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int countNeg = 0;
int countOdd = 0;
int countEven = 0;
int[] list = new int[10];
System.out.println("Please enter 10 integers:");
for(int i = 0; i < list.length; i++)
{
list[i] = scan.nextInt();
if(list[i] < 0)
{
countNeg++;
}
if(list[i] % 2 == 0 && list[i] > 0)
{
countEven++;
}
if(list[i] % 2 == 1 && list[i] > 0)
{
countOdd++;
}
}
int[] oddList = new int[countOdd];
int[] evenList = new int[countEven];
int[] negativeList = new int[countNeg];
for(int i = 0; i < list.length; i++)
{
if(list[i] < 0)
{
for(int j = 0; j < countNeg; j++)
{
negativeList[j] = list[i];
}
}
}
for(int i = 0; i < list.length; i++)
{
if(list[i] % 2 == 0 && list[i] > 0)
{
for(int j = 0; j < countEven; j++)
{
evenList[j] = list[i];
}
}
}
for(int i = 0; i < list.length; i++)
{
if(list[i] % 2 == 1 && list[i] > 0)
{
for(int j = 0; j < countOdd; j++)
{
oddList[j] = list[i];
}
}
}
for (int i : negativeList)
{
System.out.print(i + " ");
}
System.out.println();
for (int i : evenList)
{
System.out.print(i + " ");
}
System.out.println();
for (int i : oddList)
{
System.out.print(i + " ");
}
}
}
The program prints the Arrays with the correct amount of values but the wrong numbers. It prints only the last negative, even, or odd number to be input. ex input is 1, 2, 3, 4, 5, 6, -1, -2, -3, -4. For negativeList it prints -4 -4 -4 -4. Im guessing something is wrong in the loops after the arrays are created. Please help!!
you can very much simplify your code with using ArrayList instead of array. For example:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int length = 10;
System.out.println("Please enter 10 integers:");
List<Integer> oddList = new ArrayList<>();
List<Integer> evenList = new ArrayList<>();
List<Integer> negativeList = new ArrayList<>();
for (int i = 0; i < length; i++) {
int n = scan.nextInt();
if (n < 0) {
negativeList.add(n);
} else if (n % 2 == 0) {
evenList.add(n);
} else {
oddList.add(n);
}
}
for (int i : negativeList) {
System.out.print(i + " ");
}
System.out.println();
for (int i : evenList) {
System.out.print(i + " ");
}
System.out.println();
for (int i : oddList) {
System.out.print(i + " ");
}
}
there are a few issues with the code you provided.
First, in the for loops that initialize the negativeList, evenList, and oddList arrays, you are overwriting the values at each iteration. This means that the final arrays will only contain the last value that was assigned to them. To fix this, you can use a counter variable to keep track of the next index to be filled in each array, like this:
int negCounter = 0;
int evenCounter = 0;
int oddCounter = 0;
for(int i = 0; i < list.length; i++)
{
if(list[i] < 0)
{
negativeList[negCounter] = list[i];
negCounter++;
}
}
for(int i = 0; i < list.length; i++)
{
if(list[i] % 2 == 0 && list[i] > 0)
{
evenList[evenCounter] = list[i];
evenCounter++;
}
}
for(int i = 0; i < list.length; i++)
{
if(list[i] % 2 == 1 && list[i] > 0)
{
oddList[oddCounter] = list[i];
oddCounter++;
}
}
Second, you are not checking if the input values are integers. If the user enters a non-integer value, the program will throw an exception. You can add a check to make sure that the input is an integer like this:
if(scan.hasNextInt())
{
list[i] = scan.nextInt();
// ... rest of the code
}
else
{
System.out.println("Please enter an integer.");
// If the input is not an integer, discard it and move to the next
input
scan.next();
}

Program ends after entering a string in Java

I've been looking for different solutions out here but on my code they won't work. I'm getting an input from a user but then it doesn't display what's inside the if-else statement. I tried to do a different code for the if statement but it doesn't work. The int input works but it doesn't work in the string input.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int numbers [] = new int[10];
int temp;
String sc = " ";
Scanner scan = new Scanner(System.in);
// Loop through array
// Change value of each array per iteration
System.out.print("Enter 10 integers: ");
for(int i = 0; i < numbers.length; i++){
numbers[i] = scan.nextInt();
}
System.out.print("\nPlease Choose Among The Following:");
System.out.println("\n A - Display the numbers \t B - Display the values of even indexes \n C - Display the values of odd indexes \t D - Display the values in ascending order \n E - Display the values in descending order");
System.out.print("\nEnter The Letter of Your Choice: ");
sc = scan.nextLine();
if (sc.equals('A') || sc.equals('a')){
System.out.print("Display each item in array");
for(int number: numbers){
System.out.println(number);
}}
else if (sc.equals('B') || sc.equals('b')){
System.out.println("Display odd indexes");
for(int i = 0; i < numbers.length; i++){
if(i % 2 == 0){
System.out.println(numbers[i]);
}
}}
else if (sc.equals('C') || sc.equals('c')){
System.out.println("Display even indexes");
for(int i = 0; i < numbers.length; i++){
if(i % 2 == 1){
System.out.println(numbers[i]);
}
}}
else if (sc.equals('D') || sc.equals('d')){
int [] ascendingList = numbers.clone();
System.out.println("Display in ascending order using bubble sort");
for(int i = 0; i < ascendingList.length - 1 ; i++){
for(int j = 0; j < (ascendingList.length - i - 1); j++){
if(ascendingList[j] > ascendingList[j+1]){
temp = ascendingList[j];
ascendingList[j] = ascendingList[j+1];
ascendingList[j+1] = temp;
}
}
}
for(int number: ascendingList){
System.out.println(number);
}}
else if (sc.equals('E') || sc.equals('e')){
int [] descendingList = numbers.clone();
System.out.println("Display in descending order using bubble sort");
for(int i = 0; i < descendingList.length - 1 ; i++){
for(int j = 0; j < (descendingList.length - i - 1); j++){
if(descendingList[j] < descendingList[j+1]){
temp = descendingList[j];
descendingList[j] = descendingList[j+1];
descendingList[j+1] = temp;
}
}
}
for(int number: descendingList){
System.out.println(number);
}}
}
}

Java How do i repeat sort until no swaps are done in bubblesort?

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));
}

Having trouble searching array

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.

How to make Bubble Sort in Java to output the sorted numbers?

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;
}
}
}

Categories

Resources