Trying to loop a for loop multiple times - java

Hope this question makes sense but essentially here is the issue I am having. I am tasked to create a program that takes someone's free throw shooting percentage as an input then simulates 5 games where they attempt to shoot 10 free throws each game. As well as have a summary afterward showing things like best game, worst game, total made through all games, and average free throw percentage.
I currently have up to the point where I am trying to make my simulated game run multiple times but cant seem to figure it out. This is what I have so far:
import java.util.*;
public class FreeThrow {
public static int simulate(int input){
int i;
int j;
int count = 0;
for (j = 1; j < 6; j++){
System.out.println("Game " + j + ":");
for(i = 0;i < 10; i++){
int shot = (int)(Math.random()*101)-1;
if (shot > input){
System.out.print("OUT ");//shot missed
} else {
System.out.print("IN ");//shot made
count++;
}
}
//prints the number of free throws made per game out of 10
System.out.print("\nFree throws made: " + count + " out of 10.");
return i;
}
return j;
}
public static void main (String[] args){
//asks for user input to detemine player free throw percentage
Scanner scan = new Scanner(System.in);
System.out.print("Enter Player's Free Throw Percentage: ");
int input = scan.nextInt();
simulate(input);
}
}
As you can see I currently have a for loop inside a for loop. I did this to try to make the simulated game loop loop itself again while adding the "Game 1:" line that would display above and show what game each was. It works perfectly for just one Game. I have it looking exactly like it should. As well here is an example of what the professor wants it to look like:Link To Image
Any sort of insight on what I might be doing wrong or suggestions on how to get it to do what I would like would be greatly appreciated.

I've added to your code so there is now a percentage made and a total, you pretty much had it correct, just had to make a small change so that count could be carried and displayed. If you want to have a best / worst game, you'd need to create two new variables, and update them for each game if the threshold was 1) beaten for best game, and 2) lower for worst game.
If you get stuck with this let me know, and i'll give you a hand. Should be easy enough for you to implement with what you currently know.
The issue was that you were returning i when it was not necessary either. That has been ameneded in this:
public class freeThrow {
private static int count;
public static int simulate(int input){
int i;
int j;
for (j = 1; j < 6; j++){
System.out.println("Game " + j + ":");
for(i = 0;i < 10; i++){
int shot = (int)(Math.random()*101)-1;
if (shot > input){
System.out.print("OUT ");//shot missed
} else {
System.out.print("IN ");//shot made
count++;
}
}
//prints the number of free throws made per game out of 10
System.out.println("\nFree throws made: " + count + " out of 10.");
}
return j;
}
public static int average(int count) {
int average = count/5;
System.out.println("\nAverage is " + average*10 + "%");
return average;
}
public static int totalShots(int count) {
int total = count;
System.out.println("total shots made " + total);
return total;
}
public static void main (String[] args){
//asks for user input to detemine player free throw percentage
Scanner scan = new Scanner(System.in);
System.out.print("Enter Player's Free Throw Percentage: ");
int input = scan.nextInt();
simulate(input);
average(count);
totalShots(count);
}
}

Related

i need to get the total amount of guesses and also the total amount of games played for the guessing game

