only last value of array is compared [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int randnum = 0;
boolean lose = false;
Random gen = new Random();
Scanner scan = new Scanner(System.in);
System.out.println("Enter desired numbers to be drawn");
int print = scan.nextInt();
System.out.println("Enter desired numbers on dice");
int dice = scan.nextInt();
System.out.println("Enter your lucky numbers");
int[] numbers = new int[print]; // int and print rhyme
for(int i=0; i<print;i++){
numbers[i] = scan.nextInt();
}
for(int counter=1; counter<=print;counter++){
randnum = 1+gen.nextInt(dice);
System.out.println(randnum + " ");
System.out.println();
if (randnum == numbers[counter - 1]){
lose = false;
} else {
lose = true;
}
if (lose == true){
System.out.println("Bad luck!");
}
if (lose == false){
System.out.println("Winner winner chicken dinner!");
}
}
}
}
I am making a simple lotto game. If I correctly guess the numbers I will still get the losing outcome unless it was the last number I guessed. How do I compare randnum to all numbers that were inputted?

If you only want one randnum, take the definition for randnum out of the for loop. You can break out of your loop as soon as you find a match.
randnum = 1 + gen.nextInt(dice);
System.out.println(randnum + " ");
System.out.println();
for(int counter=1; counter <= print; counter++){
if (randnum == numbers[counter - 1]){
lose = false;
break;
} else {
lose = true;
}
}
If you want multiple randnums, you need two loops.
for(int counter = 1; counter <= print; counter++){
randnum = 1 + gen.nextInt(dice);
System.out.println(randnum + " ");
System.out.println();
for(int i = 1; i <= print; i++){
if (lose == false){
break;
}
if (randnum == numbers[i - 1]){
lose = false;
break;
} else {
lose = true;
}
}
}
Make sure to initialize lose as true;
boolean lose = true;
You need to take the rest of the if statements out of the for loop.
if (lose == true){
System.out.println("Bad luck!");
}
if (lose == false){
System.out.println("Winner winner chicken dinner!");
}

Related

Resetting a game to start over in java

I created a dice game between the user and computer that loops 10 rounds - but if one of the game rounds is a tie - then it will ask if you want to play again and restart the game. I'm having a problem with the last part as the game iterates over at random times now. Any suggestions?
import java.util.Random;
import java.util.Scanner;
public class Lab2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("User vs. Computer Dice Game");
boolean Correct = false;
boolean Replay = false;
while(Replay == true) {
}
while(Correct == false) {
System.out.println("Do you want to play again? ");
String a = in.nextLine();
System.out.print(a);
if (a.equals("yes")) {
for(int i =1; i<11; i++) {
Random rand = new Random();
int usernum = rand.nextInt(6)+1;
System.out.println("User rolled: "+usernum);
Random rand2 = new Random();
int computernum = rand2.nextInt(6)+1;
System.out.println("Computer rolled: "+computernum);
if (usernum > computernum) {
System.out.println("User wins");
System.out.println();
}if (computernum > usernum) {
System.out.println("Computer wins");
System.out.println();
}
if(usernum == computernum) {
System.out.println("It\'s a tie!");
System.out.println("Do you want to play again? (Y/N) ");
System.out.println();
if (a.equalsIgnoreCase("N")){
Replay = true;
}
else {
Correct = false;
}
}
}
}
System.out.println();
}
}
}
Some notes:
You never set Correct=true.
Once inside the "while (Correct==false)" loop, you never test Replay.
There is no point in creating rand2. Just reuse rand1.
You have "for (int i=1;i<11;i++)" for the main loop.
Inside of that loop, and it's a tie, you ask if you want to play again, but there is nothing there to end the loop, so the inner for loop will continue to play out until you hit 11.
You might add a break statement when it's a tie to abort the for loop.
In fact, you're probably better off just aborting the loop and then asking the question again at the top of the while loop:
while(Correct == false) {
System.out.println("Do you want to play again? ");
String a = in.nextLine();
System.out.print(a);
if (a.equals("yes")) {
for (int i = 1; i < 11; i++) {
Random rand = new Random();
int usernum = rand.nextInt(6) + 1;
System.out.println("User rolled: " + usernum);
Random rand2 = new Random();
int computernum = rand2.nextInt(6) + 1;
System.out.println("Computer rolled: " + computernum);
if (usernum > computernum) {
System.out.println("User wins");
System.out.println();
}
if (computernum > usernum) {
System.out.println("Computer wins");
System.out.println();
}
if (usernum == computernum) {
System.out.println("It's a tie!");
// Exit early from the for loop:
break;
}
}
}
else
{
Correct = true;
}
}

