Guessing the number that the user has thought with java (arrays) - java

I'm kind of new at programming and our teacher asked us to make a programme that can guess the number the user has thought using arrays. I did this:
import java.util.Scanner;
public class Exercise11 {
public static void main(String[] args) {
Scanner entrada = new Scanner(System.in);
System.out.println("Think a number between 1 and 100");
int array[] = new int[100];
for (int x = 0; x < 100; x++) {
array[x] = (int) ((Math.random() * 100) + 1);
}
//This allow us to fill the array with random numbers, without caring if they are repeated or not.
for (int i = 0; i < 100; i++) {
for (int j = 0; i < 100; j++) {
while (true) {
if (i != j && array[i] == array[j]) {
array[j] = (int) ((Math.random() * 100) + 1);
} else
break;
}
//If a number is repeated, this will swap that number with another number.
}
}
//Now we have filled the array. We ask the user:
for (int y = 0; y < 100; y++) {
System.out.println("¿Is it your number " + array[y] + "?");
String respuesta = entrada.next();
switch (respuesta) {
case "Yes":
System.out.println("I knew it! I only needed " + y + " trys!");
break;
case "No":
break;
}
}
}
}
But it is still throwing errors when I execute it, like this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100
at Ejercicio11.main(Ejercicio11.java:25).
I have tried to debug it but I'm still learning how to do it and I cannot find the mistake. Can someone help me identify where the error is and how can I fix it? Thanks a lot!