so this my first time coding and i need a lot of help trying to figure out to get the total amount of guesses and the total amount games played, i dont even know where to start. I can get the code to tell me how many guesses it took to get to the number in one game but not the overall result. Any tips or help?
thank you
import java.util.Scanner;
import java.util.Random;
public class treehouseproject {
//Instruction on how to play the game
public static void instruction() {
System.out.println("this is a guessing game");
System.out.println("you will guess the number");
System.out.println("that i am thinking of");
System.out.println("unitl you guess the correct number");
System.out.println("the number ranges from 0 to 100");
}
//playing a single game
public static void playgame() {
int guessNumber = 0;
int numberGuesses = 0;
int plays = 0;
int max = 100;
int min = 0;
Random randomNum = new Random();
int givenNumber = min + randomNum.nextInt(max);
Scanner scan = new Scanner (System.in);
while(guessNumber != givenNumber){
numberGuesses++;
System.out.println("Guess: " + numberGuesses);
guessNumber = scan.nextInt();
if (guessNumber == givenNumber) {
System.out.println("correct");
System.out.println("you go it right in " + numberGuesses + " guesses");
}
if (guessNumber < givenNumber) {
System.out.println("higher");
}
if (guessNumber > givenNumber){
System.out.println("lower");
}
}
}
//playing muliple games and reporting all end stats
public static void main(String[] args) {
String Answer = "";
instruction();
playgame();
Scanner console = new Scanner(System.in);
System.out.println("do you want to play again?");
Answer = console.nextLine();
boolean keep_playing = true;
while (Answer.equalsIgnoreCase("yes")){
playgame();
System.out.println("do you want to play again?");
Answer = console.nextLine();
}
}
//prints out the stats of the game
public static void results(int plays, int numberGuesses) {
System.out.println("Overall results");
System.out.println("Total amount of guesses = " + numberGuesses);
System.out.println("Total amount of games = " + plays);
}
}
the problem you are encountering actually has a pretty simple solution.
So if you define a variable it as a certain "lifespan" this means that is effectively dies at some point.
Every variable is only "alive" within the parents of its parent.
Example:
public static void main(string args[]){
String s1 = "";
private static void doSomething(){
String s2 = s1;
}
}
The variable s1 is "alive" until the parenthesizes of its parent (main) close, so its also alive within the function and fully usable.
s2 on the other hand is only alive within "doSomething", so it cannot be referenced after its bracket closes.
So moving the initialization of variables to a more "global" level is often very usefull.
You need to move the initialization of the these variables outside of playGame() and to the global level.
numberGuesses
plays

Println printing multiple times instead of increasing for each loop

I'm trying to make this code print out the number of games played (gameNum). Instead, it always sets gameNum to 2, and prints out the last println the number of times that the game was played. I feel like I made a dumb mistake here, but I am having trouble finding it. Could you please give me a hint instead of the answer? I'd like to figure this out on my own. If not, then feel free to go ahead and write the answer.
Thanks!
import java.util.*;
public class Testing_gameNum {
public static final int amt = 1;
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
guessCounter(console);
}
public static int game(Scanner console) {
Random rand = new Random();
int guess = 0;
int guessNum = 0;
System.out.printf("I'm thinking of a number...", amt);
System.out.println();
int num = 1;
do {
System.out.println("Your guess? ");
guess = console.nextInt();
guessNum += guessNum;
} while (guess != num);
return guessNum;
}
public static void guessCounter(Scanner console) {
int gameNum = 1;
int guessNum = game(console);
if (guessNum == 1){
System.out.printf("You won in %d guesses!", guessNum);
System.out.println();
}
gameNum = gameNum + 1;
System.out.println("Do you want to play again?");
String play = console.next();
if (play.equals("y")) {
guessCounter(console);
}
System.out.println("Number of games: " + gameNum);
}
}
Try something like this:
public class Testing_gameNum
{
public static final int amt = 1;
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
guessCounter(console);
}
public static int game(Scanner console)
{
Random rand = new Random();
int guess = 0;
int guessNum = 0;
System.out.printf("I'm thinking of a number...", amt);
System.out.println();
int num = 1;
do
{
System.out.println("Your guess? ");
guess = console.nextInt();
guessNum += amt;
}
while (guess != num);
return guessNum;
}
public static void guessCounter(Scanner console)
{
int gameNum = 1;
do
{
int guessNum = game(console);
if (guessNum == 1)
{
System.out.printf("You won in %d guesses!", guessNum);
System.out.println();
}
gameNum = gameNum + 1;
System.out.println("Do you want to play again?");
String play = console.next();
}
while (play.equals("y"))
System.out.println("Number of games: " + gameNum);
}
}
Check for every place gameNum is used. I found it i.e. in the method guessCounter(Scanner console) - and only there.
So every time you call this method, the value of gameNum is initialized to 1. After the game is won, you increment it by 1 and later on print it, hence the 2 in the output.
Move int gameNum = 1; out of the method guessCounter(Scanner console). This should help.
Aside of this please review also the code block
if (play.equals("y")) {
guessCounter(console);
}
Imagine a player goes on and on, always selecting "y". With every game round, you create another level of recursion. This "do you want to play again" could be implemented by a do-while loop, this will avoid the recursion.
You've defined guessCounter to be a recursive method, but that's probably not what you want for several reasons. First, each time you call guessCounter, you're creating a new gameNum and setting it to 1. You play the game and increment it to 2, but then recurse and never touch that variable again, which is the cause of your bug. Additionally, (although this is unlikely to happen in usual play), you could overflow your stack if you play the game enough times. Each time you play the game, the computer needs to remember the point in code that it needs to return to when it completes that call of guessCounter. Eventually you will run out of memory to store those pointers. Recursion is good for certain problems, but it's better to use loops most of the time.
How about using a loop rather than recursion.
I solved my question! Here's the code (explanation below):
public class Testing_gameNum {
public static final int amt = 1;
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
guessCounter(console);
}
public static int game(Scanner console) {
Random rand = new Random();
int guess = 0;
int guessNum = 0;
System.out.printf("I'm thinking of a number...", amt);
System.out.println();
int num = 1;
do {
System.out.println("Your guess? ");
guess = console.nextInt();
guessNum ++;
} while (guess != num);
return guessNum;
}
public static void guessCounter(Scanner console) {
int gameNum = 0;
String play = "y";
do {
int guessNum = game(console);
gameNum += 1;
if (guessNum == 1) {
System.out.printf("You won in %d guesses!", guessNum);
System.out.println();
}
System.out.println("Do you want to play again?");
play = console.next();
} while (play.equals("y"));
System.out.println("Number of games: " + gameNum);
}
}
MY PROBLEMS: gameNum was resetting each time I called guessCounter. I needed a do/while loop; that way, I could initialize gameNum inside the method, and then loop only the section of the method that needed to be repeated. The repetitive println was linked with that same issue: it was reprinted each time I called guessCounter, as opposed to just the part of the code I wanted repeated.
Thanks for your help, everyone!

