addition game fence-post issue, addition sign shows before the equation - java

I am making an addition game but the only problem I have is that the addition sign keeps showing up before the problem even though there is no number in front of it. What is the easiest way to fix this?
package addgame;
import java.util.Random;
import java.util.Scanner;
public class AddingGame {
private static Scanner console;
public static void main (String[]args) {
System.out.println("We are going to play an adding game, you have 3 tries. Type your answer.");
equation();
}
public static void equation() {
int tries = 5;
int points=0;
Random rand = new Random ();
while (tries>=3) {
int totalnums = rand.nextInt(4)+1;
int sumAns=0;
for (int i=1; i<=totalnums+1;i++) {
int nums= rand.nextInt(10)+1;
System.out.print(" + "+nums );
sumAns+=nums;
}
System.out.print(" = ");
console = new Scanner (System.in);
int ans = console.nextInt();
if(ans!=sumAns) {
tries--;
}
else if(tries>=3) {
points++;
}
if(tries<3) {
System.out.println("Game Over...");
System.out.println("Points="+points+"\nBetter luck next time!");
}
}
}
}

There are a couple issues here beyond what you posted.
First of all, don't use tries = 5 when they only have 3 tries. This is unclear. What if you or someone else has to look over this program at a later date? Would you know what "tries = 5" meant?
If you instead say something like
int triesLeft = 3;
There is far less ambiguity. And by starting on 3, your while statement is also more straightforward.
while (triesLeft > 0) {
Similarly, it is a bit unclear how many numbers you want to add. As you've noticed, it would be problematic in an addition game if the number of numbers you were adding was 0 or 1. Your solution does work. However, if you instead did this... (I've included one possible solution to your question in this block of code as well.)
int numberOfAddends = rand.nextInt(4)+2; //This assumes the maximum number of numbers you want to add is 5 (i.e. 3 + 2), and the minimum number is 2.
int sumAns = rand.nextInt(10)+1; //Now note these two lines.
System.out.print(sumAns); //this will make sure the first number is printed before the + sign
for (int i=1; i < numberOfAddends;i++) {
//the inside of this for loop can stay the same.
}
Notice that it is easier to tell what is going on now. It might be worthwhile considering if there are any ways you could make it even clearer.
Past this point, it's really just small things with your code.
while(triesLeft > 0) {
.
.
.
if(ans!=sumAns) {
tries--;
}
else { //the check you specified was only ever reachable when the condition you were checking is true. What you wrote was equivalent to else if (true).
points++;
}
}
System.out.println("Game Over..."); //You don't need a check for this when it is placed outside the while loop.
System.out.println("Points="+points+"\nBetter luck next time!");

Related

Break into Java Classes