The condition of your inner for loop should be
for (int j = 0; j < 100; j++){
(The condition is j < 100, not i < 100)

Related

How to resolve hashing collisions in Java

Write the following program using Java:
Suppose Player1 has 7 dice and Player2 has 5 dice (all 12 dice are standard 1 through 6 dice and fair). Both players roll their dice and compare their individual sum totals (i.e. Player1 rolls 1,3,5,2,6,1,1 = 19 and Player2 rolls 2,1,4,6,3 = 16). If Player1 rolls a total sum higher than Player2, Player1 wins the match, otherwise, Player2 wins. If all 2,176,782,336 combinations are rolled, how many matches will Player1 win? How many matches will Player2 win? How many matches will result in a tie? (note: only totals answering the three questions need to be printed)
The part where I'm stuck is how can I guarantee that I have no duplicate rolls?
Thanks.
import java.util.Random;
public class KDice {
public static void main(String[] args) {
Random random = new Random();
long playerOneWins = 0, playerTwoWins = 0, ties = 0;
int playerOneSum, playerTwoSum;
//for long number use L as suffix
for (long i = 0; i < 2176782336L; i++) {
//roll dice for player 1
playerOneSum = rollDice(random, 7);
//roll dice for player 2
playerTwoSum = rollDice(random, 5);
//find who won
if (playerOneSum == playerTwoSum) {
ties++;
} else if (playerOneSum > playerTwoSum) {
playerOneWins++;
} else {
playerTwoWins++;
}
}
//after all the round done, display stats
System.out.println("Player 1 win: " + playerOneWins);
System.out.println("Player 2 win: " + playerTwoWins);
System.out.println("Ties: " + ties);
}
public static int rollDice(Random random, int count) {
int sum = 0;
for (int i = 0; i < count; i++) {
sum += generateRandomNumber(random);
}
return sum;
}
public static int generateRandomNumber(Random random) {
return random.nextInt(6) + 1; //return number between 1 to 6
}
}
To simulate each possible roll of 12 dice, I use 12 nested for-loops so that I can produce each possible roll.
I replaced your random rolls of the dice with this loop:
int[] dice = new int[12];
for (dice[0] = 1; dice[0] <= 6; dice[0]++) {
System.out.println("dice[0] = " + dice[0]);
for (dice[1] = 1; dice[1] <= 6; dice[1]++) {
System.out.println("dice[1] = " + dice[1]);
for (dice[2] = 1; dice[2] <= 6; dice[2]++) {
System.out.println("dice[2] = " + dice[2]);
for (dice[3] = 1; dice[3] <= 6; dice[3]++) {
for (dice[4] = 1; dice[4] <= 6; dice[4]++) {
for (dice[5] = 1; dice[5] <= 6; dice[5]++) {
for (dice[6] = 1; dice[6] <= 6; dice[6]++) {
for (dice[7] = 1; dice[7] <= 6; dice[7]++) {
for (dice[8] = 1; dice[8] <= 6; dice[8]++) {
for (dice[9] = 1; dice[9] <= 6; dice[9]++) {
for (dice[10] = 1; dice[10] <= 6; dice[10]++) {
for (dice[11] = 1; dice[11] <= 6; dice[11]++) {
playerOneSum = dice[0] + dice[1] + dice[2] + dice[3] + dice[4] + dice[5] + dice[6];
playerTwoSum = dice[7] + dice[8] + dice[9] + dice[10] + dice[11];
//find who won
if (playerOneSum == playerTwoSum) {
ties++;
} else if (playerOneSum > playerTwoSum) {
playerOneWins++;
} else {
playerTwoWins++;
}
}
}
}
}
}
}
}
}
}
}
}
}
It took about three-four minutes to run through. I put in the println's to keep me from being too impatient. The results are:
Player 1 win: 1877280394
Player 2 win: 225654001
Ties: 73847941
If you are trying to go through every combination, you should not be rolling randomly. Just systematically go through every combination (e.g., with loops), and do your counting as you go along.
It seems to me that you misunderstood the question.
The question asks you to go through all possible outcomes and classify each outcome to either "A wins", "B wins" or "a tie".
For that, you don't use random. The answer should not change if you run the program many times. To enumerate all possible combinations of rolled dice, you can use 12 nested for loops that each count from 1 to 6. This way, the body of innermost loop will be executed 6^12 times - exactly once per any possible outcome. What you need to do is to sum 7 of the loop variables and compare it to sum of 5 other loop variables. Based on that, you either increase the counter for "A wins", "B wins" or "ties".
Alternatively, you don't need to count ties, since you always know the total number of results.
Here is a more compact and slightly more efficient way of achieving this. It works by:
starting with an array of 12 dice, initialized to all 1's (except the last for the first "toss")
then those dice are essentially incremented in a quasi base 7 to get the next toss. quasi because there are no 0's.
the sums are modified by either adding 1 or subtracting 5 depending on the the transition between between adjacent dice which would alter the sum by either +1 or -5.
int[] dice = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 };
int sum5 = 4; // inital sum for sum of five dice before first toss
int sum7 = 7; // initial sum for sum of seven dice before first toss
int sum7wins = 0;
int sum5wins = 0;
int ties = 0;
outer:
for(;;) {
for (int i = dice.length - 1; i >= 0;) {
int val = dice[i];
if (val < 6) {
dice[i] = val + 1;
if (i < 7) {
sum7++;
} else {
sum5++;
}
break;
}
if (i == 0) {
// first die is a 6 so we're done.
break outer;
}
dice[i] = 1;
if(i < 7) {
sum7-=5;
} else {
sum5-=5;
}
i--;
}
if (sum5 > sum7) {
sum5wins++;
} else if (sum7 > sum5) {
sum7wins++;
} else {
ties++;
}
}
System.out.println("sum7wins: " + sum7wins);
System.out.println("sum5wins: " + sum5wins);
System.out.println("ties: " + ties);
Prints
sum7wins: 1877205968
sum5wins: 225571216
ties: 74005152
2,176,782,336 is the number of possibilities of combination that can happens (= 6^12).
As i see you are trying roll 2,176,782,336 times randomly - which i think cannot resolve your question.
Edit, using 12 nested for loop might resolve your question:
public static void main(String args[]) {
int numP1Win = 0;
int numP2Win = 0;
int numdraw = 0;
for (int i = 1; i <= 6; i++) {
for (int j = 1; j <= 6; j++) {
for (int k = 1; k <= 6; k++) {
for (int l = 1; l <= 6; l++) {
for (int m = 1; m <= 6; m++) {
for (int n = 1; n <= 6; n++) {
for (int o = 1; o <= 6; o++) {
for (int p = 1; p <= 6; p++) {
for (int q = 1; q <= 6; q++) {
for (int r = 1; r <= 6; r++) {
for (int s = 1; s <= 6; s++) {
for (int t = 1; t <= 6; t++) {
if (i + j + k + l + m + n + o > p + q + r + s + t) {
numP1Win++;
}
else if (i + j + k + l + m + n + o < p + q + r + s + t) {
numP2Win++;
}
else {
numdraw++;
}
}
}
}
}
}
}
}
}
}
}
}
}
System.out.println("Num P1 Win: " + numP1Win);
System.out.println("Num P2 Win: " + numP2Win);
System.out.println("Num Draw: " + numdraw);
}
Output:
Num P1 Win: 1877205968
Num P2 Win: 225571216
Num Draw: 74005152

