Finding positions of a number in an array and giving points, Java - java

I'm trying to write a program that generates and stores 20 random numbers in the array Data[] and asks the user to enter their guess. If their number appears in the array, they get 10 points for each occurrence, the array is printed and all positions where the lucky number can be found. If it doesn't appear in the array, I have to print the lowest and highest values of the array and allow only one more try. if the player gets it right the second time they get 1 point for each appearance.
For example: Data[]={3,1,8,31,25,6,3,20,41,12,3,23,7,3,65,49,5,0,13,17}
and if the user inputs 3 then the program would output
3 can be found on the following positions:
0 6 10 13
3 appears 4 times. You get 40 points!
and for the same Data[]={3,1,8,31,25,6,3,20,41,12,3,23,7,3,65,49,5,0,13,17} if the user inputs 2 then the program would output
Sorry your lucky number 2 is not in the array!
Hint: Lowest Value:1 Highest Value 65 Try again with a different number in this range.
if they input 65 on their second try then the program would output
You get 1 point(s)!
This is my code I have tried but it is not working. It keeps telling me my numbers are not in the array. The lowest and highest values work. I do not know how to fix it. I have to have this done by tomorrow. Any help would be greatly appreciated.
String input1 = JOptionPane.showInputDialog("Please enter your lucky number between 0 and 100.");
luck=Integer.parseInt(input1);
System.out.println("Input " +luck);
int Data[] = new int [20];
for( int i=0; i<Data.length;++i){
Data[i] = (int) (Math.random() * 100);
System.out.print(Data[i]+ " \t");
}
for( int i=0; i<Data.length;++i){
if(Data[i]==luck){
System.out.println(luck+ " can be found in the following positions: ");
System.out.println(i);
score=score+10;
System.out.println(luck+ " appears " +(luck/10)+ " times. You get " +score+ " points.");
}else if(Data[i]!=luck){
Arrays.sort(Data);
System.out.println();
System.out.println(luck+ " is not in the array.");
System.out.println("Hint: " +Data[0]+ " is the lowest value and " +Data[19]+ " is the highest.");
input1 = JOptionPane.showInputDialog("Please enter another number between 0 and 100.");
luck=Integer.parseInt(input1);
}
}
System.out.println();
System.out.println("Score: " +score);
}}

The problem is you are not checking your value against every value in your array. If the entered value does not match the first value in your Array (i=0), then you are asking the user for another value.
What you have to do is ask for a value, compare it against EVERY value in the table, then make your decision. Either it's present or its not.
I added a boolean. We set it to true if we find our number, otherwise we display the message and ask the user to try again.
Try this:
boolean found = false;
for( int i=0; i<Data.length;++i){
if(Data[i]==luck){
System.out.println(luck+ " can be found in the following positions: ");
System.out.println(i);
score=score+10;
System.out.println(luck+ " appears " +(luck/10)+ " times. You get " +score+ " points.");
found = true;
}
}
if(!found){
Arrays.sort(Data);
System.out.println();
System.out.println(luck+ " is not in the array.");
System.out.println("Hint: " +Data[0]+ " is the lowest value and " +Data[19]+ " is the highest.");
input1 = JOptionPane.showInputDialog("Please enter another number between 0 and 100.");
luck=Integer.parseInt(input1);
}
Finally, you need to implement a counter inside your loop, and then display your information as required... Right now, it will display "# can be found in the following positions" and other messages for each instance found in the array.
Implement a counter, and a way to track indexes of values found, and then you can display all that information coherently from outside the for loop
Edit: To give you more complete implementation...
This code should basically take you almost where you need to go:
public static void main(String[] args) {
int Data[] = new int [20];
for( int i=0; i<Data.length;++i){
Data[i] = (int) (Math.random() * 100);
System.out.print(Data[i]+ " \t");
}
while(true){
String input1 = JOptionPane.showInputDialog("Please enter your lucky number between 0 and 100.");
int luck=Integer.parseInt(input1);
int score = 0;
String positions = "";
int counter = 0;
System.out.println("Input " +luck);
boolean found = false;
for( int i=0; i<Data.length;++i){
if(Data[i]==luck){
positions += i + " ";
counter++;
score=score+10;
found = true;
}
}
if(found){
System.out.println(luck+ " can be found in the following positions: ");
System.out.println(positions);
System.out.println(luck+ " appears " + counter + " times. You get " +score+ " points.");
}
else{
Arrays.sort(Data);
System.out.println();
System.out.println(luck+ " is not in the array.");
System.out.println("Hint: " +Data[0]+ " is the lowest value and " +Data[19]+ " is the highest.");
}
System.out.println();
System.out.println("Score: " +score);
}
}

