I am having issues with this array code. It needs to have a number count that displays the numbers that are entered by the user. So for instance, if the user enters three four's it will say "4 3." I already have the majority of the code done, but it is just returning the first number that's entered.
import java.util.Scanner;
public class NumberCounts
{
public static void main(String args[])
{
int[] answer = new int [100];
inputArray(answer);
}
public static void inputArray(int[] Numbercounts)
{
System.out.println("This Program is written by Benjamin Barcomb\n");
Scanner kb = new Scanner(System.in);
System.out.print("How many numbers will you enter? : ");
kb.nextInt();
//int[] answer = new int[100];
int arryNum[] = new int[] {};
System.out.println("\nEnter numbers in [0, 100] range separated by a space:");
int input = kb.nextInt();
System.out.println("Number Count");
int[] counter = new int[] {input};
for (int i = 0; i < arryNum.length; i++) {
System.out.println(" " + (i + 1) + " " + counter[i]);
}
for (int i = 0; i < counter.length; i++) {
System.out.println(" " + (i + 1) + " " + counter[i]);
}
}
}
Where to start...
1) You create an array answer of length 100, pass it to your method, then never use it anywhere.
2) You ask the user to tell you how many numbers they are going to enter, you get that input with kb.nextInt(), then do nothing with it. You never assign that int to a variable.
3) You create an array arryNum and leave it empty. You never put anything into it, ever.
4) You ask the user to input numbers separated by spaces. You then take only the first int they enter.
Since it seems like you are just learning I will leave the coding to you. Hopefully if you can now see what certain parts of your code are doing you will be able to move on from there. My one tip would be to use more descriptive variable names. It makes it easier for you to read what is going on when you look at your code.
Some Solutions
1) Unless the requirements say you must pass an array into the inputArray() method, I would just remove it all together since you are doing all the other work in the method. I would remove int[] answer = new int [100]; call the method with no parameters inputArray() and change the signature of the method to just
public static void inputArray() { ... }
2) When you ask the user how many numbers they are going to enter you are basically asking them "How long should my array be?" When you get this int you should use it to make your new array. Something like
System.out.print("How many numbers will you enter? ");
int usersNumbers = new int[kb.nextInt()];
Notice I have changed the name of arrayNum to usersNumbers. It's more descriptive and makes reading your code easier.
3) Now you want to get all those numbers and put them into that array. Since you need to get multiple numbers you will need a loop. Again, unless the requirements say you have to, I would do this a bit differently. Instead of entering all the numbers on one line separated by spaces, I would ask for the numbers individually. Since we know the length of the array (how many numbers they are going to enter), we know how many times to prompt them.
System.out.println("\nEnter numbers in [0, 100] range.\n");
for (int i = 0; i < usersNums.length; i++) {
System.out.println("Enter Your Number:");
usersNums[i] = kb.nextInt();
}
4) Now onto counting the number of occurrences of each int entered. Since the user can enter their numbers in any random order it makes things tougher. Again, I'm not sure what exactly your requirements allow or not, but here is what I did. First I want to get a list of the unique numbers. For example, if the array is {2, 4, 2, 5, 2, 4} I want to get a list with {2, 4, 5}. Once I have that I can look at each of those numbers and go through the array counting how many times I see each one. An easy way to get a list of unique numbers is to put them into a Set. It is a data structure which doesn't allow duplicates. A TreeSet is a Set which puts the numbers in order, just to make it easier to read.
Set<Integer> uniqueNumbers = new TreeSet<Integer>();
for (int i : usersNums) { uniqueNumbers.add(i); }
Now that I have the list of unique numbers I can start counting. I start count at 0. Then for every number in the set, I look at every number in the array and see if they are the same. If they are, count goes up by 1. Once I get to the end of the array I print my results for that number, then reset count to 0.
int count = 0;
for (Integer i : uniqueNumbers) { //For every number in the Set
for (int j = 0; j < usersNums.length; j++) { //Look at every number in the array
if (i == usersNums[j]) { count++; } //If the same, count++
}
System.out.print(i + " - " + count + "\n"); //Print results
count = 0; //Reset Count
}
It seems you're only getting the first value because you only called nextInt() on your scanner once. You should ideally have a while loop to keep gathering user input. Also, I think you're trying to store your answers in an array, which really isn't ideal since you don't know how big your input will be. You should really use a list. Something along the lines of
List<Integer> data = new ArrayList<Integer>();
while (kb.hasNext()) {
data.add(kb.next());
}
Explain your code hope you understand how to fix it.
First, I assume you want your user to enter more than one number but you use nextInt which means
The java.util.Scanner.nextInt() method Scans the next token of
the input as an int.An invocation of this method of the form
nextInt() behaves in exactly the same way as the invocation
nextInt(radix), where radix is the default radix of this scanner.
Suggestion: try to use to while loop to read more number and quite when your user enter -999999 for example as a termination for your while loop.
Second, use Array is not right data structure to use because you do not know the size of array.
There are 2 ways to fix this issue:
1. first to ask the size of array from the user like how many numbers the user wants to input which is not what you want.
2. use another data structure that shrinks and expands by itself which is ArrayList
Third, you did not say whether you gonna have different numbers in your input like
1 1 2 3 3 4 4 5 or unsorted like `1 2 1 4 3 4 5`
or just your input includes the same numbers like
2 2 2 2 2 2 2
More info for third point is here
Related
Hi people I made code to calculate greatest common divisor of 2 number.
It work good but I get many outputs. I want the greatest output but I don't know how to fix it?
What my code do is this here: You enter 2 integer. The first integer must be greater than the second. Now code check second integer first. Is it dividable by 1, 2, 3, 4, 5, .. Then code check all working numbers with first number. In the end we have greatest common divisor.
And before code does all it, it check if second number divide first (in case second is the gcd).
Now my problem: Let's take input 36 and 14. My code will give output
1
2
But how can I avoid code also print all other working numbers? I only want printed the greatest working number but no idea how to implement this in my code? I also don't want copy other code because I did all myself till here and proud:
import java.util.Scanner;
public class Testit{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
double x = input.nextDouble();
double y = input.nextDouble();
double first=0;
first=x/y;
if(first==(int)first){
System.out.println((int)y);
return;
}
else{
for(double i=1; i<x && i<y; i++){
double sum=0;
sum=y/i;
if(sum==(int)sum){
double temp=0;
temp=x/i;
if(temp==(int)temp){
System.out.println((int)i);
}
}
}
}
}
}
Instead of printing, save the result in a temporary variable
double first=0;
int greatestCommonDivisor = 1;
...
if(temp==(int)temp){
greatestCommonDivisor = Double.valueOf(i).intValue();
}
...
System.out.println("Greatest common divisor:" + greatestCommonDivisor);
That said, there are a lot of places your algorithm and code could be improved. For a start you should think about starting at the largest possible number and just stopping when you found the first common divisor (because that would be the greatest) instead of looping through all possible numbers starting from the smallest possible number. And you should have a look at the modulo operation and use integers instead of doubles for your values.
You have to change your code; for example like this:
Currently, your code is simply printing each time it finds a "match".
Instead of printing immediately, you push that value into a helper variable. And in the end; when your loop has ended, you simply print that helper variable!
Then you automatically print the last number that your algorithm computed and stored.
( I am not giving you any code here; just an idea - as you will learn more by writing the code yourself! )
In this lab, you will be creating a program that merges two arrays of positive (greater than 0) integers. Your program will accept each array as input from the keyboard. You do not know ahead of time how many values will be entered, but you can assume each array will have a maximum length of 10,000 elements. To stop entering values enter zero or a negative number. You should disregard any non-positive numbers input and not store these in the array.
The elements of the two input arrays should be in increasing order. In other words, each array element must have a value that is greater than or equal to the previous element value. An array may contain repeated elements.
After the two arrays have been input, your program must check to make sure the elements of each array have been entered in order. If an out of order element is found, print the message “ERROR: Array not in correct order”.
Your task is to merge the two input arrays into a new array, with all elements in order, lowest to highest. Print out each of the original arrays entered, followed by the merged array.
Please note that your program must output the arrays with exactly one space between each of the numbers.
Sample Run 1:
Enter the values for the first array, up to 10000 values, enter zero or a negative number to quit
3
3
5
6
8
9
-1
Enter the values for the second array, up to 10000 values, enter zero or a negative number to quit
3
4
5
6
-5
First Array:
3 3 5 6 8 9
Second Array:
3 4 5 6
Merged Array:
3 3 3 4 5 5 6 6 8 9
My code was:
import java.util.Scanner;
class Main{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int one1=0;
int two1=0;
int a = 0;
int b = 0;
int flag = 0;
int[]one=new int[10000];
int[]two=new int[10000];
System.out.println("Enter the values for the first array, up to 10000 values, enter a negative number to quit");
while (a==0){
int first = scan.nextInt();
if (first<=0) a++;
else{
one[one1]=first;
one1++;
}
}
System.out.println("Enter the values for the second array, up to 10000 values, enter a negative number to quit");
while (b==0){
int second = scan.nextInt();
if (second<=0) b++;
else{
two[two1]=second;
two1++;
}
}
System.out.println("First Array:");
for (int i = 0 ; i < one1 ; i++){
System.out.print(one[i]+" ");
}
for (int i = 0 ; i < one.length-1 ; i++){
if (one[i]>one[i+1]) flag++;
}
System.out.println("Second Array:");
for (int i = 0 ; i < two1 ; i++){
System.out.print(two[i]+" ");
}
for (int i = 0 ; i < two.length-1 ; i++){
if (two[i]>two[i+1]) flag++;
}
int[]combo = new int[one.length+two.length];
for (int i = 0 ; i < combo.length-1 ; i+=2){
combo[i]=one[i];
combo[i+1]=two[i];
}
if (flag>0) System.out.println("ERROR: Array not in correct order");
else{
for (int i = 0 ; i < combo.length; i++){
System.out.print(combo[i]+" ");
}
}
}
}
This code keeps giving me runtime error- what am I doing wrong?
I am sorry, your merge algortithm is all wrong. You create an array combo of length one.length + two.length, that is, 20000 (I think one1 + two1 should suffice). Then you try to fill the new array by looping through it two elements at a time:
for (int i = 0; i < combo.length - 1; i += 2) {
So i is 0, 2, 4 etc. through 19998 (the last even number before 20000). Except when it gets 10000, you try to pick out one[i], that is one[10000], which is outside the one array. This gives the ArrayIndexOutOfBoundsException.
How I found out? The stack trace gives a line number. The line it mentions is
combo[i] = one[i];
It also mentioned the number 10000, so I knew this was the value of i at this point.
I think that what you were trying to do, was fill elements 0 from one and two into elements 0 and 1 of combo, I think it works so far. Then you wanted to fill element 1 from each array into elements 2 and 3; but since you have added 2 to i, you fill in element 2 from each source array and never use element 1 from them. Or any element from odd indices.
Before you mend that problem, allow me to mention one more thing. I think with your logic, input arrays 2 5 and 11 30 will come out as 2 11 5 30. This doesn’t fulfil “with all elements in order, lowest to highest”. So I think you should think your algorithm over.
the code exist many logic error,
as for Runtime Error Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10000 at..
the problem is here:
for (int i = 0 ; i < combo.length-1 ; i+=2){
combo[i]=one[i];
combo[i+1]=two[i];
}
the i from 0 to 19999 and the index of a,b is from 0 to 9999, and the code exist other simple logic problem. Please check it again.
Homework questions are very frowned upon, but still, Java is a relatively easy language. If your program is throwing a RuntimeException, you just have to read what the problem is.
In this case, it seems a loop iterates more times than it should, and you are accessing other memory space. Give it a few reads with the info provided by the error trace in mind.
I've been working at an assignment for my intro to Java class, and I can't figure out how to accomplish the two things I need to do.
What I have now: I have created an array that rolls five dice, and displays the results. The code I have is as follows...
package operation.pkg7;
import java.util.Random;
import java.util.Scanner;
public class Operation7 {
public static void main(String[] args)
{
int[] dice = new int[5];
Random r = new Random();
//This makes the dice
for (int i = 0; i < 5; i++) {
dice[i] = r.nextInt(6) + 1;
}
//This displays the dice rolls
for (int i = 0; i < 5; i++) {
System.out.print("Roll " + (i+1) + ":" );
System.out.print(" " + dice[i] + " ");
}
System.out.println();
//..........................................
int[] counts = new int[6];
for (int i = 0; i < 6; i++){
counts[i] = 0;
}
//count up the values
for (int i = 0; i < 5; i++) {
int diceIndex = dice[i] - 1;
counts[diceIndex]++;
}
System.out.println();
for (int i = 0; i < 6; i++){
System.out.println("The number of " + (i+1) + "s is : " +
counts[i]);
}
}
}
Now, I successfully gives me the results of the die rolls, but I'm having problems figuring out how to do re-rolls. This is an example of what I'm wanting the program to ask for after displaying the initial die roll...
Roll 1: 2 Roll 2: 6 Roll 3: 1 Roll 4: 4 Roll 5: 2
Would you like to re-roll any dice? y/n
y
Which dice would you like to re-roll? 1-5
2, 3, 4
Roll 1: 2 Roll 2: 3 Roll 3: 2 Roll 4: 3 Roll 5: 2
Would you like to re-roll any dice? y/n
n
Roll 1: 2 Roll 2: 3 Roll 3: 2 Roll 4: 3 Roll 5: 2
That's the goal. Once I do that, I need to make the program display the best possible score... For example, if there are two threes and three twos, it needs to say it's a full house, or display yahtzee if there are five of the same number etc.
Anyone have any advice?
Put your code in a do-while loop with the condition of the user's input placed before the do-while loops condition check.
You have the results of your rolls store in the dice array you simply need to create new random results for the dice in those positions. E.g. if you re-roll #2 then put a new random in index 1.
As for determining the various types of rolls such as full house you will want to define generic logic for each. You might for example define a method like:
public static boolean isFullHouse(int[] diceRoll){
//return true if the roll is a full house, false otherwise
}
However, I think what you really want is not just to determine if a roll is a full house but to also calculate the total score using the scoring rules for that scenario.
EDIT #1:
Before going any further please, at a minimum, read the section on this page titled "Asking about homework".
I will try to illustrate how I think you could accomplish a re-roll without providing full code at this point. As I stated above, since you need to prompt the user for which dice they intend to re-roll you can process that input and use it as indicies into your dice array. So if the users 2,3,4 as in your example you use Scanner.getLine() to read that input and then use String methods to break it apart. Once you have the individual pieces you can convert them to int values using the Integer class. Finally, subtract 1 from them to adjust for the fact that your dice array indicies begin at 0.
Now you have an array containing indicies into your dice array. Each item in this new array is just used to refer to an index of the dice array. So let's call this second array userInput. Continuing the 2,3,4 example userInput[0]=1, userInput[1]=2, userInput[2]=3.
All you need to do is loop through userInput and each time through the loop generate a new random number. This random number is then stored in the dice array at the index stored in the current position of your userInput array.
As for determining the best possible score you could, as I suggested, write individual methods for each to determine if they are present and then another method to invoke each of them and report the greatest score possible.
Let's take one of them as an example like 3 of a Kind. Perhaps the simplest way to think about it would be to loop through all the possible rolls of the die (0 to 6) so that each time through the loop you're counting how many of each roll appear in the current dice roll. So in loop 1 you're looking for three 1's and in loop 2 you're looking for three 2's and so on.
Inside of this loop you create another loop to iterate through all of the dice in the current dice roll (your dice array) and each time through the loop you check to see if the current die is the number you're currently looking for from your outer loop. If it is the number from the outer loop then you increment a counter (which is defined and initialized in the outer loop but outside the inner loop so that it resets each time the outer loop increments) to represent how many of that number you have found so far.
If the counter reaches 3 before the inner loop ends you know you have 3 of a Kind, so have the method return true since you have no reason to continue (can't possibly have 2 different 3 of a Kind). Otherwise your method should return false to indicate there was no match.
Note that if you want to be ambitious you could exercise good programming practice and reuse code by making the limit of your counter a parameter to your method so that you can use the same logic for both 3 of a Kind and 4 of a Kind.
Hint there is a more clever way of doing this but I thought this approach would be more consistent with the constructs you already know.
I hope this helps to get you started!
Suppose I wanted to generate random numbers taken from ArrayList:(1,2,3,4,5,6,7,8,9,10)
A Random Generator produces 5.
List gets updated- AL:(1,2,3,4,6,7,8,9,10)
Next Random Number cannot be 5.
I am writing a program that generates random numbers from a arraylist and once it generates the random number the list removes that number and the next random generated digit cannot be that number.
ArrayList<Integer> numsLeft = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5,6,7,8,9,10));
Random randomGenerator = new Random();
int number = 0;
String cont;
do
{
number = randomGenerator.nextInt(numsLeft.size());
numsLeft.remove(number);
System.out.println (number + " continue (y/n)");
cont = (stdin.readLine());
}
while (cont.equalsIgnoreCase("y"));
But the only thing I can do here is lower the size...
http://docs.oracle.com/javase/7/docs/api/java/util/Random.html
The easier approach is to simply shuffle your list then use the numbers in the shuffled order:
List<Integer> nums = new ArrayList<Integer>();
for (int i = 1; i < 11; i++)
nums.add(i);
Collections.shuffle(nums);
Now they are in random order, just use them one by one:
for (Integer i : nums) {
// use i
}
You could make an array of the available numbers. Then, the random number generator gives you the position in that array for the number that you want.
Probably a linked list or something would be more efficient, but the concept is the same.
So, with your example, you'd pull 5 the first time. The second time, you'd have this in your list:
1, 2, 3, 4, 6, 7, 8, 9
If your random number was 5 again, the fifth position is 6. Pop the six out, shift 7, 8, 9 over one, and decrement your random number generator to be 1-8 instead of 1-9. continue on.
of course, looking at your code, it looks like that is what you are trying to do already.
What seems to be the issue with your code? What results are you getting?
number = randomGenerator.nextInt(numsLeft.size());
numsLeft.remove(number);
You are now printing the random index that you are generating, not the number that was removed from the list. Is that what you wanted? I think you really meant this:
int index = randomGenerator.nextInt(numsLeft.size());
number = numsLeft.remove(index);
You could also do this using by randomly shuffling the list and then just going through it:
List<Integer> numsLeft = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5,6,7,8,9,10));
// Shuffle the list randomly
Collections.shuffle(numsLeft);
do {
// Remove the first number each time
int number = numsLeft.remove(0);
System.out.println (number + " continue (y/n)");
cont = (stdin.readLine());
} while (cont.equalsIgnoreCase("y"));
Why don't you create a hash map to take care of this. So your hash map can contain something like
Map[(1,1), (2,2), (3,3), ...] or Map[(1,true), (2,true), (3,true), ...]
So if you generate a number, then you can do something like:
String value = map.get(key); or boolean present = map.get(key);
if(value != null) or if(value == present)
map.remove(key), or you can even update the data and instead of removing the key you can update it and add the word removed or a boolean as previously suggested. But this way you can keep track of all the entries and removals in your map for each of the key values which would be your list of numbers.
remove can be pretty expensive operation when list is long. Shuffle is too - especially if you only need a few numbers. Here is another algorithm (it is famous but I can't find the source right now).
put your N (ordered) numbers in a list
Choose a random number m between 0 and N-1
Pick the element at location m. This is your unique random number
SWAP element m with the LAST element in the array
Decrement N by 1
Go to step 2
You "set aside" the numbers you have used in step 4 - but
Unlike shuffle, your initialization is fast
Unlike remove, your remove operation only takes moving one element (instead of, on average, N/2)
Unlike the "pick one and reject if you saw it before", your efficiency of picking a "new" number doesn't decrease as the number of elements picked increases.
Homework. Dice Game. I've got an array that represents five rolls of a die. Consider:
diceRoll[] = {6,3,3,4,5}. I would LIKE to create a SECOND array that has the counts of values from one to six contained in diceRoll[], (e.g., occurence[] = {0,0,2,1,1,1} for the diceRoll[] above.) but I fear I'm getting lost in nested loops and can't seem to figure out which value I ~should~ be returning. occurence[] is a global variable, and the intent is that the array will contain six values...the count of ones (at index [0]), twos (at [1]), threes (at [2]), etc.
So Far:
for(i=1;i<7;i++) /* die values 1 - 6
{
for(j=0;j<diceRoll.length;j++) /* number of dice
{
if (diceRoll[j] == i) /* increment occurences when die[j] equals 1, then 2, etc.
occurence = occurence + 1;
}
}
return occurence;
}
I cannot, however, get the occurence=occurence+1 to work. bad operand types for binary operator is my most common error. I suspect I need to increment occurence OUTSIDE one or both of the for loops, but I'm lost.
Guidance? or perhaps the one-line easy way to do this?
d
The easiest way I have to do this is to create the second array in order so that
occurrence[0] = # of 1's occurrence[1] = # of 2's and so on. Then this becomes a 1 loop method.
//method to return number of occurrences of the numbers in diceRolls
int[] countOccurrences(int[] diceRolls) {
int occurrence[] = new int[6]; //to hold the counts
for(int i = 0; i < diceRolls.length; i++) { //Loop over the dice rolls array
int value = diceRolls[i]; //Get the value of the next roll
occurence[value]++; //Increment the value in the count array this is equivalent to occurrence[value] = occurrence[value] + 1;
//occurrence[diceRolls[i]]++; I broke this into two lines for explanation purposes
}
return occurrence; //return the counts
}
EDIT:
Then to get the count for any particular value use occurrence[value-1]