I'm trying to finish a project for one of my courses and I'm almost done, but having issues. For this I was able to get something to work but I'm not really sure how I should go about breaking it into the required classes.
The final project is supposed to have a GuessApp class that runs the simple guessing game using the GuessLogic (which I have as correct) which handles the logic of the game. In other words, the GuessApp class is not to keep track of the correct answer, the number of guesses made, the numbers previously guessed, or whether a guess is legal. On the other hand, the GuessApp class is responsible for all of the I/O. In other words, the GuessLogic class is not to print anything (except possibly for the purposes of debugging).
So my question is essentially how do I break up my code into these 2 classes and we were also supposed to implement a toString method in your GuessLogic class that returns the state of the GuessLogic object (that is, all of its member variables) as a single string. How would I do this?
My code thus far:
package guessapp;
import java.util.HashSet;
import java.util.Scanner;
public class GuessApp {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
HashSet<Integer> hs = new HashSet<>();
int GuessLogic = (int) (Math.random() * 10 + 1);
int guess;
int NumGuess = 1;
do {
System.out.print("Enter a guess: ");
guess = keyboard.nextInt();
if (hs.contains(guess)) {
System.out.println("You have already entered this number");
continue; // this will repeat the loop
}
if (guess < 0 || guess > 10) {
System.out.println("Your guess is out of the specified range. Please try again.");
continue; // this will repeat the loop
}
System.out.println("Your guess is " + guess);
if (guess == GuessLogic) {
System.out.println("You got it right!! Congrats!! Total Number of Guesses: " + NumGuess);
return; // this will stop the loop
}
else if (guess < GuessLogic) {
System.out.println("You are wrong!!! Hint: Guess Higher, Guess number: " + NumGuess);
NumGuess++;
}
else if (guess > GuessLogic) {
System.out.println("You are wrong!!! Hint: Guess Lower, Guess number: " + NumGuess);
NumGuess++;
}
hs.add(guess);
} while (true);
}
}
Well, do it by steps.
Create the GuessLogic class, and move to it all the data fields.
public class GuessLogic {
HashSet<Integer> hs = new HashSet<>();
int GuessLogic = (int) (Math.random() * 10 + 1);
int guess;
int NumGuess = 1;
...
Provide a method to add a guess
public void guess(int guess){
this.guess=guess;
this.NumGuess++;
validate();
}
Implement the validate method. Here you have loads of choices. You could keep an enumeration with the current state, something like
enum State {
START,
DUPLICATE,
OUT_OF_RANGE,
LOWER,
HIGHER,
MATCH
}
And validate would set the state.
Then your App queries the state and print the actual message.
Or, which would be simpler, your logic should calculate the message and just maintain a boolean shouldStop, that the app would query to know if it should prompt again or exit
the toString() method, you could just concatenate all the field values (most objects in the Java API have a meaingful toString(). Hint: a good IDE can generate the toString() automatically from the fields.
Hope this helps, and don't be afraid to try things!!

How to print each number up to a certain number

I am taking an online MOOC to learn Java, the only problem i have is it is from the university of Helsinki in Finland i live in the US so there are limited times when i can be awake to ask for help on an exercise. my current exercise is to ask the user for a number and then print each whole number up to that number while using a
while {
}
statement
this is the code i have currently
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int number = Integer.parseInt(reader.nextLine());
System.out.print("up to what number?:"+ number);
while (number<=number){
System.out.println(number);
number++;
}
}
and what it looks like it is doing is ignoring the
while (number<=number) {
System.out.println(number);
part of my code and proceeding straight to the
number++;
portion of my code do i need to declare another int(variable) to store a value?
the way the course has the test cases for grading i can't simply declare a variable with a definite value as they run several test cases like positive numbers and negative numbers.
is there a way to use the reader to store a value to two separate variables so that they can be compared against each other and only print the numbers up to that number?
i also know that i am missing a
Break;
statement but i am not sure where i would place it in the code i have, i have tried to use
} else {
break;
but get an error stating that i have an else without an if.
i am using netbeans as it is required for my course because the server submissions are setup through TMC.
thinking about it now i'm sure its not skipping the while statement but simply continues to print because as it prints and increments the users input is incremented as well since i only have the one variable but i am again not sure how i would go about storing the user input value in two different variables where i can compare them with the less than or equal to statement and stop the printing once it reaches the number input by the user, in that case i would not necessarily need the break statement as it would stop once it prints up to the number input.
ANSWERED: here is what i finally came up with as my answer.
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("up to what number?:");
int numbers = 1;
int number = Integer.parseInt(reader.nextLine());
while (numbers <= number){
System.out.println(numbers);
numbers++;
}
}
You are comparing number to itself. So (number <= number) is always true.
Use a different variable, such as count to actually count up. Initialize it at zero.
Change the condition to (count < number), then in the loop change the increment to count++ and then output count.
Oh, and you should probably prompt for the number before you read it in.
ie your whole program will be:
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("up to what number?:");
int number = Integer.parseInt(reader.nextLine());
int count = 0;
System.out.println(number);
while (count<number){
count++;
System.out.println(count);
}
}
You need another variable to increment upto inserted number
int i=1;
while (i<=number){
System.out.println(i++);
}
What your loop is doing
while (number<=number){
System.out.println(number);
number++;
}
for example number=10 so it's checking like this 10<=10 do you need this,absolutely not.
So for your code you need an another variable to increment up to entered number.
This would do it:
public static void main(String[] args) {
int startingInt = 1; //begin printing from 1
System.out.println("Up to what number?");
Scanner reader = new Scanner(System.in);
int number = Integer.parseInt(reader.nextLine());
while (startingInt <=number){
System.out.println(startingInt);
startingInt++;
}
}
i'm c# expert, so first of all please use c#.
But I know I know you can't always select your laguagued, ;)
Here is solution , it works on my machine.
while (number<=number){
System.out.println(number);
number++;
if (number==arg[0]) break;
}
Enjoy the solution!
System.out.println("Up to what number?");
int number = Integer.parseInt(reader.nextLine());
int n = 1;
while (n <= number) {
System.out.println(n);
n++;
}