Related

why is my program displaying the array wrong?

I am having a problem with my program. When I compile and run my program everything runs great until it's time to display the guesses back to the user. when that happens the last guess always gets displayed as 0.
My assignment is to develop a program that simulates the high-low game. For each execution of the program, the game will generate a random number in the inclusive range of 1 to 100. The user will have up to 10 chances to guess the value. The program will keep track of all the user’s guesses in an array. For each guess, the program will tell the user if his/her guess was too high or too low. If the user is successful, the program will stop asking for guesses, display the list of guesses, and show a congratulatory message stating how many guesses he/she took. If the user does not guess the correct answer within 10 tries, the program will display the list of guesses and show him/her the correct value with a message stating that he/she was not successful. Regardless of the outcome, the program will give the user a chance to run the program again with a new random number.
This is what I have so far:
import java.util.Random;
import java.util.Scanner;
/**
*
* #author jose
*/
public class Assignment7
{
/*
*/
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int number;
String again = "y";
while (again.equalsIgnoreCase("y"))
{
int[] guesses = new int[10];
int tries = 0;
number = GetRandomNumber(1, 100);
System.out.println(number); // delete before submitting
int userGuess = GetUserGuess(1,100);
while (userGuess != number && tries < guesses.length - 1 )
{
guesses[tries] = userGuess;
LowOrHigh(number, userGuess);
userGuess = GetUserGuess(1, 100);
tries++;
}
if (tries != 10)
{
userGuess = guesses[tries];
tries++;
System.out.println("Congratulations! You were able to guess the correct number");
}
else
{
System.out.println("Sorry! You were not able to guess the correct number");
}
if (tries == 10)
{
System.out.println("Your guesses were incorrect");
System.out.print("You guessed: ");
for ( int i = 0; i < 10 ; i++)
{
System.out.print(guesses[i] + ", ");
}
System.out.println("The random number generated was " + number);
}
else
{
System.out.println("Well done! You were able to guess the "
+ "correct number in under 10 tries");
System.out.print("You guessed: ");
for ( int i = 0; i < tries; i++)
{
System.out.print(guesses[i] + " ");
}
System.out.println("The random number generated was "
+ number + ", it only took you " + tries + " tries.");
}
System.out.println("");
System.out.print("Do you wish to try again with a different "
+ "number? (Enter y or n ): ");
again = input.next();
System.out.println("");
}
}
/*
METHOD 1
Description
A method that generates the random number to be guessed returns the
random number to main. Two parameters are the two numbers needed to generate
the random number (1 and 100 in this case).
*/
public static int GetRandomNumber (int rangeLow, int rangeHigh)
{
Random gen = new Random();
int number;
number = gen.nextInt(rangeHigh) + rangeLow;
return number;
}
/*
METHOD 2
This method tells the user if the guess is too low or too high. It will have
2 parameters one for the random number and the second is the user guess.
*/
public static void LowOrHigh (int number, int userGuess )
{
if (userGuess > number )
{
System.out.println("The value that you guessed is too high, "
+"Try guessing a lower number. ");
System.out.println("");
}
else if (userGuess < number )
{
System.out.println("The value that you guessed is too low, "
+"Try guessing a higher number. ");
System.out.println("");
}
}
/*
METHOD 3
This method will get the user guess. It has 2 parameters which will be the
valid range the user should guess between (in this case 1 and 100). It will
return the users guess as an integer. This method should validate that the
users guess is between the two parameters.
*/
public static int GetUserGuess(int rangeLow, int rangeHigh)
{
Scanner scan = new Scanner(System.in);
int userGuess;
System.out.print("Enter a number between " + rangeLow + " and " + rangeHigh + ": ");
userGuess = scan.nextInt();
while (userGuess > rangeHigh || userGuess < rangeLow)
{
System.out.println("The number given was not within the range, Try again ");
System.out.println("");
System.out.print("Enter a number between " + rangeLow + " and " + rangeHigh + ": ");
userGuess = scan.nextInt();
}
return userGuess;
}
}
I'm sorry if its obvious im still pretty new to programming.
Whenever you store a guess, you always store it in guesses[tries], and then immediately afterwards, you increment tries. Your while condition then checks if tries is less than guess.length - 1.
More generally, to program you need to know how to debug. Debugging is generally the act of following along with the code and checking what it actually does vs. what you wanted it to do. You can use a debugger for this, alternatively, you can add a boatload of System.out statements to follow along.
Do that, and you'll find the error in your logic. I've already given you quite a sizable hint in the first paragraph ;)

