I wrote my code and it works completely, but I didn't write my own methods. The point of the assignment is to practice using subroutines and that's what I have to use. I read about making my own methods--A LOT. But I still can't wrap my mind around it.
Here's a piece of my code. Can you help me by explaining how I'd make my own method with it and call it?
public static void main(String[] args) {
//Display welcome message
System.out.println("Welcome to the Math Functions event!");
Scanner keyIn = new Scanner(System.in);
Scanner userInput;
System.out.print("Press the ENTER key to toss the dice.");
keyIn.nextLine();
//roll dice
Random rand = new Random();
int tries = 0;
int sum = 0;
while (sum != 7 && sum != 11) {
// roll the dice once
int roll1 = rand.nextInt(6) + 1;
int roll2 = rand.nextInt(6) + 1;
sum = roll1 + roll2;
System.out.println(roll1 + " + " + roll2 + " = " + sum);
tries++;
}
}
Any help would be greatly appreciated! Thank you!
Here is an example of a method giving you a random dice roll:
public static int rollDice()
{
Random rand = new Random();
int roll = rand.nextInt(6) + 1;
return roll;
}
You would call the function like this:
int roll = rollDice();
So it could be integrated in your program like this for example:
public static void main(String[] args) {
//Display welcome message
System.out.println("Welcome to the Math Functions event!");
Scanner keyIn = new Scanner(System.in);
Scanner userInput;
System.out.print("Press the ENTER key to toss the dice.");
keyIn.nextLine();
int tries = 0;
int sum = 0;
while (sum != 7 && sum != 11) {
// Here is where you call your newly created method
int roll1 = rollDice();
int roll2 = rollDice();
sum = roll1 + roll2;
System.out.println(roll1 + " + " + roll2 + " = " + sum);
tries++;
}
}
The idea is that you want to split up a complicated task into many smaller ones. This way it makes it much easier to debug. The above is just an example, but if you are performing an operation that you realise is repetitive, a function can never hurt.
Try to think about your function in the following way:
1. What does my function do?
2. What data should it provide me with?
3. What is the minimum my function requires to provide me with this data?
As for a function that counts the characters for a string as mentioned in the comments:
Your function counts the characters in a string.
The data that it provides you with is simply a number.
All you need to get this number is a string.
Given this information, we can come up with the following function protocol:
public static int countCharacters(String myString)
{
int count = myString.length();
return count;
}
The return type and value is an int as this is what it needs to provide you with, and myString is the only data the function needs to work. Thinking this way makes code much more maintainable, and you will be able to break up a complicated task into several very simple steps.
Related
I'm coding an arithmetic game where the user is asked a series of addition questions. I want to however randomly assign an operator for each question so that the question could be either:
Question 1: num1 + num2 =
or
Question 2: num1 - num2 =
I have been using the Math.random() method to randomise num1 and num2 the last thing I am struggling on is randomly generating '+' and '-'.
Is it something to do with the ASCII values of these two characters and then I can randomly pick between them? Thanks for the help!
As a side note, I want to ask the user to 'press enter' to start the game, but i'm not sure how to do it. Currently I've got the user to enter 'y' to start. Any ideas? Thanks so much.
//prompt user to start the game
System.out.println();
System.out.print("Press y to Start the Game: ");
String start_program = keyboard.next();
if (start_program.equals("y")) {
heres my code so far:
public static void main(String[] args) {
//mental arithmetic game
System.out.println("You will be presented with 8 addition questions.");
System.out.println("After the first question, your answer to the previous question will be used\nas the first number in the next addition question.");
//set up input scanner
Scanner keyboard = new Scanner(System.in);
//declare constant variables
final int min_range = 1, max_range = 10, Max_Number_of_Questions = 8;
long start_time, end_time;
//generate 2 random numbers
int random_number1 = (int) ((Math.random() * max_range) + min_range);
int random_number2 = (int) ((Math.random() * max_range) + min_range);
//declare variables
int question_number = 1;
int guess;
//prompt user to start the game
System.out.println();
System.out.print("Press y to Start the Game: ");
String start_program = keyboard.next();
if (start_program.equals("y")) {
//start timer
start_time = System.currentTimeMillis();
//ask the question
System.out.print("Question " + question_number + ": What is " + random_number1 + " + " + random_number2 + "? ");
//take in user input
guess = keyboard.nextInt();
while (guess == (random_number1 + random_number2) && question_number < Max_Number_of_Questions) {
System.out.println("Correct");
++question_number;
//generate a new question
//generate 2 random numbers
random_number1 = guess;
random_number2 = (int) ((Math.random() * max_range) + min_range);
//ask the question again
System.out.print("Question " + question_number + ": What is " + random_number1 + " + " + random_number2 + "? ");
//take in user input
guess = keyboard.nextInt();
}
end_time = System.currentTimeMillis();
int time_taken = (int) (end_time - start_time);
if (guess != (random_number1 + random_number2))
System.out.println("Wrong");
else {
System.out.println();
System.out.println("Well Done! You answered all questions successfully in " + (time_taken / 1000) + " seconds.");
}
}
}
You can use Random#nextInt to pick a random int from 0 to array.length - 1 which you can use as the index of an array of operators.
import java.util.Random;
public class Main {
public static void main(String[] args) {
char[] operators = { '+', '-', '*', '/' };
// Pick a random operator
Random random = new Random();
char op = operators[random.nextInt(operators.length)];
System.out.println(op);
}
}
A sample run:
/
I think for the random - and + characters you could use boolean like so:
Random rd = new Random(); // creating Random object
if(rd.nextBoolean()) {
//Do something
} else {
//Do Something else
}
For the enter, i think this is a game that is played in the console of the ide? Because then you can use a Scanner to track when enter is being pressed.
This will help you i think:
Java using scanner enter key pressed
The thing with the "Enter 'y' to start the game" is totally superfluous, as evidenced by the fact that you obviously don't have sensible things to do when the user does not enter 'y'.
So, since this is a command line application, why would anyone start it and then not want to play the game? Just go ahead and ask the first question! If the user did start that program by accident somehow, there will be no harm whatsoever, it's not that you're going to overwrite important files, start missiles or something like that.
You could try something like this.
Random r = new Random();
int[] signs = { 1, -1 };
char[] charSigns = { '+', '-' };
int a = r.nextInt(20);
int b = r.nextInt(20);
int sign = r.nextInt(2);
System.out.printf("%s %s %s = ?%n", a, charSigns[sign], b);
// then later.
System.out.printf("The answer is " + (a + signs[sign] * b));
Where the commented section is, it says that there is a StackOverflowError - null. I am trying to get it to make random numbers to match up with an inputted value. The goal of this code is to do the following:
Accept a top number (ie 1000 in order to have a scale of (1-1000)).
Accept an input as the number for the computer to guess.
Computer randomly guesses the first number and checks to see if it is correct.
If it is not correct, it should go through a loop and randomly guess numbers, adding them to an ArrayList, until it guesses the input. It should check to see if the guess is already in the array and will generate another random number until it makes one that isn't in the list.
In the end, it will print out the amount of iterations with the count variable.
Code:
import java.util.*;
public class ArrNumGuess
{
public static Integer top, input, guess, count;
public static ArrayList <Integer> nums;
public static void main ()
{
System.out.println("Please enter the top number");
top = (new Scanner(System.in)).nextInt();
System.out.println("Please enter the number to guess (1 - " + top + ")");
input = Integer.parseInt(((new Scanner(System.in)).nextLine()).trim());
nums = new ArrayList<Integer>(); //use nums.contains(guess);
guess = (new Random()).nextInt(top) + 1;
nums.add(guess);
System.out.println("My first guess is " + guess);
count = 1;
if(guess != input)
{
guesser();
}
System.out.println("It took me " + count + " tries to find " + guess + " and " + input);
}
public static void guesser()
{
boolean check = false;
while(!check)
{
guess = (new Random()).nextInt(top) + 1; //Stack Overflow - null
if(nums.contains(guess) && !(guess.equals(input)))
{
count--;
guesser();
}
else if(guess.equals(input))
{
check = true;
System.out.println("My guess was " + guess);
// nums.add(guess);
count++;
}
else
{
System.out.println("My guess was " + guess);
nums.add(guess);
count++;
}
}
}
}
In guesser() method, you're invoking itself:
if(nums.contains(guess) && !(guess.equals(input)))
{
count--;
guesser();
}
There is quite a possibility it will never end. But all that is in while loop, so why not get rid of recurrence and do this in an iterative style?
OK - a different approach to your guesser for fun. Enumerate a randomized sequence of numbers in specified range (1 to 'top') and find the guess in the list whose index is effectively the number of "attempts" and return.
(BTW - #Andronicus answer is the correct one.)
/** Pass in 'guess' to find and 'top' limit of numbers and return number of guesses. */
public static int guesser(int guess, int top) {
List<Integer> myNums;
Collections.shuffle((myNums = IntStream.rangeClosed(1, top).boxed().collect(Collectors.toList())), new Random(System.currentTimeMillis()));
return myNums.indexOf(guess);
}
You are making it more complicated than it needs to be and introducing recursion unnecessarily. The recursion is the source of your stack overflow as it gets too deep before it "guesses" correctly.
There is a lot of sloppiness in there as well. Here's a cleaned up version:
import java.util.*;
public class Guess {
public static void main(String args[]) {
System.out.println("Please enter the top number");
Scanner scanner = new Scanner(System.in);
int top = scanner.nextInt();
System.out.println("Please enter the number to guess (1 - " + top + ")");
int input = scanner.nextInt();
if (input < 1 || input > top) {
System.out.println("That's not in range. Aborting.");
return;
}
ArrayList <Integer> nums = new ArrayList<>();
Random rng = new Random(System.currentTimeMillis());
while(true) {
int guess = rng.nextInt(top) + 1;
if (!nums.contains(guess)) {
nums.add(guess);
if (nums.size() == 1) {
System.out.println("My first guess is " + guess);
} else {
System.out.println("My guess was " + guess);
}
if (guess == input) {
System.out.println("It took me " + nums.size() + " tries to find " + guess);
break;
}
}
}
}
}
I have made it a little further. It turns out I can use loops but not arrays in my assignment. So here's the current version (keep in mind no final calculations or anything yet.) So if you look at the homework method, you can see I am asking for the "number of assignments." Now, for each assignment, I need to ask for and sum both the Earned Score and the Maximum Possible Score. So for instance, if there were 3 assignments, they might have earned scores of 18, 22, and 29, and maximum possible scores of 20, 25, and 30 respectively. I need to grab both using the console, but I don't know how to get two variables using the same loop (or in the same method).
Thanks in advance for your help!
import java.util.*;
public class Grades {
public static void main(String[] args) {
welcomeScreen();
weightCalculator();
homework();
}
public static void welcomeScreen() {
System.out.println("This program accepts your homework scores and");
System.out.println("scores from two exams as input and computes");
System.out.println("your grade in the course.");
System.out.println();
}
public static void weightCalculator() {
System.out.println("Homework and Exam 1 weights? ");
Scanner console = new Scanner(System.in);
int a = console.nextInt();
int b = console.nextInt();
int c = 100 - a - b;
System.out.println();
System.out.println("Using weights of " + a + " " + b + " " + c);
}
public static void homework() {
Scanner console = new Scanner(System.in);
System.out.print("Number of assignments? ");
int totalAssignments = console.nextInt();
int sum = 0;
for (int i = 1; i <= totalAssignments; i++) {
System.out.print(" #" + i + "? ");
int next = console.nextInt();
sum += next;
}
System.out.println();
System.out.println("sum = " + sum);
}
}
I don't know where exactly your problem is, so I will try to give you some remarks. This is how I would start (of course there are other ways to implement this):
First of all - create Assignment class to hold all informations in nice, wrapped form:
public class Assignment {
private int pointsEarned;
private int pointsTotal;
public Assignment(int pointsEarned, int pointsTotal) {
this.pointsEarned = pointsEarned;
this.pointsTotal = pointsTotal;
}
...getters, setters...
}
To request number of assignments you can use simply nextInt() method and assign it to some variable:
Scanner sc = new Scanner(System.in);
int numberOfAssignments = sc.nextInt();
Then, use this variable to create some collection of assignments (for example using simple array):
Assignment[] assignments = new Assignment[numberOfAssignments];
Next, you can fill this collection using scanner again:
for(int i = 0; i < numberOfAssignments; i++) {
int pointsEarned = sc.nextInt();
int pointsTotal = sc.nextInt();
assignments[i] = new Assignment(pointsEarned, pointsTotal)
}
So here, you have filled collection of assignments. You can now print it, calculate average etc.
I hope above code gives you some remarks how to implement this.
import java.util.*;
public class Guess {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
Random r = new Random();
intro();
int numGames = 0;
int numGuesses = game(console, r);
int max = max(numGuesses);
String again = "y";
do {
game(console, r);
System.out.println("Do you want to play again?");
again = console.next();
System.out.println();
numGames++;
} while (again.startsWith("y") || again.startsWith("Y"));
stats(numGames, numGuesses, max);
}
public static void intro() {...}
public static int game(Scanner console, Random r) {
System.out.println("I'm thinking of a number between 1 and 100...");
int answer = r.nextInt(100) + 1;
System.out.println("answer = " + answer);
int guess = -1;
int numGuesses = 0;
while (answer != guess) {
System.out.print("Your guess? ");
guess = console.nextInt();
numGuesses++;
if (guess > answer) {
System.out.println("It's lower.");
} else if (guess < answer) {
System.out.println("It's higher.");
} else {
System.out.println("You got it right in " + numGuesses + " guesses");
}
max(numGuesses);
}
return numGuesses;
}
public static int max(int numGuesses) {
int max = numGuesses;
if (max > numGuesses) {
max = numGuesses;
}
return max;
}
public static void stats(int numGames, int numGuesses, int max) {
System.out.println("Overall results:");
System.out.println(" total games = " + numGames);
System.out.println(" total guesses = " + numGuesses);
System.out.println(" guesses/game = " + numGuesses / numGames / 1.0);
System.out.println(" best game = " + max);
}
}
So this is a small part of my program and the problem I'm having is that my initial int for numGuesses (int numGuesses = game(console, r);) is executing the game method shown below.
All I want from the game method is the return value of numGuesses so that I can forward the value into a different method called stats(numGames, numGuesses, max); . How do I make it so that the initial value isn't executing the method and only the do/while loop is?
Is the way I produce a return statement wrong? Also, my return values aren't saving in my stats method so when I run it, I get the wrong answers.
Then you should put the code that's responsible of generating numGuesses in another method that you will use on both main and game, for example:
public static int game(Scanner console, Random r) {
int numGuesses = getNumberOfGuesses(..);
//continue implementation here
}
public static void main(String[] args) {
int numGuesses = getNumberOfGuesses(..);
//use value
}
You should get familiar with class variables. At the top of your class, you can declare a variable and also give it a value. That is what you should do with numGuesses if you want to access it from different methods in your class. Here is the Foobar example:
class Foo {
private int bar = 0;
private void foobar(int arg) {...}
}
You just need to watch out that you don't do int numGuesses somewehere in a method as that would create a second local variable. The class variable can be accessed via just the name.
Next, you want to keep track of the total games played and the total guesses. You can guess now (hahaha), that you need to use class variables as well. If you need to keep track of the total guesses even when the program is restarted you will need to store these values in a file, but that will be for another time.
Finally, two more little things.
1.) The method max. I do not know what max should do, but at the moment it is just returning the value passed to it. Also the if statement will never execute (x can't be higher than x).
2.) You should maybe consider not making everything static. It obviously works that way, but that is not, what is called object-oriented programming.
My name is Fermin. I'm new in this forum and I'm also studying Java to be a Java developer. I'm stuck on an assignment and I would like some help from anyone. Here is the description and the code
Using an if statement in the for block, determine
whether randNum and guessNum are equal.
public class GuessGame {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int randNum , guessNum ;
//Generates a random number from 1 to 10
randNum = new java.util.Random().nextInt(10) + 1;
System.out.println("Im thinking of a number from 1 to 10");
for (guessNum = 0; guessNum <= 10; guessNum ++){
java.util.Scanner scan = new java.util.Scanner(System.in);
guessNum = scan.nextInt();
if (guessNum == randNum) {
System.out.println("you guess" + guessNum );
}
}
}
}
Updated code
import java.util.Random;
import java.util.Scanner;
public class NumberGuess {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random rand = new Random();
System.out.println("Im thinking of a number from 1 to 10");
int number = scan.nextInt(10);
//Generates a random number from 1 to 10
int number2 = rand.nextInt(10)+1;
System.out.println("you enter the number" + " " + number);
for (int counter = -1; counter < 3; counter ++ ){
if(number!= number2)
System.out.println("and your random number is:" + " " + number2 + " " + "please try again");
else
System.out.println("your guess number is equal to the random number Good job guessing");
break;
}
}
}
Your for loop is controlled by the guessNum variable. Within the loop, you're reassigning that variable's value when you do this:
guessNum = scan.nextInt();
As a result, you're likely getting an inconsistent number of loops because you're changing the variable that the loop relies on for control.
Given the name of this variable, I suspect you originally intended it to be used to store the user's input. If that is the case, I would alter your for loop to use a different variable instead, like so:
for (int guessCount = 0; guessCount < 10; guessCount++){
Also note, your condition originally had <= 10; since your counting variable started at zero, this will allow the user 11 guesses, rather than 10 (since 0 to 10 inclusive = 11). Assuming you wanted 10 guesses instead, you will want to check for less than 10 (since 0..10 exclusive = 10).
import java.util.Random;
import java.util.Scanner;
public class NumberGuess {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random rand = new Random();
System.out.println("Im thinking of a number from 1 to 10");
int number = scan.nextInt(10);
//Generates a random number from 1 to 10
int number2 = rand.nextInt(10)+1;
System.out.println("you enter the number" + " " + number);
for (int counter = -1; counter < 3; counter ++ ){
if(number!= number2)
System.out.println("and your random number is:" + " " + number2 + " " + "please try again");
else
System.out.println("your guess number is equal to the random number Good job guessing");
break;
}
}
}