Fibonacci Riddle almost right in need of a quick fix and an easy solve

Help I have a puzzle that needs solved!
I made a Fibonacci series but I forgot to include the 0
Who can help me solve this riddle?
If the input is five in the sequence the output should be 0,1,1,2,3
What should I change to clean up the code and get the desired result without completely starting from scratch?
//Class Assignment 9 little Fibonacci series based on what input
//the user provides
import java.util.Scanner;
public class LittleFibonacci {
int number;// This declares an int variable
public static void main(String[] args){
//itnu is the new object
LittleFibonacci itnu = new LittleFibonacci ();
itnu.GetNumberInput();
}
public void GetNumberInput()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a number and that number will be a" +
" \nrepresentitive of the length of a sequence in the Fibonocci series.");
number = input.nextInt();
int f1, f2=0, f3=1;
for(int i = 1 ; i <= number ; i++ )
{
System.out.print(" "+f3+" ");
f1 = f2;
f2 = f3;
f3 = f1 + f2;
}
input.close();
}
}
Just start your loop at zero instead of one, and change the initializations of {f1,f2,f3} accordingly (left as an exercise for the reader).
The other solutions here that tell you to output zero first are basically cheating. You might as well just hard-code all the Fibonacci numbers. You won't get any marks for doing that.
Add
System.out.print(" "+f2+" ");
before the for loop. Change the for loop terminating condition to <.
I guess to be really completist we should also check that the user does not enter 0 (or a negative number) and not even print f2 in that case.
This may seem slightly "unclean" but the fibonacci sequence has two starting numbers, they are special and need special treatment.
the approach I would take, is to print your base cases first, and then reset them after each iteration
int fPrev = 0, fCur = 1;
System.out.print(fPrev+" "+fCur);
for(int i = 2 ; i <= number ; i++ )
{
int fNew = fPrev + fCur
System.out.print(" "+fNew);
fPrev = fCur;
fCur = fNew;
}

Need To Take Input To Array Until User Enters 0 JAVA

