Trying to swap array elements based on user input - java

So I have to swap two elements in an array with 5 values but the two to swap have to be taken from the keyboard. The previous question was to swap to specific ones and I got it done but I'm not sure how to get the numbers from the keyboard to be used in the swap. Some of this is left from the previous one where I knew the elements I had to swap.
import java.util.Scanner;
public class Swap2 {
public static void main(String []args) {
Scanner keyboardIn = new Scanner (System.in);
int[] numbers = new int []{12,9,33,28,5};
int temp = 0, first, second;
System.out.println ("Before the swap: ");
for(int i=0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
System.out.println();
System.out.println ("Enter the first number to swap:");
first = keyboardIn.nextInt();
System.out.println ("Enter the second number to swap:");
second = keyboardIn.nextInt();
System.out.println ();
temp = numbers[3];
numbers [3] = numbers [1];
numbers [1] = temp;
System.out.println ("After the swap:");
for (int i = 0; i < numbers.length; i++) {
System.out.print (numbers[i] + " ");
}
}
}

you have to define index...
import java.util.Scanner;
public class Swap {
public static void main(String[] args) {
Scanner keyboardIn = new Scanner(System.in);
/* enter code here */int[] numbers = new int[] { 12, 9, 33, 28, 5 };
int temp = 0, first, second;
int index1 = 0 , index2 = 0;
int j , k ;
System.out.println("Before the swap: ");
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
System.out.println();
System.out.println("Enter the first number to swap:");
first = keyboardIn.nextInt();
System.out.println("Enter the second number to swap:");
second = keyboardIn.nextInt();
System.out.println();
for(k = 0 ; k < numbers.length; k++){
if(numbers[k] == first)
index1 = k;
}
for(j = 0 ; j < numbers.length; j++){
if(numbers[j] == second)
index2 = j;
}
temp = numbers[index1];
numbers[index1] = numbers[index2];
numbers[index2] = temp;
System.out.println("After the swap:");
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
}
}

You're not actually swapping the numbers which user enters, you're always swapping 4th element with the 1st.
To swap the elements you need to find out the index where they belong.
public static int indexOf(int []arr, int ele)
{
for(int i = 0; i < arr.length; ++i)
if(arr[i] == ele)
return i;
return -1;
}
Now to swap those elements, call this function.
int first = sc.nextInt();
int firstIndex = indexOf(arr, first);
int second = sc.nextInt();
int secondIndex = indexOf(arr, second);
int temp;
temp = arr[firstIndex];
arr[firstIndex] = arr[secondIndex];
arr[secondIndex] = temp;

Why don't you try this. Please keep in mind that array indices start at 0.
import java.util.Scanner;
public class Swap2
{
public static void main(String []args)
{
Scanner keyboardIn = new Scanner (System.in);
int[] numbers = new int []{12,9,33,28,5};
int temp, first, second;
System.out.println ("Before the swap: ");
for(int i=0; i < numbers.length; i++)
{
System.out.print(numbers[i] + " ");
}
System.out.println ();
System.out.println ("Enter the first number to swap:");
first = keyboardIn.nextInt();
System.out.println ("Enter the second number to swap:");
second = keyboardIn.nextInt();
System.out.println ();
temp = numbers[first];
numbers [first] = numbers [second];
numbers [second] = temp;
System.out.println ("After the swap:");
for (int i = 0; i < numbers.length; i++)
{
System.out.print (numbers[i] + " ");
}
}
}

Related

Program that removes duplicated elements and return its new elements and size

My code is almost done but the problem is the returning size it supposed to return the size after the duplicated elements has been removed. it wont output the right size.
import java.util.Scanner;
import java.util.Arrays;
public class Main
{
public static void main (String[] args)
{
int size;
int i;
int j;
Scanner scn = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
size = scn.nextInt();
System.out.println("\n");
int myArray[] = new int [size];
for(i = 0; i < size; i++)
{
System.out.print("Enter value for num["+i+"]: ");
myArray[i] = scn.nextInt();
}
System.out.print("\nThe inputted values are ");
for(i = 0; i < size; i++)
{
System.out.print(" " + myArray[i] + ",");
}
System.out.print("\nDuplicate values ");
for (i = 0; i < myArray.length-1; i++)
{
for (j = i+1; j < myArray.length; j++)
{
if ((myArray[i] == myArray[j]) && (i != j))
{
System.out.print(" " +myArray[j]+ ",");
}
}
}
int length = myArray.length;
length = remove_dupli(myArray,length);
System.out.print("\nThe new values of the array are ");
for(i = 0; i < length; i++)
{
System.out.print(" " +myArray[i]+", ");
}
System.out.println("\nThe new length of the array is: "+array_sort(myArray));
}
is there a problem on this part?
public static int remove_dupli(int myArray[], int n){
if (n==0 || n==1){
return n;
}
int[] temp = new int[n];
int j = 0;
for (int i=0; i<n-1; i++){
if (myArray[i] != myArray[i+1]){
temp[j++] = myArray[i];
}
}
temp[j++] = myArray[n-1];
for (int i=0; i<j; i++){
myArray[i] = temp[i];
}
return j;
}
or this part?
public static int array_sort(int[] myArray) {
int index = 1;
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] != myArray[index-1])
myArray[index++] = myArray[i];
}
return index;
}
}
The output should be:
Enter Number of Elements: 4
Enter value for num[0]: 2
Enter value for num[1]: 2
Enter value for num[2]: 3
Enter value for num[3]: 4
The inputted values are 2,2,3,4
Duplicated values 2,
The new values of the array are 2,3,4
The new length of the array is 3
The process you are using to find the duplicate elements is fine but you are not actually changing the elements in the array , you are just printing the non-duplicate ones, best approach is to change the value of the duplicate elements as a flag and then to find the length of the array after the duplicates have been removed,it will be easy :
for(int i=0;i<array.length;i++){
for(int j=i+1;j<array.length;j++)
{
if((array[i]==array[j]) && i!=j)
System.out.println("duplicate value:"array[j]);
array[j]=-1;
}
}
So, now for the array length after removing the duplicate elements is:
int count=0;
for(int i=0;i<array.length;i++){
if(array[i]!=-1)
count ++;
}