How to get a zig zag output in console using java for?

I am very new to coding and not very good at it :(
I've been struggling to do a project for my class for several hours now and I have scoured the internet with little use.
I need to make it appear on my console as if a ball is bouncing back and forth, the width of the ball bounce is set by the user.
So far, my output just produces an infinite left to right diagonal spanning the width chosen by the user.
My code so far:
import java.util.Scanner;
public class Midterm1_1 {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
double yourNum;
System.out.println("How many spaces wide would you like the ball to bounce?");
yourNum= scan.nextDouble();
String ballBounce = new String ("o")
int count = 0;
while (count < 50){
System.out.println(ballBounce);
String x = " ";
for (int row = 1; row < yourNum; row++) {
System.out.println(x+"o");
x+= " ";
}
}
}
}
How do I get it to return right to left? My assumption is another for statement. But so far everything I've tried does not work.
Thank you in advance.
The code below is not necessarily the shortest one, it is meant to get the OP some ideas but without providing her/him with a straight answer. If the OP will copy the code as it is and doesn't adapt it, it should be obvious to the teacher the code is copied from somewhere. In case the OP understands it, it will be easy to clean and simplify the solution.
You have 2 methods below, take your pick only after you read the code and understand it (there is another one which I eliminated on purpose: this is an exercise of learning, so the obvious one is left as an exercise).
For the first method (paintBallAt_1), go read PrintStream.printf
For the second method (paintBallAt_2), go read String.substring
public class Midterm1_1 {
static private String ballBounce = "o";
public static void paintBallAt_1(int x) {
if(x==0) {
System.out.println("o");
}
else {
// will get your format strings as "%1$1c\n", "%1$2c\n", etc
String formatString="%1$"+x+"c\n";
System.out.printf(formatString, 'o');
}
}
// 6x20=120 spaces at max. Limit or expand them how you see fit
static public final String filler=
" "+
" "+
" "+
" "+
" "+
" "
;
static public final int MAX_BOUNCE=filler.length();
public static void paintBallAt_2(int x) {
if(x>MAX_BOUNCE) {
x=MAX_BOUNCE;
}
if(x<0) {
x=0;
}
String bounceSpace=filler.substring(0, x);
System.out.println(bounceSpace+"o");
}
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
int yourNum;
System.out.println("How many spaces wide would you like the ball to bounce?");
yourNum= scan.nextInt();
int count = 0;
while (count < 50) {
System.out.println(ballBounce);
String x = " ";
for (int row = 1; row < yourNum; row++) {
System.out.println(x+"o");
x+= " ";
}
// bounce it to the left
for (int row = yourNum-1; row >= 0; row--) {
switch(row % 2) {
case 0:
paintBallAt_1(row);
break;
default:
paintBallAt_2(row);
break;
}
}
}
}
}