I need help understanding how to write a for loop that takes in a certain amount of integers (must be 1 through 10) and it stops taking in numbers once 0 is entered (0 will be the last number). My code so far is:
import java.util.Scanner;
public class countNum {
public static void main(String[] args) {
int[] array;
Scanner input = new Scanner(System.in);
System.out.println ("Enter in numbers (1-10) enter 0 when finished:");
int x = input.nextInt();
while (x != 0) {
if (x > 2 && x < 10) {
//Don't know what to put here to make array[] take in the values
}
else
//Can I just put break? How do I get it to go back to the top of the while loop?
}
}
}
}
I don't understand how to simultaneously initialize an array with a set length while having the Scanner read a certain amount of digits of that unknown length, until 0 is entered, and then the loop stops taking in input for the array.
Thanks for any help!
Ok here's the bit more detail: -
You need to use an ArrayList if you want a dynamically increasing array. You do it like this: -
List<Integer> numbers = new ArrayList<Integer>();
Now, in your above code, you can put your number reading statement (nextInt) inside the while loop, since you want to read it regularly. And put a condition in while loop to check whether the entered number is an int or not: -
int num = 0;
while (scanner.hasNextInt()) {
num = scanner.nextInt();
}
Further, you can move on your own. Just check whether the number is 0 or not. If it is not 0, then add it to ArrayList: -
numbers.add(num);
If its 0, break out of your while loop.
And you don't need that x != 0 condition in your while loop, as you are already checking it inside the loop.
In your case, the user seems to be able to input any number of digits. For this scenario, having an array is not ideal simply because the size of the array needs to be known prior to the array initialization. You have some options though:
Use an ArrayList. This a dynamic data structure which expands dynamically.
Ask the user the amount of numbers he/she is going to be entering and use that to initialize the array.
Create an array basing yourself on some assumption on the size.
In both cases 2 and 3, you would also need to include some logic that will make the program stop when: (1) The user enters 0 (2) OR when the amount of numbers provided by the user exceeds the size of the array.
I would recommend sticking to the first solution though since it is easier to implement.
I strongly recommend you go get some hands on with Java Collections.
you can fix your program as
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Scanner;
public class arrayQuestion {
public static void main(String[] args) {
List<Integer> userInputArray = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
System.out.println("Enter 10 Numbers ");
int count = 0;
int x;
try {
do {
x = input.nextInt();
if (x != 0) {
System.out.println("Given Number is " + x);
userInputArray.add(x);
} else {
System.out
.println("Program will stop Getting input from USER");
break;
}
count++;
} while (x != 0 && count < 10);
System.out.println("Numbers from USER : " + userInputArray);
} catch (InputMismatchException iex) {
System.out.println("Sorry You have entered a invalid input");
} catch (Exception e) {
System.out.println("Something went wrong :-( ");
}
// Perform Anything you want to do from this Array List
}
}
I hope this will solve your doubt..
beyond this u need to handle Exceptions if user enters any character or invalid inputs as above

A program that will loop under the conditions of an operator

I'm writing a java program that will count up to a number that the user inputs. The user is only allowed to input a number that is between 1-10.
For instance:
if the user entered 6 the output will be:
1 2 3 4 5 6
How do I do this with only using operators and while and if statements?
Here's my code. I've been painfully trying to figure out why my code won't work. Thanks in advance!
import java.util.Scanner;
public class loop_lab {
public static void main(String[] args) {
System.out.println("Hi user, input any number that is between 1-10");{
Scanner input = new Scanner(System.in);
int num1 = input.nextInt();
int num2 = 0;
if (1<=num1 && num1>=10);
num2=0;
while (num2 < num1)
System.out.println(""+(num2 + 1));
num2++;
}
}
}
I think the problems lies with the code-blocks (the stuff between {}). Especially look at how the while-loop behaves. What is supposed to be in the loop and what not? Also, your if-statement is empty. The ; closes the code-block that is handled by the if.
An IDE can help you detect these errors by applying syntax-formatting. The comments in your code looked like they were coming from Eclipse. Try ctrl-shift-f (or look it up in the menu). This automatically formats and indents your code, this makes it easier to detect errors in the structure.
The if has a stray trailing ; As a result, the next line is always run.
I make it a point to include even single line statements involved with conditional statements and loops inside {/}. That helps make the start & end of the code block clear. My earlier comment about the code indentation is also a factor in identifying where code block begin & end.
First, your conditional check should use an or and braces; and assign 0 to num1, as to prevent the loop from running if the user inputs anything outside the 1-10 range:
if (num1 < 1 || num1 > 10){
num1=0;
}
And you can also improve your loop:
while (num2 < num1) {
System.out.println( ""+ num2++ );
}
Also, as said by user689893, check your {} blocks.
in while loop just change
while (num2 < num1){
if(num2==0)
System.out.println((num2 + 1));
else{
num2++;
System.out.println(num2);
}
}
Try this one
import java.util.Scanner;
public class loop_lab {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hi user, input any number that is between 1-10");
Scanner input = new Scanner(System.in);
int num1 = input.nextInt();
int num2 = 1;
if (1<=num1 && num1>=10){
num2=1;
while (num2 <= num1)
{
System.out.println("" + num2);
num2++;
}
}
}
}

Categories