write a program that repeatedly prompts a user to supply score(out of 100) java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
write a program that repeatedly prompts a user to supply score(out of 100) on a test for 5 students once the program has real all score it should produce a table with the following headings (and automatically fill in the rest of the table) for example
Student No # Score(out of 100)
1 55
2 66
The program should them calculate the total score
Here is my code
import java.io.*;
import java.util.*;
public class test33 {
public static void main(String[]args){
Scanner kbReader = new Scanner (System.in);
int scores[] = new int [100];
int counter = 0;
int sum = 0;
int input = 0;
do {
System.out.println("Enter score out of 100 or negative to break.");
input = kbReader.nextInt();
if (input < 0) {
break;
} else if (input > 100) {
System.out.println("Score must be out of 100");
} else {
scores[input]++;
counter++;
sum += input;
}
} while (input > 0);
System.out.println("Score\t# of occur...");
for (int i = 0; i < 100; i++) {
System.out.println(i + "\t" + scores[i]);
}
System.out.println("The mean score is " +(sum/counter));
}
}
scores[input]++; if you want to assign value to your array scores[] you must corrected like i did below.
public static void main(String[]args) {
Scanner kbReader= new Scanner (System.in);
int scores[] = new int [100];
int counter = 0;
int sum = 0;
int input = 0;
do {
System.out.println("Enter score out of 100 or negative to quit.");
input=kbReader.nextInt();
if(input<0) {
break;
}
else if (input>100) {
System.out.println("Score must be out of 100");
} else {
scores[counter]=input;
counter++;
sum+=input;
}
} while (input>0);
if(counter != 0){
System.out.println("Score\t# of occur...");
for(int i =0; i<100; i++) {
System.out.println(i + "\t" + scores[i]);
};
System.out.println("The mean score is " +(sum/counter));
}
}

Trying to count number of occurrences in an array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
So I'm trying to count the number of integer occurrences in this program. The code still doesn't work, but am I on the right track?
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int userInput = 0;
ArrayList<Integer> myList = new ArrayList<Integer>();
int[] newArray = new int[myList.size()];
int index1 = -1;
int current;
for (int num = 0; num <= userInput ; num++)
{
System.out.println("Please enter a random number between 0 and 50, enter a negative number to end input: ");
num--;
if(userInput >= 0 || userInput <= 50)
{
userInput++;
userInput = scan.nextInt();
index1++;
myList.add(userInput);
}
if (userInput < 0 || userInput > 50)
{
myList.remove(index1);
index1--;
break;
}
}
for (int num2 = 0; num2 < myList.size(); num2++)
{
current = myList.get(num2);
if(current == myList.get(num2))
{
newArray[current-myList.get(num2)]++;
}
}
for (int number=0; number < newArray.length; number++)
{
System.out.println(number + "1");
System.out.println(" : " + newArray[number]);
}
}
}
edit:
just wanted to add that I can run the program, but when I input an integer that is out of bounds (not between 0 and 50), I get an error
I just finished writing this, thanks for the downvotes while I was modifying my code and specifically stated I was modifying the code. Hashmaps will do the trick for you here.
public static void main(String args[]) {
HashMap<Integer, Integer> numbers = new HashMap<Integer, Integer>();
Scanner scan = new Scanner(System.in);
boolean loop = true;
while (loop) {
System.out.println("Number: ");
int current = scan.nextInt();
if (current > 0 && current < 51) {
if (numbers.containsKey(current)) {
numbers.put(current, numbers.get(current)+1);
}else{
numbers.put(current, 1);
}
} else {
if(numbers.isEmpty()){
System.out.println("Nothing inputted");
loop = false;
}else{
for(Entry<Integer,Integer> e : numbers.entrySet()){
System.out.println(e.getKey() + " was entered " + e.getValue() + " times");
}
loop = false;
}
}
}
}
You do not need any additional collection like myList.
You can declare array
int[] occurrences = new int[51];
which can store occurence of elements from range [0,50]. When You read n as nextInt from scanner You should increment element of this array at readed n-th position if n is in range or stop reading new values otherwise.
This if statemest is always true:
current = myList.get(num2);
if(current == myList.get(num2))
Code example:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] occurrrences = new int[51];
while (true){
int value = scanner.nextInt();
if(value>=0 && value<occurrrences.length){
occurrrences[value]++;
}else{
scanner.close();
break;
}
}
for (int i = 0; i < occurrrences.length; i++) {
if(occurrrences[i]>0){
System.out.println(i + " occured " + occurrrences[i] + " times.");
}
}
}