Java program takes input but does not output

When I try to run the program it asks me for my input and then just says "running" without any output until I close it. I do not see any issues with the code, and I have run this exact program before on a different computer (my home computer is far superior in processing power to the PC it ran on) is this a Netbeans bug?
int ticket [] = new int [6];
for (int i = 0; i < 6; i++)
{
ticket [i] = Integer.parseInt(JOptionPane.showInputDialog("Input a number:"));
}
int balls[] = new int [7];
for (int i = 0; i < balls.length; i++)
{
boolean keepLooking = true;
int b = (int)(Math.random()*6 + 1);
while(keepLooking)
{
keepLooking = false;
for (int j = 0; j < balls.length; j++)
{
if (balls [j] == b)
{
keepLooking = true;
}
}
}
balls [i] = b;
}
int bonus = balls[6];
int matching = 0;
boolean bonusMatch = false;
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 7; j++)
{
if (ticket[i] == balls[j])
{
matching = matching +1;
}
}
if (ticket[i] == balls[6])
{
bonusMatch = true;
}
}
System.out.println("The winning balls are: ");
for (int i = 0; i < 6; i++)
{
System.out.print(" " +balls[i]);
}
System.out.println(" And the bonus ball is " +balls[6]);
int Payout = 0;
if (matching == 3)
{
System.out.println("Your payout was: R57");
}
else if (matching == 4)
{
System.out.println("Your payout was: R1033");
}
else if (matching == 5)
{
if (bonusMatch = true)
{
System.out.println("Your payout was: R2300000");
}
else
{
System.out.println("Your payout was: R55491");
}
}
else if (matching == 6)
{
System.out.println("Your payout was: R14000000");
}
}
int b = (int)(Math.random()*6 + 1);
if b is twice the same (it's random, it can happen and will happen), you have an infinite loop (keepLooking = true since you found b in your table, and you iterate without changing anything).
whatever you are trying to achieve (honestly your code made no sense, create methods with meaningful names, avoid intricate loops, brief refactor), bug's on you, not Netbeans.
please use "if" loop instead of "while" loop you will get a output like what u want!!i.e.,
while(keepLooking) instead use if(keepLooking)

Multiarray inputs

I am unable to create a loop to add hours to a multi-array. When I use the method Hours there is an error. I suspect my for-loop is not capturing the input.
import javax.swing.JOptionPane;
public class Gain
{
// Defining array names.
String[] name = {"A", “B”, “C”, “D”, “E”, “F”, “G”, “H”, “I”, “L”};
int[][] hours = new int[10][3];
public final int Hours()
{
boolean canceled = false;
for (int index = 0; index < name.length; index++) {
JOptionPane.shoeMessageDialog(“Please enter " + name[index] + “’s hours”);
for (int x = 0; x <= hours.length; x++)
for (int y = 0; y <= hours[x].length; y++)
Integer value = promptForInt(artist[index] + “’s first hour: ”);
if (value != null) {
while (value < 0)
{
JOptionPane.showMessageDialog(null, "Please positive figures." + "\nPlease try again.");
value = promptForInt(name[index] + “’s first hour: ”);
}
pay[x][y] = value;
} else {
canceled = true;
break;
}
}
public static void main(String[] args) // Main program
{
for (int x = 0; x <= name.length; x++)
for (int y = 0; y <= hours.length; y++)
System.out.println(x, y);
}
Try adding in brackets like so:
import javax.swing.JOptionPane;
public class Gain
{
// Defining array names.
String[] name = {"A", “B”, “C”, “D”, “E”, “F”, “G”, “H”, “I”, “L”};
int[][] hours = new int[10][3];
public final int Hours()
{
boolean canceled = false;
for (int index = 0; index < name.length; index++)
{
JOptionPane.shoeMessageDialog("Please enter " + name[index] + "’s hours");
for (int x = 0; x <= hours.length; x++)
{
for (int y = 0; y <= hours[x].length; y++)
{
Integer value = promptForInt(artist[index] + “’s first hour: ”);
if (value != null)
{
while (value < 0)
{
JOptionPane.showMessageDialog(null, "Please positive figures." + "\nPlease try again.");
value = promptForInt(name[index] + “’s first hour: ”);
}
pay[x][y] = value;
}
else
{
canceled = true;
break;
}
}
}
}
}
public static void main(String[] args) // Main program
{
for (int x = 0; x <= name.length; x++)
for (int y = 0; y <= hours.length; y++)
System.out.println(x, y);
}
While it's fine to avoid brackets in a for loop when you only have one line of code afterwards (like in your main method), you need to use them when you have a whole block, as is the case here in your Hours() method. Personally, I like to use brackets all of the time as it makes the code more readable, but that's just me. :)

Input loop number missing loop

Whenever I input x (number of empoyee) as any number it always short in 1 loop when asking the employee salary. And if i put x as 1 it doesn't ask me.
Need help how to fix it.
class salary {
public static void main(String[] args) {
int x = 0;
int y;
System.out.println("Enter how many employee");
x = EasyIn.getInt();
for (int i = 1; i < x; ++i) {
System.out.println("Enter the salary of employee " + i);
y = EasyIn.getInt();
if (y < 20000) {
System.out.println("This employee Bonus Rate is 7%");
}
}
}
}
You have an error in your for loop. It should be:
for(int i = 0; i < x; ++i)
or:
for(int i = 1; i <= x; ++i)
What is EasyIn?
There might also be an issue with your EasyIn class.
Your problem is here
for (int i = 1; i < x; ++i)
Think about the terminating condition of the for loop.
Try something like this -
// start at 0.
for (int i = 0; i < x; ++i)
{
// add one for display.
System.out.println("Enter the salary of employee " + (1+i));
y = EasyIn.getInt();
if(y < 20000)
{
System.out.println("This employee Bonus Rate is 7%");
}
}
you are starting i from 1 instead of zero so it will always short by 1.
Simply change int i=1; to int i=0;

Find the prime-->sieve way

I tried it several times but still gives me ArrayOutOfIndex. But i want to save the memory so i use
boolean[]isPrime = new boolean [N/2+1];
instead of
boolean[]isPrime = new boolean [N+1];
This gives me ArrayOutOfIndex for line 23 and 47
line 23:
for (int i = 3; i <= N; i=i+2) {
isPrime[i] = true;
}
line 47:
for (int i = 3; i <= N; i=i+2) {
if (isPrime[i]) primes++;
...
}
Full code:
public class PrimeSieve {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: java PrimeSieve N [-s(ilent)]");
System.exit(0);
}
int N = Integer.parseInt(args[0]);
// initially assume all odd integers are prime
boolean[]isPrime = new boolean [N/2+1];
isPrime[2] = true;
for (int i = 3; i <= N; i=i+2) {
isPrime[i] = true;
}
int tripCount = 0;
// mark non-primes <= N using Sieve of Eratosthenes
for (int i = 3; i * i <= N; i=i+2) {
// if i is prime, then mark multiples of i as nonprime
if (isPrime[i]) {
int j = i * i;
while (j <= N){
tripCount++;
isPrime[j] = false;
j = j + 2*i;
}
}
}
System.out.println("Number of times in the inner loop: " + tripCount);
// count and display primes
int primes = 0;
if(N >= 2 ){
primes = 1;
}
for (int i = 3; i <= N; i=i+2) {
if (isPrime[i]) primes++;
if (args.length == 2 && args[1].equals("-s"))
; // do nothing
else
System.out.print(i + " ");
}
System.out.println("The number of primes <= " + N + " is " + primes);
}
}
You should store and access the array using the same indexing function: isPrime[i/2]
When you change the size of your array from [N+1] to [N/2+1], you need to also update the end-conditions of your for-loops. Right now your for-loops run until i=N, so you are trying to do isPrime[i] when i > (N/2+1) ... so you get an ArrayIndexOutOfBoundsException.
Change this:
for (int i = 3; i <= N; i=i+2)
to this:
for (int i = 3; i <= N/2; i=i+2)
Well, for example if N=50 your isPrime only holds 26 elements, and you're trying to access the elements at 3,5..47,49 (which, of course, is out of bounds)
What you probably want is to use i/2 (as the index) inside your loops, that way you are still iterating over the numbers 3,5..47,49, but you use the correct indexes of your vector.

Categories

Resources