not able to sort array by ascending order

I have just started to do programming ...I am trying to sort an array in ascending order.. but not getting desired result , please point where i am doing wrong..
public static void main(String[] args) {
int count, temp;
// User inputs the array size
Scanner scan = new Scanner(System.in);
System.out.print("Enter number of elements you want in the array: ");
count = scan.nextInt();
int num[] = new int[count];
System.out.println("Enter array elements:");
for (int i = 0; i < count; i++) {
num[i] = scan.nextInt();
}
scan.close();
{
int i = 0;
while (i <= count) {
for (int j = i + 1; j < count; j++) {
if (num[i] > num[j]) {
temp = num[i];
num[i] = num[j];
num[j] = temp;
i++;
}
}
}
}
System.out.print("Array Elements in Ascending Order: ");
for (int i = 0; i < count - 1; i++) {
System.out.print(num[i] + ", ");
}
System.out.print(num[count - 1]);
}
you should increment the i outside the for loop or you can get rid of the while loop and use for loop too, you can find the code below :
import java.util.Scanner;
public class Ascending _Order
{
public static void main(String[] args)
{
int n, temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.print("Ascending Order:");
for (int i = 0; i < n - 1; i++)
{
System.out.print(a[i] + ",");
}
System.out.print(a[n - 1]);
}
}
Output:
Enter no. of elements you want in array:5
Enter all the elements: 4 3 2 6 1
Ascending Order:1,2,3,4,6
or you can use the method sort :
import java.util.Scanner;
import java.util.Arrays;
public class Ascending_Order {
public static void main(String[] args) {
int n, temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
}
Arrays.sort(a);
System.out.print("Ascending Order:");
for (int i = 0; i < n - 1; i++) {
System.out.print(a[i] + ",");
}
System.out.print(a[n - 1]);
}
}
Output:
Enter no. of elements you want in array:5
Enter all the elements: 4 3 2 6 1
Ascending Order:1,2,3,4,6

How to print results of matched numbers with a space

Just thought of a simple program to practice java coding and am stuck at the end part.,..
the code prints out the required answer (what numbers match from input compared to results for a 5 number lottery) but the answer is printed without spaces. I thought perhaps to add a "" when += to matchingNumbers but that didnt do anything!
import java.util.Scanner;
import java.util.Arrays;
public class LottoChecker
{
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
int [] yourNumbers = new int [5];
int yourInput, resultsInput;
int [] results = new int [5];
int currentNumber = 0;
String matchingNumbers = "";
for (int i=0; i<yourNumbers.length; i++)
{
System.out.println ("Enter your main numbers: " );
yourInput = in.nextInt();
yourNumbers[i]=yourInput;
}
for (int j=0; j<results.length; j++)
{
System.out.println("Enter the results from the main numbers: ");
resultsInput = in.nextInt();
results[j] = resultsInput;
}
System.out.println("Your Numbers: " +
Arrays.toString(bubbleSort(yourNumbers)));
System.out.println("The Results are: " +
Arrays.toString(results));
for (int i =0; i<yourNumbers.length;i++)
{
currentNumber = yourNumbers[i];
for (int j=0;j<results.length;j++)
if (currentNumber == results[j])
matchingNumbers += currentNumber + "";
}
System.out.println("Your matching numbers are: " +
matchingNumbers);
}
public static int [] bubbleSort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
{
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
return arr;
}
}
An elegant solution would be using StringJoiner(" ") and then add the numbers on each iteration.

