I'm new to Java. I've spent hours trying to figure out why this code doesn't work. It's supposed to take user input integers separated by whitespace, and load them into an int array. Then, the numbers are supposed to be sorted in descending order, and the frequency of repeated inputs has to be displayed in a separate int array.
I'm getting zeroes in the output though. Can anyone help me fix this program?
This is what I have:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] inputNumbers = new int[50];
int[] ocurrences = new int[50];
int size = 0;
System.out.println("How many numbers to enter? (At most 50)");
size = input.nextInt();
System.out.println("Enter eaach of the numbers. Please put a space between each number.");
String arrayString = input.next();
input = new Scanner(arrayString);
while(input.hasNextInt())
{
int nextNumber = input.nextInt();
if(!isInArray(inputNumbers, size, nextNumber))
{
inputNumbers[size] = nextNumber;
ocurrences[size] = 1;
size++;
}
else
{
int index = search(inputNumbers, size, nextNumber);
ocurrences[index]++;
}
}
sort(inputNumbers, ocurrences, size);
System.out.println("N\t\tCount");
for(int i = 0; i < size; i++)
{
System.out.println(inputNumbers[i] + "\t\t" + ocurrences[i]);
}
}
public static void sort(int[] inputNumbers, int[] ocurrences, int size)
{
for(int current = 0; current < size; current++)
{
int max = current;
for(int i = current; i < size; i++)
{
if(inputNumbers[i] > inputNumbers[max])
max = i;
}
int temp = inputNumbers[max];
inputNumbers[max] = inputNumbers[current];
inputNumbers[current] = temp;
temp = ocurrences[max];
ocurrences[max] = ocurrences[current];
ocurrences[current] = temp;
}
}
public static int search(int[] array, int size, int number)
{
for(int i = 0; i < size; i++)
{
if(array[i] == number)
return i;
}
return -1;
}
public static boolean isInArray(int[] array, int size, int number)
{
for(int i = 0; i < size; i++)
{
if(array[i] == number)
return true;
}
return false;
}
}
The current output is:
How many numbers to enter? (At most 50)
4
Enter eaach of the numbers. Please put a space between each number.
5 5 4 7 8
N Count
5 1
0 0
0 0
0 0
0 0
BUILD SUCCESSFUL (total time: 11 seconds)
It should have been something like
N Count
8 1
7 1
5 2
4 1
Initialize the array where we know the exact size, so it avoid unnecessary memory utilization.
Also input.next() will read only the next complete token not the entire line. That was the mistake in the code.
Finally the scanner resource was not closed.
I have refactored your code, please check it.
public static void main(String[] args) {
Scanner input = null;
try {
input = new Scanner(System.in);
int[] inputNumbers, ocurrences;
int index = 0, size;
System.out.println("How many numbers to enter? (At most 50)");
size = input.nextInt();
inputNumbers = new int[size];
ocurrences = new int[size];
System.out.println("Enter each of the numbers. Please put a space between each number.");
for (int i = 0; i < size; i++) {
int nextNumber = input.nextInt();
if (!isInArray(inputNumbers, nextNumber)) {
inputNumbers[index] = nextNumber;
ocurrences[index] = 1;
index++;
} else {
int oIndex = search(inputNumbers, nextNumber);
ocurrences[oIndex] ++;
}
}
sort(inputNumbers, ocurrences);
System.out.println("N\t\tCount");
for (int i = 0; i < index; i++) {
System.out.println(inputNumbers[i] + "\t\t" + ocurrences[i]);
}
} finally {
input.close();
}
}
public static void sort(int[] inputNumbers, int[] ocurrences) {
int size = inputNumbers.length;
for (int current = 0; current < size; current++) {
int max = current;
for (int i = current; i < size; i++) {
if (inputNumbers[i] > inputNumbers[max])
max = i;
}
int temp = inputNumbers[max];
inputNumbers[max] = inputNumbers[current];
inputNumbers[current] = temp;
temp = ocurrences[max];
ocurrences[max] = ocurrences[current];
ocurrences[current] = temp;
}
}
public static int search(int[] array, int number) {
int size = array.length;
for (int i = 0; i < size; i++) {
if (array[i] == number)
return i;
}
return -1;
}
public static boolean isInArray(int[] array, int number) {
int size = array.length;
for (int i = 0; i < size; i++) {
if (array[i] == number)
return true;
}
return false;
}
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;
I have made this program using array concept in java. I am getting Exception as ArrayIndexOutOfBound while trying to generate product.
I made the function generateFNos(int max) to generate factors of the given number. For example a number 6 will have factors 1,2,3,6. Now,i tried to combine the first and the last digit so that the product becomes equal to 6.
I have not used the logic of finding the smallest number in that array right now. I will do it later.
Question is Why i am getting Exception as ArrayIndexOutOfBound? [i couldn't figure out]
Below is my code
public class SmallestNoProduct {
public static void generateFNos(int max) {
int ar[] = new int[max];
int k = 0;
for (int i = 1; i <= max; i++) {
if (max % i == 0) {
ar[k] = i;
k++;
}
}
smallestNoProduct(ar);
}
public static void smallestNoProduct(int x[]) {
int j[] = new int[x.length];
int p = x.length;
for (int d = 0; d < p / 2;) {
String t = x[d++] + "" + x[p--];
int i = Integer.parseInt(t);
j[d] = i;
}
for (int u = 0; u < j.length; u++) {
System.out.println(j[u]);
}
}
public static void main(String s[]) {
generateFNos(6);
}
}
****OutputShown****
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at SmallestNoProduct.smallestNoProduct(SmallestNoProduct.java:36)
at SmallestNoProduct.generateFNos(SmallestNoProduct.java:27)
at SmallestNoProduct.main(SmallestNoProduct.java:52)
#Edit
The improved Code using array only.
public class SmallestNoProduct {
public static void generateFNos(int max) {
int s = 0;
int ar[] = new int[max];
int k = 0;
for (int i = 1; i <= max; i++) {
if (max % i == 0) {
ar[k] = i;
k++;
s++;
}
}
for (int g = 0; g < s; g++) {
System.out.println(ar[g]);
}
smallestNoProduct(ar, s);
}
public static void smallestNoProduct(int x[], int s) {
int j[] = new int[x.length];
int p = s - 1;
for (int d = 0; d < p;) {
String t = x[d++] + "" + x[p--];
System.out.println(t);
int i = Integer.parseInt(t);
j[d] = i;
}
/*for (int u = 0; u < j.length; u++) {
System.out.println(j[u]);
}*/
}
public static void main(String s[]) {
generateFNos(6);
}
}
Maybe it better:
public class SmallestNoProduct {
public static int smallest(int n) {
int small = n*n;
for(int i = 1; i < Math.sqrt(n); i++) {
if(n%i == 0) {
int temp = Integer.parseInt(""+i+""+n/i);
int temp2 = Integer.parseInt(""+n/i+""+i);
temp = temp2 < temp? temp2: temp;
if(temp < small) {
small = temp;
}
}
}
return small;
}
public static void main(String[] args) {
System.out.println(smallest(6)); //6
System.out.println(smallest(10)); //25
System.out.println(smallest(100)); //205
}
}
Problem lies in this line
String t=x[d++]+""+x[p--];
x[p--] will try to fetch 7th position value, as p is length of array x i.e. 6 which results in ArrayIndexOutOfBound exception. Array index starts from 0, so max position is 5 and not 6.
You can refer this question regarding postfix expression.
Note: I haven't checked your logic, this answer is only to point out the cause of exception.
We are unnecessarily using array here...
below method should work....
public int getSmallerMultiplier(int n)
{
if(n >0 && n <10) // if n is 6
return (1*10+n); // it will be always (1*10+6) - we cannot find smallest number than this
else
{
int number =10;
while(true)
{
//loop throuogh the digits of n and check for their multiplication
number++;
}
}
}
int num = n;
for(i=9;i>1;i--)
{
while(n%d==0)
{
n=n/d;
arr[i++] = d;
}
}
if(num<=9)
arr[i++] = 1;
//printing array in reverse order;
for(j=i-1;j>=0;j--)
system.out.println(arr[j]);
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.
I'm not sure if anyone is familiar with the game cows and bulls. Basically I'm trying to write a method that is a user enters in a number of 1234 and another user enters in 4305 this will give them 2 cows because the numbers are in the first number but in the wrong index. If they are in the same index then they get a bull. I must call methods that I have previously coded. I have it to where it counts the number of correct numbers found in the first number given but I can't figure out how to get it to NOT count them if they are in the same index. Any advice would be great.
public static int numDigits(int number)
{
int counter = 0;
while(number !=0)
{
int digit = number % 10;
number= number /10;
counter++;
}
return counter;
}
public static int getDigit(int number, int i)
{
int negative =-1;
int counter = 0;
int digit = 0;
if(i>numDigits(number)|| i == 0)
{
return negative;
}
while(counter < i)
{
digit = number % 10;
number = number / 10;
counter++;
}
return digit;
}
public static int indexOf (int number, int digit)
{
int counter = 0;
int negative = -1;
for(int i = 0; i<=numDigits(number); i++)
{
counter++;
if(getDigit(number,i)== digit)
{
return counter-1;
}
}
return negative;
}
public static int getCows(int first, int second)
{
int counter = 0;
for(int i = 0; i<numDigits(first); i++)
{
if(getDigit(first,i)==getDigit(second,i))
{
counter++;
}
}
return counter;
}
Threw this together for fun (running in groovy console, possibly not perfectly valid java).
public static int[] getCowsBulls(int match, int guess)
{
Character[] matchChars = Integer.toString(match).getChars();
Character[] guessChars = Integer.toString(guess).getChars();
int minLen = Math.min(matchChars.length, guessChars.length);
Set<Character> matchSet = new HashSet<>();
matchSet.addAll(matchChars);
int cows = 0;
int bulls = 0;
for(int i = 0; i < minLen; i++) {
Character gc = guessChars[i];
boolean inMatch = matchSet.contains(gc);
if(!inMatch) { continue; }
if(matchChars[i].equals(gc)) {
bulls++;
} else {
cows++;
}
}
return new Integer[]{ cows, bulls };
}
You are asking how to not count the bulls as cows?
public static int getCows(int first, int second)
{
int counter = 0;
for(int i = 0; i<numDigits(first); i++)
{
for(int j = 0; i<numDigits(second); j++)
{
if(j!=i && getDigit(first,i)==getDigit(second,j) )
{
counter++;
}
}
}
return counter;
}
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;
}