When user enter number 1 smaller than number 2 swap does not work,
but when number 1 is larger than number 2 it works. I don't understand why this is occurring. I would appreciate some suggestions or help.
package javaapplication36;
public class JavaApplication36 {
static Scanner s = new Scanner(System.in);
// main method
public static void main(String[] args) {
int[] arr = new int[10];
input(arr);
System.out.println("Enter n1 :");
int n1 = s.nextInt();
System.out.println("Enter n2 : ");
int n2 = s.nextInt();
display(arr);
int temp = 0;
int index_a = index(arr, n1);
int index_b = index(arr, n2);
if (index(arr, n1) != -1 && index(arr, n2) != -1) {
temp = arr[index_a];
arr[index_a] = arr[index_b];
arr[index_b] = temp;
}
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println();
}
public static void display(int[] arr) {
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println();
}
public static void input(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.println("Enter number : " + (i + 1));
arr[i] = s.nextInt();
}
}
public static int index(int[] arr, int n) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == n)
return i;
}
return -1;
}
}
I tried this and could not find anything wrong. To make debugging this easier I recommend you populate your array using random numbers.
Create an instance of Random
Random rand = new Random();
And assign the output to your array variable.
arr = rand.ints(10,1,15).toArray();
The arguments to rand.ints are.
10 - the number of elements
1 - the start of the range of numbers
15 - the end of the range (not including that number)
So that call would generate 10 numbers from 1 to 14 inclusive.
One possibility for any problems could be duplicate numbers in your array and finding the correct one to swap. But I was unable to reproduce the error.
Related
I got a task to write the methods to 1. take information in and save it into array, 2. to copy the array(only with previously given arguments) and 3. to sort the array to be in descending order. it seems to me like i got the first 2 parts working but i have been stuck on the third method for 2 days without any progress. i am still learning java so i'm pretty sure i have made a dumb mistake somewhere. thanks in advance.
import java.util.*;
public class RevisionExercise {
public static void main(String[] args) {
int[] tempArray = new int[100];
System.out.println("Type in numbers. Type zero to quit.");
int amountOfNumbers = askInfo(tempArray);
int[] realArray = new int[amountOfNumbers];
copyInfo(realArray, tempArray);
setArray(realArray);
printArray(realArray);
}
public static int askInfo(int[] tempArray) {
Scanner reader = new Scanner(System.in);
int i;
for (i = 0; i < tempArray.length; i++) {
System.out.print((i+1) + ". number: ");
tempArray[i] = reader.nextInt();
if (tempArray[i] == 0) {
return tempArray[i];
}
}
return i;
}
private static int[] copyInfo(int[] realArray, int[] tempArray)
{
int targetIndex = 0;
for( int sourceIndex = 0; sourceIndex < tempArray.length; sourceIndex++ )
{
if( tempArray[sourceIndex] != 0 )
tempArray[targetIndex++] = tempArray[sourceIndex];
}
realArray = new int[targetIndex];
System.arraycopy( tempArray, 0, realArray, 0, targetIndex );
return realArray;
}
public static int[] setArray(int[] realArray)
{
int temp = 0;
for (int i = 0; i <realArray.length; i++) {
for (int j = i+1; j <realArray.length; j++) {
if(realArray[i] >realArray[j]) {
temp = realArray[i];
realArray[i] = realArray[j];
realArray[j] = temp;
}
}
}
return realArray;
}
public static void printArray(int[] realArray ) {
System.out.println("\nOrdered array: ");
for(int i = 0; i < realArray .length; i++) {
System.out.println(realArray [i]);
}
}
}
the output i'm getting looks like this.
Type in numbers. Type zero to quit.
1. number: 3
2. number: 8
3. number: 5
4. number: 6
5. number: 9
6. number: 0
Ordered array:
while it should look like this:
Type in numbers. Type zero to quit.
1. number: 3
2. number: 8
3. number: 5
4. number: 6
5. number: 9
6. number: 0
Ordered array:
9
8
6
5
3
You made a mistake in calculating the total numbers entered by the user. Your function always return 0. So change it to something like this:
public static int askInfo(int[] tempArray) {
Scanner reader = new Scanner(System.in);
int totalNumbers = 0;
for (int i = 0; i < tempArray.length; i++) {
System.out.print((i+1) + ". number: ");
int number = reader.nextInt();
if (number != 0) {
totalNumbers++;
tempArray[i] = number;
} else {
break;
}
}
return totalNumbers;
}
Chage the sort function to this:
public static void setArray(int[] realArray) {
int temp = 0;
for (int i = 0; i < realArray.length; i++) {
for (int j = i+1; j < realArray.length; j++) {
// Use < for descending order and > for ascending order
if(realArray[i] < realArray[j]) {
temp = realArray[i];
realArray[i] = realArray[j];
realArray[j] = temp;
}
}
}
}
Your main program
public static void main(String[] args) {
int[] tempArray = new int[100];
System.out.println("Type in numbers. Type zero to quit.");
int amountOfNumbers = askInfo(tempArray);
int[] realArray = new int[amountOfNumbers];
copyInfo(tempArray, realArray, amountOfNumbers);
setArray(realArray);
printArray(realArray);
}
public static int askInfo(int[] tempArray) {
Scanner reader = new Scanner(System.in);
int totalNumbers = 0;
for (int i = 0; i < tempArray.length; i++) {
System.out.print((i+1) + ". number: ");
int number = reader.nextInt();
if (number != 0) {
totalNumbers++;
tempArray[i] = number;
} else {
break;
}
}
return totalNumbers;
}
private static void copyInfo(int[] tempArray, int[] realArray, int size) {
for( int sourceIndex = 0; sourceIndex < size; sourceIndex++ )
{
realArray[sourceIndex] = tempArray[sourceIndex];
}
}
public static void setArray(int[] realArray) {
int temp = 0;
for (int i = 0; i < realArray.length; i++) {
for (int j = i+1; j < realArray.length; j++) {
if(realArray[i] < realArray[j]) {
temp = realArray[i];
realArray[i] = realArray[j];
realArray[j] = temp;
}
}
}
}
public static void printArray(int[] realArray ) {
System.out.println("\nOrdered array: ");
for(int i = 0; i < realArray.length; i++) {
System.out.println(realArray [i]);
}
}
To begin with, in the askInfo method, the size of the realArray will always be 0, since amountOfNumbers is the return of
if (tempArray[i] == 0) {
return tempArray[i];
}
because your condition is tempArray[i] == 0, hence you are always returning 0. Then your copyInfo method is returning an array but you have nothing receiving the returned array. I would suggest changing your copyInfo method to
private static int[] copyInfo(int[] tempArray)
{
// same
int [] realArray = new int[targetIndex];
// same
}
and your main method to
public static void main(String[] args) {
//same
int[] realArray = new int[amountOfNumbers];
realArray = copyInfo(tempArray);
// same
}
General remark: Each of your methods returns an array but you never use this return value.
There are 2 modifications necessary to fix your code:
Keep the value of the method output:
realArray=copyInfo(realArray, tempArray);
So you put the result of the copy in the realArray variable.
You expect the askInfo method to return the number of entered numbers but in fact you return the value of the last entered number.
So instead of return tempArray[i]; you have to return i;
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 2 years ago.
I'm creating a program that uses two methods to print all the odd numbers in an array and then get the sum of the odd numbers. However, I'm getting an output that makes no sense. This is the code that I'm using:
public class ArrayMethods1 {
public static int[] printOdds(int[]arrayExample) {
int i;
String oddNum = "";
int [] newArray = new int [3];
int x = 0;
for (i = 0; i < arrayExample.length; i++) {
if (arrayExample[i] % 2 != 0) {
System.out.print(arrayExample[i] + " ");
}
}
int[] sumOfOdds = new int [1];
sumOfOdds = sumOdds(newArray);
return sumOfOdds;
}
public static int[] sumOdds(int[]arrayExample1) {
int i;
int[] oddsTotal = new int[1];
int total = 0;
for (i = 0; i < arrayExample1.length; i++) {
if (arrayExample1[i] % 2 != 0) {
total = total + arrayExample1[i];
}
}
oddsTotal[0] = total;
return oddsTotal;
}
public static void main(String[] args) {
int [] mainArray = new int [5];
mainArray[0] = 17;
mainArray[1] = 92;
mainArray[2] = 21;
mainArray[3] = 984;
mainArray[4] = 75;
printOdds(mainArray);
int [] oddSum = new int[1];
oddSum = sumOdds(mainArray);
System.out.println(oddSum);
}
}
And I'm getting this as output:
17 21 75 [I#51016012
I have absolutely no idea where that second part is coming from, so any help would be awesome. Thanks!
well you are storing the result of the sum in an array and then you print the reference of type int[], that's why you get [I#51016012. so you need to print oddSum[0].
It is not quite clear why you return int[] from the methods that just print and calculate the sum of the odd numbers.
So the code could be enhanced:
public static void printOdds(int[] arr) {
for (int n : arr) {
if (n % 2 == 1) {
System.out.print(n + " ");
}
}
System.out.println();
}
public static int sumOdds(int[] arr) {
int total = 0;
for (int n : arr) {
if (n % 2 == 1) {
total += n;
}
}
return total;
}
Also, it may be worth to use Java 8+ stream to implement both tasks in one run:
import java.util.Arrays;
public class PrintAndSumOdds {
public static void main(String [] args){
int[] arr = {17, 92, 21, 984, 75};
int sumOdds = Arrays.stream(arr) // get IntStream from the array
.filter(n -> n % 2 == 1) // filter out the odds
.peek(n -> System.out.print(n + " ")) // print them in one line
.sum(); // and count the sum (terminal operation)
System.out.println("\nTotal odds: " + sumOdds);
}
}
Output:
17 21 75
Total odds: 113
I'm new to Java programming and I want to know how to swap the position of the highest number and the lowest number.
import java.util.*;
public class HighestandLowestNum
{
static Scanner data = new Scanner (System.in);
public static void main(String[]args)
{
int num [] = new int [10];
int i;
System.out.println("Enter 10 numbers: ");
for (i = 0; i < num.length; i++)
{
num [i] = data.nextInt();
Highest(num);
Lowest(num);
}
System.out.println("The highest number is: " + Highest(num));
System.out.println("The lowest number is: " + Lowest(num));
}
public static int Highest(int[] num)
{
int highest = num[0];
int i;
for (i = 1; i < num.length; i++)
{
if (num[i] > highest)
{
highest = num[i];
}
}
return highest;
}
public static int Lowest(int[] num)
{
int lowest = num[0];
int i;
for (i = 1; i < num.length; i++)
{
if (num[i] < lowest)
{
lowest = num[i];
}
}
return lowest;
}
}
This is my program. Please help me to fix my problem.
Your two functions Highest and Lowest return the value of the highest and lowest numbers. In order to swap them, you need to know the positions those values have within the array.
If you alter those functions or create new ones to return the index of the highest and lowest values, then you can swap them with what you've probably already seen before:
pseudocode:
temp = first
first = last
last = temp
To Swap the two numbers in the array, you need to know the numbers and their position as mentioned in the earlier answers. You can modify the two functions in such a way that they provide Numbers as well as their Position. One way to do this is to return an array instead of integer from the function. And in that array, information about the number and its position can be encapsulated. Ill show you what I mean in the code I am providing:
static Scanner data = new Scanner (System.in);
public static void main(String[]args)
{
int num []= new int [10];
int i;
System.out.println("Enter 10 numbers: ");
for (i = 0; i <num.length; i++)
{
num [i] = data.nextInt();
Highest(num);
Lowest(num);
}
System.out.print("The original array is");
for (i = 0; i <num.length; i++)
{
System.out.print(" "+num[i]);
}
System.out.println("");
int highest = Highest(num)[0];
int lowest = Lowest(num)[0];
int highestPosition = Highest(num)[1];
int lowestPosition = Lowest(num)[1];
System.out.println("The highest number is: " +highest+" at position "+highestPosition);
System.out.println("The lowest number is: " +lowest+" at position "+lowestPosition);
//Swap//
num[highestPosition] = lowest;
num[lowestPosition] = highest;
System.out.print("The new array is");
for (i = 0; i <num.length; i++)
{
System.out.print(" "+num[i]);
}
}
public static int[] Highest(int[] num)
{
int highest = num[0];
int i;
int index = 0;
int[] result = {highest,index};
for (i = 1; i <num.length;i++)
{
if (num[i] > highest)
{
highest = num[i];
index = i;
result[0] = highest;
result[1] = index;
}
}
return result;
}
public static int[] Lowest(int[] num)
{
int lowest = num[0];
int i;
int index = 0;
int[] result = {lowest,index};
for (i = 1; i <num.length;i++)
{
if (num[i] < lowest)
{
lowest = num[i];
index = i;
result[0] = lowest;
result[1] = index;
}
}
return result;
}
Try reading the modification in the Highest and Lowest functions and than go through the main code. Hope this helps.
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class Queuessorting {
public static int randInt(int min, int max) {
// Usually this should be a field rather than a method variable so
// that it is not re-seeded every call.
Random rand = new Random();
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static void main(String[] args){
Scanner myScanner = new Scanner(System.in);
ArrayList<Integer> ar = new ArrayList<Integer>();
ArrayList<Integer> temp = new ArrayList<Integer>();
ArrayList<Integer> arf = new ArrayList<Integer>();
System.out.println("Enter n: ");
int n = myScanner.nextInt();
int count = 0;
int r=0;
for(int i = 0;i < n;i++){
ar.add(randInt(1,99));
}
System.out.println(ar.size());
for(int i=0;i<ar.size();i++)
System.out.println(ar.get(i));
int j=0;
int nctr=0;
while(ar.size() > 0){
int a = 0;
int nct = 0;
a = ar.remove(0);
if(nctr == 0){
temp.add(a);
}
else{
if(arf.size() != 0){
for(int k = 0;k<arf.size();k++){
temp.add(arf.remove(0));
}
}
while(r<temp.size() && count == 0) {
if(a > temp.get(r)){
arf.add(a);
count++;
nct++;
}
else
arf.add(temp.remove(0));
r++;
}
if(nct == 0)
arf.add(a);
}
if(temp.size()!=0){
for(int l = 0;l<temp.size();l++){
arf.add(temp.remove(0));
}
}
nctr++;
}
System.out.println("***************************");
for(int u=0;u<arf.size();u++)
System.out.println(arf.get(u));
}
}
My code works perfectly fine when having an input of 2 but if I enter any number greater than 2 the sorting is completely messed up. I'am sorting descending order being the top the number the first index of the arraylist
pseudocode: example : 72,97,2 a will get 72 from ar then store it to temp because it is the first one, next a will get 97 and compare it to 72 if a > 72, a will go to arf then the remaining values in temp will go to arf too : 92,72 <- contents of arf now. After that procedure everything in arf will go to temp and the loop goes on and on I hope you understand my explanation :(
the final output or the final arf contents will be 97,72,2
This code takes a random sampling of numbers, plugs them into an array, counts the odd numbers, and then lets the user pick an integer to see if it matches. This works great now with just arrays, but I want to convert it to work with ArrayLists. What's the easiest way to do this?
import java.util.Scanner;
import java.util.Random;
public class ArrayList {
public static void main(String[] args) {
// this code creates a random array of 10 ints.
int[] array = generateRandomArray(10);
// print out the contents of array separated by the delimeter
// specified
printArray(array, ", ");
// count the odd numbers
int oddCount = countOdds(array);
System.out.println("the array has " + oddCount + " odd values");
// prompt the user for an integer value.
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer to find in the array:");
int target = input.nextInt();
// Find the index of target in the generated array.
int index = findValue(array, target);
if (index == -1) {
// target was not found
System.out.println("value " + target + " not found");
} else {
// target was found
System.out.println("value " + target + " found at index " + index);
}
}
public static int[] generateRandomArray(int size) {
// this is the array we are going to fill up with random stuff
int[] rval = new int[size];
Random rand = new Random();
for (int i = 0; i < rval.length; i++) {
rval[i] = rand.nextInt(100);
}
return rval;
}
public static void printArray(int[] array, String delim) {
// your code goes here
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
if (i < array.length - 1)
System.out.print(delim);
else
System.out.print(" ");
}
}
public static int countOdds(int[] array) {
int count = 0;
// your code goes here
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 == 1)
count++;
}
return count;
}
public static int findValue(int[] array, int value) {
// your code goes here
for (int i = 0; i < array.length; i++)
if (array[i] == value)
return i;
return -1;
}
}
I rewrite two of your functions,maybe they will useful for you.
public static List<Integer> generateRandomList(int size) {
// this is the list we are going to fill up with random stuff
List<Integer> rval = new ArrayList<Integer>(size);
Random rand = new Random();
for (int i = 0; i < size; i++) {
rval.add(Integer.valueOf(rand.nextInt(100)));
}
return rval;
}
public static int countOdds(List<Integer> rval) {
int count = 0;
for (Integer temp : rval) {
if (temp.intValue() % 2 == 1) {
count++;
}
}
return count;
}