This is a homework that I was working on. I have created 2 classes to play Towers of Hanoi. The first one is the basically a runner to run the actual game class.
import java.util.Scanner;
class TowersRunner {
public static void main(String[] args) {
TowersOfHanoi towers = new TowersOfHanoi();
towers.TowersOfHanoi()
}
}
public class TowersOfHanoi {
public static void main(String[] args) {
System.out.println("Please enter the starting " + "number of discs to move:");
Scanner scanner = new Scanner(System.in);
int num_of_discs = scanner.nextInt();
solve(num_of_discs, 'A', 'B', 'C');
}
public static void solve(int first_disc, char aTower, char bTower, char cTower) {
if (first_disc == 1) {
System.out.println("Disk 1 on tower " + aTower + " moving to tower " + cTower);
} else {
solve(first_disc - 1, aTower, cTower, bTower);
System.out.println("Disk " + first_disc + " on tower " + aTower + " moving to tower " + cTower);
solve(first_disc - 1, bTower, aTower, cTower);
}
}
}
What I need help with is to make the TowersOfHanoi class to run from my TowersRunner class. I also need to implement a counter display how many times it took for the game to run until the game is finished in my TowersOfHanoi class. Basically I need line that is System.out.println("It took" + counter + "turns to finish.");
I don't know how to implement the counter correctly. Also, can't make the runner class to run the TowersOfHanoi. The TowersOfHanoi class runs fine by itself but the requirment for the homework is we need at least 2 classes min.
Help would be much appreciated!!! Please I am a novice in Java and programming in general please don't go too advanced on me. :D
You don't need the main-Function in the TowersOfHanoi class.
Instead, replace your TowersRunner main(String args[]) method with
public static void main(String[] args) {
System.out.println("Please enter the starting " + "number of discs to move:");
Scanner scanner = new Scanner(System.in);
int num_of_discs = scanner.nextInt();
TowersOfHanoi.solve(num_of_discs, 'A', 'B', 'C');
}
You can just pass the counter in the function and have it be incremented. For example:
public static void solve(int first_disc, char aTower, char bTower, char cTower, int counter) {
System.out.println("Currently on turn #" + counter);
if (first_disc == 1) {
System.out.println("Disk 1 on tower " + aTower + " moving to tower " + cTower);
} else {
solve(first_disc - 1, aTower, cTower, bTower, counter + 1);
System.out.println("Disk " + first_disc + " on tower " + aTower + " moving to tower " + cTower);
solve(first_disc - 1, bTower, aTower, cTower, counter + 1);
}
}
In the first call of solve, you would pass in 1. As you can see, each time solve is called recursively, the counter is incremented.
I'll leave you to adapt this to return the final value of counter :) If you just need the final value, you don't need to add a parameter at all. Just make the function return int instead of void then try and figure out how you would make it return the value you want.
Related
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;
}
}
}
}
}
So I was wondering if someone could show me how I can call/reference a variable from one method into another method. For example,
public static void main(String[] args)
{
System.out.println("Welcome to the game of sticks!");
playerNames();
coinToss();
}
public static void playerNames()
{
Scanner input = new Scanner(System.in);
System.out.println();
System.out.print("Enter player 1's name: ");
String p1 = input.nextLine();
System.out.print("Enter player 2's name: ");
String p2 = input.nextLine();
System.out.println();
System.out.println("Welcome, " + p1 + " and " + p2 + ".");
}
public static void coinToss()
{
System.out.println("A coin toss will decide who goes first:");
System.out.println();
Random rand = new Random();
int result = rand.nextInt(2);
result = rand.nextInt(2);
if(result == 0)
{
System.out.println(p1 + " goes first!");
}
else
{
System.out.println(p2 + " goes first!");
}
}
I want to use p1 and p2 from playerNames() inside of coinToss() so I can simply announce who goes first, but I just can't figure out how to call the variables.
My question is not really different compared to others, however I was unable to understand the answers others were given. Once I posted this I got the answer from a bunch of kind people :)
I'm assuming you are new to Java, because it seems you aren't familiar with the concept of fields (i.e. you can put variables outside methods).
public class YourClass {
static String p1;
static String p2;
public static void main(String[] args)
{
System.out.println("Welcome to the game of sticks!");
playerNames();
coinToss();
}
public static void playerNames()
{
Scanner input = new Scanner(System.in);
System.out.println();
System.out.print("Enter player 1's name: ");
p1 = input.nextLine();
System.out.print("Enter player 2's name: ");
p2 = input.nextLine();
System.out.println();
System.out.println("Welcome, " + p1 + " and " + p2 + ".");
}
public static void coinToss()
{
System.out.println("A coin toss will decide who goes first:");
System.out.println();
Random rand = new Random();
int result = rand.nextInt(2);
result = rand.nextInt(2);
if(result == 0)
{
System.out.println(p1 + " goes first!");
}
else
{
System.out.println(p2 + " goes first!");
}
}
}
what you are searching for is called instance variables, check this out.
https://www.tutorialspoint.com/java/java_variable_types.htm
All I had to do was create the instance/static variables outside! Like this:
static String name1;
static String name2;
It was very easy. Thanks everyone for your help!
So I just whipped up this quick little demo game in like 30 minutes and I was wondering 2 things:
How could I organize my code more?
Would you be willing to play a game like this?
I know that I could use classes but I'm a bit inexperienced them. I'm confused on how to get variables from specific classes. Would I need to import them into the main method class?
import java.util.Scanner;
public class mainGame
{
public static Scanner kboard = new Scanner(System.in);
public static boolean loop = true;
public static int treesInArea = 0;
public static int day = 0;
public static int wood = 0;
public static int woodCollected = 0;
public static int woodLevel = 0;
public static void main(String[] args)
{
System.out.println("__________________________________");
System.out.println(" Welcome to seul...Lets begin ");
System.out.println(" You woke up in the middle of ");
System.out.println(" a forest. Use the command walk ");
System.out.println(" in order to walk into a new area ");
System.out.println("__________________________________\n");
while(loop == true)
{
String choice = kboard.nextLine();
if(choice.equalsIgnoreCase("walk"))
{
treesInArea = (int)(Math.random() * 20);
System.out.println("__________________________________");
System.out.println("The number of trees in this area is");
System.out.println(treesInArea + " trees");
System.out.println("__________________________________\n");
day++;
System.out.println(" It is day " + day + " ");
System.out.println("__________________________________\n");
System.out.println(" Current usuable commands are : ");
System.out.println(" - Chop tree\n");
} else
if(choice.equalsIgnoreCase("choptree") || choice.equalsIgnoreCase("chop tree"))
{
if(treesInArea < 1)
{
System.out.println("There are no trees in this area.");
} else
{
woodCollected = (int)(Math.random() * 10);
treesInArea --;
wood += woodCollected;
woodLevel += (int)(Math.random() * 2);
System.out.println("__________________________________");
System.out.println(" You collected " + woodCollected + " wood");
System.out.println(" Your total wood = " + wood);
System.out.println(" Your total woodcutting level = " + woodLevel);
System.out.println("__________________________________\n");
}
}
}
}
}
You could improve your code in 4 main ways:
1 • Your code-indentation is not great, it should be a 4 space(or just press tab) indent after class name, loops, if statements etc. Example:
private methodName() {
for(int i = 0; i < 10; i++;) {
//do something
}
}
2 • It is easier to read your code when braces are right after methods/loops, and it takes less space, such as(5 lines of neat code):
if (condition = true) {
//do something
} else {
//do something else
}
Rather than(7 lines of messy code):
if (condition = true)
{
//do something
} else
{
//do something else
}
because when you have long if-else blocks, or long loops, it can become hard to read.
3 • You do not need to add spaces after a line, this does nothing. So this:
System.out.println(" It is day " + day + " ");
Can become this:
System.out.println(" It is day " + day);
4 • Lastly, the best way to organize code is by "dividing and conquering". This means make methods even if they're very short, to prevent repeat-code and save time. For example, you printed this line: System.out.println("__________________________________"); 7 times in your program. If you make a method like the one below, you can save time and space, by avoiding repeat-code, and simply call the method using printDivider(); wherever you used this line:
private static void printDivider() {
System.out.println("__________________________________");
}
Yes, I would play your game(in fact i did play your game), but you could improve it, by adding more possibilities, or different 'paths' to go down, ending in different results.
I have been trying to write code, which makes the machine guess a random number from 1 to 1000.
Because I know how to write it in pascal and python, I tried to write it in java, but I'm stuck now.
Here is the code:
import java.util.concurrent.ThreadLocalRandom;
public class Test {
public static void main(String[] args) {
int random = ThreadLocalRandom.current().nextInt(0, 1000);
int count = 0;
do {
int answer = ThreadLocalRandom.current().nextInt(0, 1000);
count++;
} while (random != answer);
System.out.println("Answer: " + answer + " " + "Count: " + count);
}
}
The problem is, that in this line
} while (random != answer);
answer is not defined.
I am trying to do the loop, until random equals answer.
The question is, how do I define the answer variable as a random changing number, while the variable random stays the same?
Thanks in advance!
You have to define int answer outside of the do{}while(...):
public static void main(String[] args) {
int random = ThreadLocalRandom.current().nextInt(0, 1000);
int count = 0;
int answer;
do {
answer = ThreadLocalRandom.current().nextInt(0, 1000);
count++;
} while (random != answer);
System.out.println("Answer: " + answer + " " + "Count: " + count);
}
Exercise 1: Write an application that prints the hundreds digit in two integers read from the keyboard. For example, if the data values are 1456 and 254 respectively, your program should print 4 and 2. You may choose the integers yourself. Your output should include the original number followed by the digit in the hundreds position. Label your output appropriately.
That was my question; here's the code I attempted to write using Eclipse.
public class Hundreds
{
int first1 = 1523;
first2 = first1 % 1000;
first3 = first2 / 100;
System.out.println("Original number equals: " + first1);
System.out.println("Hundreds digit equals: " + first3);
int second1 = 589;
second2 = 589 / 100;
System.out.println("Original number equals: " + second1);
System.out.println("Hundreds digit equals: " + second2);
}
I'm sure there would be a better method to naming the numbers; that's just what I came up with… but Eclipse shows an error reading:
java.lang.NoSuchMethodError: main
Exception in thread "main"
when I attempt to run it. Any ideas on what I've done incorrectly here?
You need a main() method. The error message you see is because the JVM wants to run main(), but it cannot find it.
A canonical Java example (taken from http://en.wikipedia.org/wiki/Java_(programming_language)#Hello_world) is:
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
You need to put your logic in a main method:
public class Hundreds {
public static void main(String[] args) {
int first1 = 1523;
first2 = first1 % 1000;
first3 = first2 / 100;
System.out.println("Original number equals: " + first1);
System.out.println("Hundreds digit equals: " + first3);
int second1 = 589;
second2 = 589 / 100;
System.out.println("Original number equals: " + second1);
System.out.println("Hundreds digit equals: " + second2);
}
}
You need to have a main method as in the Java programming language, every application must contain a main method (entry point) whose signature is:
public static void main(String[] args)
So your code should look like:
public class Hundreds
{
public static void main(String[] args) {
int first1 = 1523;
int first2,first3,second2;
first2 = first1 % 1000;
first3 = first2 / 100;
System.out.println("Original number equals: " + first1);
System.out.println("Hundreds digit equals: " + first3);
int second1 = 289;
second2 = 589 / 100;
System.out.println("Original number equals: " + second1);
System.out.println("Hundreds digit equals: " + second2);
}
}
You could see The Method main; it's a short explanation of its usages.
You need a main method.
public class Hundreds {
public static void main(String[] args) {
// put code here
}
}
Dude...
Where is your main method?
public static void main.....
The rest of your code should go inside it...
BTW, this is the part where you hit your forehead and say "duh..." ;-)
Good luck