Build a java app that asks the user to input a series of grades between 0-100

Im extremely new at Java programming and my professor asked us to write a program that can:
Show each grade by the letter. (Ex: A, B, C, D, F)
Show the Minimum & Average grade of the class
Show the number of people who passed the exam (70+ is passing)
I have been trying to use arrays and if else statements to solve this but Im not making much progress. Can you guys please help me out?
I know I'm not good at coding, but here is something I am trying.
I also would like to incorporate if else statements in my code to make things simpler.
Thank you so much in advance.
import java.util.Scanner;
public class HelloWorld
{
public static void main (String[] args)
{
double[] grades = new double[10];
int sum
Scanner scan = new Scanner (System.in);
System.out.println ("Number of students: " + grades.length);
for (int index = 0; index < grades.length; index++)
{
System.out.print ("Enter number " + (index+1) + ": ");
grades[index] = scan.nextDouble();
}
}
}
Finding the minimum value is done by using a for loop just like your current one and using:
min = Math.min(min, grades[index]);
The average can be found just by finding the sum inside the loop:
sum += grades[index];
And then divide by the number of values.
The number of grades 70+ can be found with an if statement inside the loop:
if (grades[index] >= 70) {
numPassing++;
}
Each of these operations can also be done using DoubleStream from Java 8:
double min = Arrays.stream(grades).min().orElse(0.0);
double avg = Arrays.stream(grades).average().orElse(0.0);
long numPassing = Arrays.stream(grades).filter(grade -> grade >= 70).count();
Okay I modified the code a bit, plus I didn't used any functionalities provided in java so that you can understand the flow control and logic as being a newbie to java.
import java.util.Scanner;
public class HelloWorld
{
public static void main (String[] args)
{
double[] marks = new double[10];
char[] grades=new char[10];
int[] numGradeStudent={0,0,0,0,0};
int min=0,avg=0,minIndex=0;
Scanner scan = new Scanner (System.in);
System.out.println ("Number of students: " + grades.length);
for (int index = 0; index < grades.length; index++)
{
//Taking marks then applying grades and counting no. of students
System.out.print ("Enter number " + (index+1) + ": ");
marks[index] = scan.nextDouble();
if(marks[index]>90)
grades[index]='A';
if(marks[index]>75 && marks[index]<=90)
grades[index]='B';
if(marks[index]>65 && marks[index]<=75)
grades[index]='C';
if(marks[index]>55 && marks[index]<=64)
grades[index]='D';
else
grades[index]='E';
//Setting up graded students down from here
if(grades[index]=='A')
numGradeStudent[0]++;
if(grades[index]=='B')
numGradeStudent[1]++;
if(grades[index]=='C')
numGradeStudent[2]++;
if(grades[index]=='D')
numGradeStudent[3]++;
if(grades[index]=='E')
numGradeStudent[4]++;
}
min=numGradeStudent[0];
for(int i=0;i<5;i++){
if(numGradeStudent[i]<min){
min=numGradeStudent[i];
minIndex=i;
}
}
System.out.println("Min grade of class is:"+ grades[minIndex]);
for(int i=0;i<10;i++){
if(marks[i]>70)
System.out.println("Student "+(i+1)+" passed.");
}
}
}

Finishing a simple gradebook program in Java, sort and clear functions