The If statement in my for loop is acting strangely

My program takes user input to create a sport score table.
Its validation function prints "Invalid input" when the array "words" contains less than 4 elements
for (int i = 0; i < counter; i++) { // A loop to control the Array
String[] words = football_list[i].split(":"); // Splits the input into 4 strings
if (words.length != 4) { // If the length of the array elements does not equal 4 then print error message
System.out.println("Input was not valid");
When I enter an incorrect input FIRST, it then makes the rest of the following scores to be deemed equally incorrect even when they are correct - here is an example of what that looks like on the text console.
Home team : Away team : Home score : Away score
Leeds : Liverpool : 2 :
Home team : Away team : Home score : Away score
Leeds : Liverpool : 2 : 1
Home team : Away team : Home score : Away score
Leeds : Liverpool : 2 : 1
Home team : Away team : Home score : Away score
Leeds : Liverpool : 2 : 1
Home team : Away team : Home score : Away score
quit
Input was not valid
Input was not valid
Input was not valid
Input was not valid
Totals
------------------------- Total games played: 0*
END--
This is where I think the problem is:
for (int i = 0; i < counter; i++) {
String[] words = football_list[i].split(":"); 4 strings
if (words.length != 4) {
System.out.println("Input was not valid");
counter--;
i--;
} else {
System.out.println(words[0].trim() + " [" + words[2].trim() + "]" + " | " + words[1].trim() + " [" + words[3].trim() + "]"); // Formats and prints the output
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" Totals ");
System.out.println("-------------------------");
System.out.println("Total games played: " + counter);
}
}
Don't decrement i inside the loop.
Because you decrement i and counter if input is invalid. And after that increase i in for-statement. In this case you are reading invalid row again and again while counter > i
To make things more readable and less error prone, you could simply use the length of your array to control your loop ending, and increment counter (starting at 0) only when the input is valid :
int counter = 0;
for (int i = 0; i < football_list.length; i++) { // A loop to control the Array
String[] words = football_list[i].split(":"); // Splits the input into 4 strings
if (words.length != 4) { // If the length of the array elements does not equal 4 then print error message
System.out.println("Input was not valid");
} else {
counter++;
System.out.println(words[0].trim() + " [" + words[2].trim() + "]" + " | " + words[1].trim() + " ["
+ words[3].trim() + "]"); // Formats and prints the output
}
}

Why does the second while loop cancel both while loops?

Why does the second while loop while (numberOfTries < 2) cancel both while loops? It runs perfect if there is no incorrect answer. But let's say I select 4 problems to be made, and I am only on the first problem. I give the incorrect answer 2 times so the program should say Incorrect two times and then give me a new question because while (numberOfTries < 2) should force it to break from that loop. But it doesn't, it just quits the whole thing. I know it has to be a logic issue, so what am I missing?
import java.util.Random;
import java.util.Scanner;
public class Howthe {
public static void main(String[] args) {
// Open Scanner
Scanner scan = new Scanner(System.in);
// Ask user to choose number of problems to be made.
// Can only choose 4, 9, or 16
System.out.print("Choose a number of problems to be made (4, 9, 16): ");
int userChoiceOfProblems = scan.nextInt();
// Ask user to choose a number between 0 and 12
System.out.print("\nChoose a number between 0 and 12: ");
int userNumberBetween0and12 = scan.nextInt();
// Ask user to choose between add/sub or multiply/divide
System.out.println("\nChoose to:"
+ "\n0: add/sub your chosen number"
+ " and the randomly generated number: "
+ "\n1: multiply/divide your chosen number"
+ " and the randomly generated number: ");
int userArithmeticChoice = scan.nextInt();
int counter = 0;
String equationString;
int equationAnswer;
int numberOfAnswersRight = 0;
int numberOfTries = 0;
int userAnswerToQuestion;
if (userArithmeticChoice == 0){
while (counter < userChoiceOfProblems){
// Create random number to decide if add or sub used.
// add is equal to 0 and sub is equal to 1
Random rand = new Random();
int randomNumberBetween0and1 = rand.nextInt(1) + 0;
// Create random number that is multiplied by userNumberBetween0and12
int randomNumberBetween0and12 = rand.nextInt(12) + 0;
// Add and increase counter by 1
if (randomNumberBetween0and1 == 0){
// If numberOfTries is more than 2, then display answer.
while (numberOfTries < 2){
// Compute the right answer (addition).
equationAnswer = userNumberBetween0and12 + randomNumberBetween0and12;
// Produce string of equation, then display string (addition).
equationString = userNumberBetween0and12 + " + "
+ randomNumberBetween0and12;
System.out.println(equationString);
userAnswerToQuestion = scan.nextInt();
// If answer is right, increase numberOfAnswersRight.
if (userAnswerToQuestion == equationAnswer){
numberOfAnswersRight++;
System.out.println("Correct!");
break;
}
// If answer is wrong, continue loop and increase numberOfTries
else if (userAnswerToQuestion != equationAnswer){
numberOfTries++;
System.out.println("Incorrect");
}
} // end of while (numberOfTries < 2 && !quit)
counter++;
}
} System.out.println("Yout got " + numberOfAnswersRight + " problem(s) right!");
}
}
}
numberOfTries is initialized outside of your loops. Once you try twice, it never gets set back to 0 which causes the loops to skip and finish on the next question because numberOfTries is already 2.

Average of an array and associate with name

Does anyone know how to display the average race time for participants in this simple program?
It would also be great to display the associated runners name with the time.
I think that I have the arrays structure properly and have taken in the user input.
Thanks for any assistance you can provide. Here's my code...
import java.util.Scanner;
public class RunningProg
{
public static void main (String[] args)
{
int num;
Scanner input= new Scanner (System.in);
System.out.println("Welcome to Running Statistical Analysis Application");
System.out.println("******************************************************************* \n");
System.out.println("Please input number of participants (2 to 10)");
num=input.nextInt();
// If the user enters an invalid number... display error message...
while(num<2|| num >10)
{
System.out.println("Error invalid input! Try again! \nPlease input a valid number of participants (2-10)...");
num=input.nextInt();
}
// declare arrays
double resultArray [] = new double [num]; // create result array with new operator
String nameArray [] = new String [num];// create name array with new operator
// Using the num int will ensure that the array holds the number of elements inputed by user
// loop to take in user input for both arrays (name and result)
for (int i = 0 ; i < nameArray.length ; i++)
{
System.out.println ("Please enter a race participant Name for runner " + (i+1) );
nameArray[i] = input.next();
System.out.println ("Please enter a race result (time between 0.00 and 10.00) for runner " + (i+1) );
resultArray[i] = input.nextDouble();
}
This seems like a homework problem so here is how you can solve your problems, in pseudo-code:
Total average race time for participants is calculated by summing up all the results and dividing by the amount of results:
sum = 0
for i = 0 to results.length // sum up all the results in a loop
sum = sum + results[i]
average = sum / results.length // divide the sum by the amount of results to get the average
It would be even better to perform the summation while you read user input and store the runner's names and results. The reason is that it would be more efficient (there would be no need for a second loop to perform the sum) and the code would be cleaner (there would be less of it).
Displaying runners with theirs times can be done by iterating over the two arrays that hold names and results and print values at corresponding index:
for i = 0 to results.length
print "Runner: " + names[i] + " Time: " + results[i]
This works because you have the same amount of results and names (results.length == names.length), otherwise you would end up with an ArrayIndexOutOfBounds exception.
Another way to do this is to use the object-oriented nature of Java and create an object called Runner:
class Runner {
String name;
double result;
Runner(String n, double r) {
result = r;
name = n;
}
}
Then use an array to store these runners:
Runner[] runners = new Runner[num];
for (int i = 0 ; i < num ; i++) {
System.out.println ("Please enter a race participant Name for runner " + (i+1) );
String name = input.next();
System.out.println ("Please enter a race result (time between 0.00 and 10.00) for runner " + (i+1) );
double result = input.nextDouble();
runners[i] = new Runner(name, result);
}
Then you can just iterate over the array of runners and print the names and the results... Here is pseudo-code for this:
for i = 0 to runners.length
print runners[i].name + " " + runners[i].result

Java Powers display table

I need to display an output like this:
Enter an integer: 3
Number Squared Cubed
====== ======= =====
1 1 1
2 4 8
3 9 27
But instead, when I run the code, I get this output:
Number Squared Cubed
====== ======= =====
3 9 27
In other words, I need to display the powers of an integer,including the powers of the numbers less than or equal to the integer. The numbers of the lesser integers need to be listed but are not displayed along with the integer being entered. How do I fix the code to make sure it outputs all of the integers that are less than or equal to the integer being entered? There are no errors (i.e. red exclamation mark circles) but I need to figure out the proper calculation.
Here is the code:
====================
import java.util.Scanner;
public class Powers
{
public static void main(String[] args)
{
System.out.println("Welcome to the Squares and Cubes Table");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
while(choice.equalsIgnoreCase("y"))
{
// get the input from the user
System.out.println("Enter an Integer: ");
int integerNext = sc.nextInt();
System.out.println("Number" + " " + "Squared" + " " + "Cubed");
System.out.println("======" + " " + "======" + " " + "======");
for(int i = 1; i <= integerNext; i++)
{
i = integerNext;
int numberSquared = (int) Math.pow(i, 2);
int numberCubed = (int) Math.pow (i, 3);
String message = "\n" + i + " " + numberSquared + " " + numberCubed;
System.out.println(message);
System.out.println();
// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
}
}
}
Help is always appreciated. Thanks.
Firstly, as Nikhil said: "Remove the line i = integerNext; It is resetting the value of I and therefore only last row is printed".
Secondly, move the first closing curly brace to before getting user input - you want to run the loop, and only ask about continuing when that's finished, if I understand correctly.
Remove the line i = integerNext; It is resetting the value of I and therefore only last row is printed
Your are almost there. Since you are looping from 1 to integerNext (which is 3 in your text), the looping variable i will get the values [1,2,3] each iteration, so you don't have to set i manually. When you do:
i = integerNext;
you are setting i to 3, so the loop will finish when it reaches the loop condition.
You may also want to put the "Continue?" check outside the loop:
for (int i = 1; i <= integerNext; i++) {
int numberSquared = (int) Math.pow(i, 2);
int numberCubed = (int) Math.pow(i, 3);
String message = "\n" + i + " " + numberSquared + " " + numberCubed;
System.out.print(message);
}
// see if the user wants to continue
System.out.print("\nContinue? (y/n): ");
choice = sc.next();
System.out.println();
import java.util.Scanner;
public class SquaresAndCubes {
public static void main(String[] args)
{
// Welcome the user
System.out.println("Welcome to the Squares and Cubes table");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
do
{
// Get input from the user
System.out.print("Enter an integer: ");
int integer = sc.nextInt();
// Create a header
String header = "Number " + "Squared " + "Cubed " + "\n"
+ "====== " + "======= " + "===== ";
System.out.println(header);
int square = 0;
int cube = 0;
String row = "";
for (int i = 1; i <= integer; i++)
{
square = i * i;
cube = i * i * i;
row = i + " " + square + " " + cube;
System.out.println(row);
}
// See if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
while (!choice.equalsIgnoreCase("n"));
}
}
Basic way to do it with foor loop and some printlines
Scanner sc = new Scanner(System.in);
System.out.print("What number would you like to go up to? ");
int userInt = sc.nextInt();
System.out.println("");
System.out.println("Here is your table!");
System.out.println("");
System.out.println("number | squared | cubed");
System.out.println("------ | ------- | -----");
for (int i = 1; i <= userInt; i++){
System.out.println(i + " | " + (i * i) + " |" + " " +(i * i * i));
}

Categories

Resources