why do I get -1 when i try to delete an element in an array

I checked out the questions that were already posted, but I still couldn't find a solution.
My output for the code is:
Enter the number of integers: 5
Enter 5 integers: 1
2
3
4
5
Enter the number to be deleted: 2
-1
package array;
import java.util.*;
//import java.util.ArrayLists;
public class DeleteFromArray {
public static void main(String[] args) {
int n = 0; // number of integers
int d = 0; // the number to be deleted
int count = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number of integers: ");
n = scan.nextInt();
if (n <= 0) {
System.out.println("Invalid input");
System.exit(-1);
}
int[] buffer = new int[n];
System.out.print("Enter " + n + " integers: ");
for (int k = 0; k < buffer.length; k++) {
buffer[k] = scan.nextInt();
}
System.out.print("Enter the number to be deleted: ");
d = scan.nextInt();
for (int i = 0; i < buffer.length; i++) {
if (buffer[i] == d) {
for (int j = 0; j < (buffer.length) - 1; j++) {
buffer[j] = buffer[j + 1];
}
count++;
break;
}
}
if(count ==0) {
System.out.println("Element not found!");
}
else {
System.out.print("Element Deleted Successfully..!!");
System.out.print("\nNow the New Array is :\n");
for (int i = 0; i < (buffer.length)-1; i++) {
System.out.println(buffer[i]+ " ");
}
}
scan.close();
}
}
Your for loop
for (int j = 0; j < (buffer.length) - 1; j++) {
buffer[j] = buffer[j + 1];
}
will not work properly because it will replace the value at 0 index with the value at index 1 and so on. What you want to do is just intialize the j=i where i is the index of d. and it will replace this value with the next.
for (int j = i; j < (buffer.length) - 1; j++) {
buffer[j] = buffer[j + 1];
}
Try this loop it will work.

program that reads in ten numbers and displays the number of distinct numbers and the distinct numbers separated by one space

I know that this question has been asked before, but not in the the format that I'm writing my code.. Just started taking java classes so I am not familiar with any complex java.. the code below consists of basically all the java I know. Please help! Thanks in advance.
import java.util.Scanner;
public class problem2try {
public static void main(String[] args) {
//declarations
Scanner keyboard = new Scanner (System.in);
int [] inputList = new int [10];
int [] distinctArray = new int [10];
int num;
int counter = 0;
//input
System.out.print("Please enter in 10 integers: ");
for (int i = 0; i < inputList.length; i++)
{
num = keyboard.nextInt();
inputList[i] = num;
}
//processing
distinctArray[0] = inputList[0];
for (int i = 1; i < inputList.length; i++)
{
for (int j = 0; j < inputList.length; j++)
{
if (inputList[i] == inputList[j])
{
counter++;
continue;
}
else
{
distinctArray[i] = inputList[i];
}
}
}
//output
System.out.println("The number of distinct numbers is " + counter);
System.out.print("The distict numbers are: ");
for (int x=0; x<distinctArray.length; x++)
{
if (distinctArray[x] != 0)
System.out.print(distinctArray[x] + " ");
}
}
}
Your logic in the "processing" block seemed off. I modified it to check the current number (outer loop) to all of the known numbers (inner loop). If no match was found, it is appended to the list of known numbers and the count is incremented.
I also modified the "output" code to print the first counter numbers from the list of known numbers. Values past that index are uninitialized.
import java.util.Scanner;
public class problem2try {
public static void main(String[] args) {
//declarations
Scanner keyboard = new Scanner (System.in);
int [] inputList = new int [10];
int [] distinctArray = new int [10];
int num;
int counter = 0;
//input
System.out.print("Please enter in 10 integers: ");
for (int i = 0; i < inputList.length; i++)
{
num = keyboard.nextInt();
inputList[i] = num;
}
//processing
for (int i = 0; i < inputList.length; i++)
{
boolean found = false;
for (int j = 0; j < counter; j++)
{
if (inputList[i] == distinctArray[j])
{
found = true;
break;
}
}
if (!found)
{
distinctArray[counter++] = inputList[i];
}
}
//output
System.out.println("The number of distinct numbers is " + counter);
System.out.print("The distict numbers are: ");
for (int x=0; x<counter; x++)
{
System.out.print(distinctArray[x] + " ");
}
}
}

Categories