boolean is assigned but never accessed [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I'm just trying to create a GuessMyNumber game and here is my code:
import java.util.Random;
import java.util.Scanner;
public class classic {
public static void main(String[] args) {
Random rand = new Random();
boolean beaten = false;
int number;
int randn = rand.nextInt(99);
//System.out.println(randn);
System.out.println("What is my number? Guess it!");
Scanner input = new Scanner(System.in);
int counter = 0;
int counter2 = 0;
while(beaten = true){
number = input.nextInt();
if (number == randn) {
System.out.println("Correct!");
beaten = true;
}
if (number < randn) {
System.out.println(number + " is too low");
}
if (number > randn) {
System.out.println(number + " is too high");
}
}
}
}
In the while loop I set beaten = true but still, while loop continues
What am I doing wrong here?
while(beaten = true)
As = is an assignment operator, so true is assigned into beaten first, then while loop condition becomes,
beaten = true
while(true) {
//.... hence, loop executed.
}
Use comparison operator == for condition checking. Moreover, not ! operation can be used also for boolean variable.
Say,
beaten = true
Then
while(!beaten)
means
while(!true) // read while not true
//implies
while(false) {
//.... loop will not going to execute.
}
import java.util.Random;
import java.util.Scanner;
public class Guess {
public static void main(String[] args) {
Random rand = new Random();
boolean beaten = false;
int number;
int randn = rand.nextInt(99);
//System.out.println(randn);
System.out.println("What is my number? Guess it!");
Scanner input = new Scanner(System.in);
int counter = 0;
int counter2 = 0;
while(beaten == false ){
number = input.nextInt();
if (number == randn) {
System.out.println("Correct!");
beaten = true;
}
if (number < randn) {
System.out.println(number + " is too low");
counter++;
}
if (number > randn) {
System.out.println(number + " is too high");
counter++;
}
}
System.out.print("It took you " + counter + " tries to gues the number");
}
}
Now it works. You set "beaten" to false originally so it wasn't working and I also changed your while loop condition too "beaten == false" instead of "beaten = false" Hope this helps. I didn't know what you wanted to do with the counter so I just added that into the bottom to count how many tries it took.

int variable remains at 0, while loop not running properly as a result

What I really am stuck with is the second to last variable userGuessDifference. It remains at zero making my second while loop not run properly as it just keeps going back to the first else if statement.
public class GuessingGame {
/**
* #param args
*/
public static void main(String[] args)
{
Scanner keyboard = new Scanner (System.in);
Random generator = new Random();
int difficulty = 0;
int guesses = 0;
int userGuess = 0;
int correctAnswer = 0;
int counter = 0;
int userGuessDifference = (Math.abs(correctAnswer) - Math.abs(userGuess));
boolean flag = false;
System.out.println("We are going to play a number guessing game.");
System.out.println(" ");
System.out.println("Choose your difficulty:");
System.out.println("Pick a number - 10 is easy, 25 is medium, 50 is hard.");
difficulty = keyboard.nextInt();
if (difficulty == 10)
{
guesses = 3;
System.out.println("You have 3 guesses, make them count!");
}
else if (difficulty == 25)
{
guesses = 5;
System.out.println("You have 5 guesses, make them count!");
}
else if (difficulty == 50)
{
guesses = 6;
System.out.println("You have 6 guesses, make them count!");
}
else
{
System.out.println("If you can't follow instructions, I'm going to make this very difficult for you!");
difficulty = (difficulty * 100);
guesses = 1;
}
System.out.println(" ");
System.out.println("Ok, I have my number. Time to play.");
correctAnswer = generator.nextInt(difficulty) + 1;
System.out.println("Pick a whole number between 1 and " + difficulty + ":");
userGuess = keyboard.nextInt();
while (!flag || (counter <= guesses))
{
if (userGuess == correctAnswer)
{
System.out.println("CONGRATS YOU WIN!");
flag = true;
}
else if ((userGuessDifference <= (difficulty * .10)))
{
System.out.println("HOT!");
userGuess = keyboard.nextInt();
counter++;
}
else if ((userGuessDifference < (difficulty * .25)) && (userGuessDifference > (difficulty * .10)))
{
System.out.println("Warm...");
userGuess = keyboard.nextInt();
counter++;
}
else
{
System.out.println("Ice cold.");
userGuess = keyboard.nextInt();
counter++;
}
}
}
}
As #SotiriosDelimanolis wrote, you never reassign userGuessDifference. This should be done inside the while loop.
Moreover, there is another problem with your code: if you guess the number, the program just prints "CONGRATS YOU WIN!" forever, but it seems to me that you wanted to quit from the while loop once the user guesses the number (I guess the flag variable was introduced for this reason).
I slightly changed your code in order to meet this requirement:
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Random generator = new Random();
int difficulty = 0;
int guesses = 0;
int userGuess = 0;
int correctAnswer = 0;
int counter = 0;
System.out.println("We are going to play a number guessing game.");
System.out.println(" ");
System.out.println("Choose your difficulty:");
System.out.println("Pick a number - 10 is easy, 25 is medium, 50 is hard.");
difficulty = keyboard.nextInt();
if (difficulty == 10) {
guesses = 3;
System.out.println("You have 3 guesses, make them count!");
} else if (difficulty == 25) {
guesses = 5;
System.out.println("You have 5 guesses, make them count!");
} else if (difficulty == 50) {
guesses = 6;
System.out.println("You have 6 guesses, make them count!");
} else {
System.out.println("If you can't follow instructions, I'm going to make this very difficult for you!");
difficulty = (difficulty * 100);
guesses = 1;
}
System.out.println(" ");
System.out.println("Ok, I have my number. Time to play.");
correctAnswer = generator.nextInt(difficulty) + 1;
System.out.println("Pick a whole number between 1 and " + difficulty + ":");
userGuess = keyboard.nextInt();
while (counter <= guesses) {
// int userGuessDifference = (Math.abs(correctAnswer) - Math
// .abs(userGuess));
int userGuessDifference = Math.abs(correctAnswer - userGuess);
if (userGuess == correctAnswer) {
System.out.println("CONGRATS YOU WIN!");
break;
}
else if ((userGuessDifference <= (difficulty * .10))) {
System.out.println("HOT!");
}
else if ((userGuessDifference < (difficulty * .25))
&& (userGuessDifference > (difficulty * .10))) {
System.out.println("Warm...");
}
else {
System.out.println("Ice cold.");
}
userGuess = keyboard.nextInt();
counter++;
}
}
}

Categories