This is my first time posting a question here on stack overflow, although I've received help from other answers in the past on here. I am currently working on an assignment to make a gradebook program for my programming class and I have run into some issues.
The prompt can be found here http://bit.ly/1k4osYg
The code that I have so far is:
import java.util.*;
public class temp {
static Scanner in = new Scanner(System.in);
public static void main(){
menu();
}
public static void menu(){
int numStudents = 0;
int numQuizzes = 0;
int[][] array = null;
String choice = null;
boolean fFlag = false;
boolean dFlag = false;
while(choice!="q" || choice!="Q"){
System.out.println("Please enter a command.");
choice = in.next();
if(choice=="h" || choice=="H"){
help();
}
else if(choice=="s" || choice=="S"){
setParams(numStudents, numQuizzes);
fFlag = true;
}
else if( choice=="f" || choice=="F"){
if(fFlag){
fillArray(numStudents, numQuizzes, array);
dFlag = true;
}
else{
System.out.println("Please set paramaters before filling the array.");
clear();
}
}
else if(choice=="d" || choice=="D"){
if(dFlag){
displayResults(numStudents, numQuizzes, array);
}
else{
System.out.println("Please fill the array before displaying");
clear();
}
}
else if(choice=="q" | choice=="Q"){
}
else{
System.out.println("Invalid command. Please enter a valid command.");
}
}
}
public static void help(){
System.out.println("S sets paramaters for program operation, etc, etc.");
System.out.println("F fills array, etc, etc.");
System.out.println("D displays results, etc, etc.");
System.out.println("H brings up the help menu, etc, etc.");
System.out.println("Q quits the program, etc, etc.");
clear();
}
public static void setParams(int numStudents, int numQuizzes){
System.out.println("How many students are in the class?");
numStudents = in.nextInt();
while(numStudents > 50 || numStudents < 0){
System.out.println("Please use a number between 0-50.");
numStudents = in.nextInt();
}
System.out.println("How many quizzes are in the class?");
numQuizzes = in.nextInt();
while(numQuizzes > 5 || numQuizzes < 0){
System.out.println("Please use a number between 0-5.");
numQuizzes = in.nextInt();
}
clear();
}
public static void fillArray(int numStudents, int numQuizzes, int[][] array){
Random gen = new Random();
array = new int[numStudents][numQuizzes];
for(int i = 0; i<numStudents; i++){
for(int j = 0; j<numQuizzes; j++){
array[i][j] = gen.nextInt(100);
}
}
System.out.println("Data entry complete...");
clear();
}
public static void displayResults(int numStudents, int numQuizzes, int[][] array){
int[] tempQuiz = new int[numStudents];
for(int i = 0; i < numQuizzes; i++){
for(int j = 0; j < numStudents; j++){
tempQuiz[j] = array[j][i];
}
sort(tempQuiz); //wtf blizz
float average = 0;
for(int k = 0; k < numStudents; k++){
average += tempQuiz[k];
}
average = average/numStudents;
System.out.println("Quiz "+ i+1 +":");
System.out.println("Lowest Grade: "+ tempQuiz[0]);
System.out.println("Highest Grade: "+ tempQuiz[numStudents-1]);
System.out.println("Average Grade: "+ average);
System.out.println("Medium Grade: "+ tempQuiz[(int) numStudents/2]);
System.out.println();
}
System.out.printf("Student ID\t\t");
for(int i = 0; i < numQuizzes; i++){
System.out.printf("Quiz %n\t\t", i+1);
}
System.out.println();
for(int i = 0; i < numStudents; i++){
System.out.printf("%n\t\t", 75678+i);
for(int j = 0; j< numQuizzes; j++){
System.out.printf("%n\t\t", array[i][j]);
}
System.out.println();
}
clear();
}
private static void clear() {
// TODO Auto-generated method stub
}
}
I've been working on this for four days, and I'm stuck. So any help that y'all can provide will be greatly appreciated.
Also, as a sort of noob-ish question, would it be better to put the GUI in the same class, or to write another class altogether?
EDIT THE FIRST:
My brain is derping all over the place tonight, chock it up to lack of sleep over the past 48 hours. What I need help with specifically are how to sort out the highest grade for each quiz, lowest grade for each quiz, average grade for each quiz, and median grade for each quiz.
My other concern has to do with the variables. I have a distinct suspicion that when I run the program it isn't going to function properly. Should I just move the variables in the menu method as variables of the class?
My final question is whether I should use a separate class for the GUI or just include it as a part of this class.
You don't write main like that. Instead, you're supposed to write it like this:
public static void main(String[] args) {
If you do it that way, you end up with a nasty exception. I'm not sure if this was your problem.
For starters, your setParams method will not work as expected. Java methods do not pass arguments by reference, so changing the value of a parametet inside of a method will not affect its value where the method was called.
Solution 1:
Return a value from the method and store that value in a variable. Methods can return only one value, so you'll have to break setParams into two methods.
Solution 2:
Pass values by updating instance variables (requires redesign of class structure).

Categories