Having a few problems after recently starting Eclipse Java - java

Hello I have start learning Java coding on Eclipse recently and have only made a few very simple things.
I am trying to make a basic game where a random number from 1-100 is chosen by the program and you have to try and pick it, with the program telling you whether you are higher or lower. However I've encountered a few problems.
import java.util.Scanner;
import java.util.*;
public class numbergame {
/**Number guessing game
* calculates a random number and has the player guess it
*/
public static void main (String[] args) {
int myNumber, guess;
System.out.println("What is your guess?");
Scanner guessScanner = new Scanner(System.in);
Random myNumber = new Random();
int number = randomNumber.nextInt(100);
guess = guessScanner;
if (guess<myNumber) {
System.out.println ("The Number is less");
}
if (guess>myNumber) {
System.out.println ("Your guess is more");
}
else{
if (guess==myNumber)
System.out.println ("Your number is correct");
}
}
}
This is what I have done so far,
The following lines are not working but I am not sure how to fix them:
Random myNumber = new Random();
int number = randomNumber.nextInt(100);
guess = guessScanner;
if (guess<myNumber) {
Could I please have some advice as of how to fix these? And how to make the program record then umber of guesses?

change
guess = guessScanner
to
guess = guessScanner.nextInt();
You are willing to take the user input as int. But guess = guessScanner from this you are assigning int to Scanner. That is wrong.
And also change as
Random randomNumber = new Random();

You are trying to assign Scanner to an int:
guess = guessScanner;
Instead, you should call the nextInt() method on it, to get the integer the user inputed:
guess = guessScanner.nextInt();

Related

Can someone help analyse my java code on an averaging program?

Hi so I've started learning java online for two weeks now, but as I watched those tutorials, I felt the only way I'd actually grasp that information was to practice it. My other programs worked great, but just when I decided to do something spectacular (for me only of course; a java expert would find creating this program mind-numbing), something went terribly wrong. I'd really appreciate if you could take a look at my code below of an averaging program that could average any amount of numbers you want, and tell me what in the world I did wrong.
UPDATE: Eclipse just outputs a random number after typing in just one number and then shuts down the program.
Here is a snapshot where I type in the console to average 6 numbers and then start with the number 7, but for some reason, when I hit enter again, it outputs 8.
package justpracticing;
import java.util.*;
public class average{
int grade = 0;
int average;
Scanner notoaverage = new Scanner(System.in);
System.out.println("Please enter the amount of numbers you'd like the average of! ");
final int totalaverage = notoaverage.nextInt();
Scanner averagingno = new Scanner(System.in);
System.out.println("Start typing in the " + totalaverage + " numbers");
int numbers = averagingno.nextInt();
int counter = 0;
public void averagingnumbers(){
while(counter<=totalaverage){
grade+=numbers;
++counter;
}
}
public void printStatement(){
average = grade/totalaverage;
System.out.println(average);
}
}
It seems that you have created an average Object in another class, and are calling the methods given from a main class.
I don't know what exactly you're having trouble with, but one problem is here:
average = grade/totalaverage;
These 2 variables that you are dividing are both integers. That means that the result will also be an integer. This is called truncation. What you want to do is first convert at least one of the integers to a double:
... = (grade * 1.0) / totalaverage;
You also want your average variable to be a double instead of an integer so that it can be a lot more accurate.

Taking random number as input in java from user

`
System.err.println("welcome to the game");
System.err.println("please throw your dice 10 times");
Scanner s=new Scanner(System.in);
Random r=new Random();
for(int i=0;i<10;i++)
{
System.err.println("try"+i);
int d= r.nextInt(6)+1;
System.err.println(r.nextInt(10)+1);
}
}
I have a question,I am developing a basic game dice rolling .I am a bit confused that how to take random number when user press enter key each time ,a new random number is generated ?here ,all the random no. is genereted at once.but I want it just like user inputs any integer no or double etc after pressing the enter key.
I'm going to assume you mean you want the user to press a button, and a new number is randomly generated.
First off, in Java, a random number is generated from the Random class.
You can import Random by saying, at the top of your code:
import java.util.*;
or, to be more precise:
import java.util.Random;
When you want to generate a random number in your main method, you must make a Random object, then create an instance of Random, since Java is an Object-Oriented Language. In other words, like this:
public static void main(String[] args) {
Random r = new Random();
int rantInt = r.nextInt(7); //random integer between 0 and 6
}
You could use the Scanner class to get user input; however, at your level, I would suggest simply rerunning the program to get a new random dice roll.
Also, on StackOverflow, as well as any other Stack Exchange website (or any forum, to be honest), you should be clear about your question. At the very least, write in complete sentences and with proper grammar. If possible, provide some of your source code, as well as your environment/experience.

Writing a loop that will repeat itself "N" times as decided by the user

I need to write a program for Java that "rolls" two 6-sided die and that keeps track of how many tries it took to roll a 7. The program also needs to run this process N number of times, determined by the user. After the Nth trial, the program needs to compute the average amount of trials it takes to roll a 7.
I'm pretty confident that I should use a while loop inside of a for loop but I'm unsure of exactly how to do it. I already have written the code to a program that "rolls the dice," and is shown below.
import java.util.*;
public class RollDice {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
Random rand = new Random();
String input = "";
do {
System.out.println("Rolling the dice...");
System.out.println("You rolled a"+((rand.nextInt(6)+1)+(rand.nextInt(6)+1)));
System.out.println("Roll again? (y/n)");
input = keyboard.next();
} while (input.equalsIgnoreCase("y"));
}
}
Yes, I know it's a do-while loop, but it's all I have so far.
https://codereview.stackexchange.com/questions/31980/a-simple-dice-roll-game
This would be a great place for you to start. Then just add a second die, and a variable for the average. But please do not copy this code directly. Use it as a template/guideline. I want no part in plagiarism.

In Cannot be resolved and MasterMind

Ok, I am having a problem receiving a value... I have been researching for several days, but nothing has hit the topic I need. It is a mastermind game. I am creating this for a Final project in my High School programming class. The Eclipse Compiler is telling me that in cannot be resolved. How do I fix this and Accomplish my goal. This is not being run in an applet.
package masterMind;
import java.util.Scanner;
public class MasterMind {
public static void main(String[] args) {
System.out.println("This is MasterMind, a logic game");
System.out.println("To win you must guess correctly where each number is");
System.out.println("You will be told if you get one correct");
System.out.println("You will only get 10 tries, then you lose");
System.out.println("Lets begin");
//Change this value to change the game
int m1=2;
int m2 =3;
int m3=2;
int m4=1;
//Create Board
System.out.println("__ __ __ __");
Scanner UserGuess = new Scanner(System.in);
int num = in.nextInt();
I have very limited Coding knowledge, so please keep it simple and explain
System.in is the InputStream of the system (like the cmd for windows) , in order to read from that you use the Scanner or InputStreamReader just like you are trying to do ... so instead of
in.nextInt();
you need
userGuess.nextInt();
and btw learn to use capital letters properly as it will help you later , like userGuess should not start with a capital since its an instance not a class.
anyways , for your game you have to guess 10 times which means you have to repeat the same guessing action 10 times or till the user guesses all the numbers , thats when you should use a while loop like so ....
boolean guessedAll = false;
int guessedCount=0;
int tryCounter=0;
while(tryCounter<9 || !guessedAll){
//read the number from the user and test it ...
//if number equals one of the numbers above then guessedCount++ ...
//if guessedCount==4 then guessedAll=true
tryCounter++;
}
now i almost gave you all of the algorithm needed to do that homework , but i ain't going to solve it for you till you try , else you will learn nothing ;)
you could ofcourse ask for help as comment after you've tried some ... good luck
for nextInt method you should call it from Scanner object
Change this
int num = in.nextInt();
To
int num = UserGuess.nextInt();
You never closed the brackets when you started the class nor when you started the main method. Match every { with a }.
package masterMind;
import java.util.Scanner;
public class MasterMind {
public static void main(String[] args) {
System.out.println("This is MasterMind, a logic game");
System.out.println("To win you must guess correctly where each number is");
System.out.println("You will be told if you get one correct");
System.out.println("You will only get 10 tries, then you lose");
System.out.println("Lets begin");
//Change this value to change the game
int m1=2;
int m2 =3;
int m3=2;
int m4=1;
//Create Board By randomly generating the number
//After generating the code, print the blank board to start the game
System.out.println("__ __ __ __");
//Take in the user's guess (limit is 10)
int limit = 10
for(int i = 0; i < limit; ++i) {
Scanner UserGuess = new Scanner(System.in);
int num = in.nextInt();
//Other logic..Leaving it for you to attempt
}
}
You want to make a program which the user must guess where each number is in a 4 digit code.. Well how do you do this?
We need the user to be able to input a number, typically the rules of this game are:
There are 6 possible numbers or colors
The code is 4 numbers or colors long
The user has ten tries to guess the code correctly
That means we have to start by doing something like this.
Generate the 4-digit code somehow (with the possible combinations from 0000-6666) and the split the random number put it in an array
Ask the user to enter a number guess along with a position for that number
Keep checking the user guess against the code, each time display the current guesses and which ones they have correct

random number generator is generating huge negative numbers

So I am creating a random code that's not necessarily pertinent to anything at this level, but I'm more testing a few ideas. So for some reason my code will work randomly, but for most of the time it's throwing out a random negative number usually in the vicinity of -413796084. I don't know why it's doing this and I am trying to keep the numbers in the vicinity of 0 - 50. I thought I had done it right but obviously I haven't. Also I am relatively new at Java, if that helps explain any mistakes I made.
import java.util.Scanner;
import java.util.Random;
class damagecalc {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
Random randamage = new Random();
int totaldmg;
System.out.println("Will you (a) attack, (s) defend, (d) skip your turn, (f) magic, (i) use an item?");
String dmgString = input.next();
char dmgChar = dmgString.charAt(0);
if(dmgChar == 'a'){
for(int finaldmg=50;finaldmg<=50;finaldmg++){
totaldmg = randamage.nextInt(10);
}
totaldmg = randamage.nextInt();
if(totaldmg >= 50){
System.out.println("You have defeated the monster!");
}else{
System.out.println("Damage Dealt:" + totaldmg);
}
}
}
}
EDIT------------------------------------------------
So I changed my code and fixed some things and now it's just spitting out 0 every time. Maybe now it will be a little easier to figure out. But I definitely need help.
This is the new code:
import java.util.Scanner;
import java.util.Random;
class damagecalc {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
Random randamage = new Random();
int totaldmg;
System.out.println("Will you (a) attack, (s) defend, (d) skip your turn, (f) magic, (i) use an item?");
String dmgString = input.next();
char dmgChar = dmgString.charAt(0);
if(dmgChar == 'a'){
for(int finaldmg=1;finaldmg<=50;finaldmg++){
}
totaldmg = randamage.nextInt(1);
if(totaldmg >= 50){
System.out.println("You have defeated the monster!");
}else{
System.out.println("Damage Dealt:" + totaldmg);
}
}
}
}
totaldmg = randamage.nextInt();
Random.nextInt() can return any legal value for an int, including the massive negative ones, which isn't likely to be the result you want here. Give nextInt some integer as an argument to constrain it to the desired range.
also, I'd take a look at this loop because chances are that it doesn't do what you think it does.
for(int finaldmg=50;finaldmg<=50;finaldmg++){
totaldmg = randamage.nextInt(10);
}
The body of the loop executes only once and totaldmg is overwritten right after the loop anyway.
EDIT: if you want just to generate a number between 0 and 50, you can just replace this:
for(int finaldmg=50;finaldmg<=50;finaldmg++){
totaldmg = randamage.nextInt(10);
}
totaldmg = randamage.nextInt();
with this:
totaldmg = randamage.nextInt(51);
In case you're wondering about that 51, that is the excluded upper bound - meaning that you'll get damage amounts that are at least zero and at most 50.
Sorry my first answer was c#, changed.
What you want is
totaldmg = randamage.nextInt(50);
use 51 if you want it to generate between 0 and 50 since it is exclusive.
Or if you're going for 50+random damage between 0 and 10, use this:
totaldmg = 50 + randamage.nextInt(10);
The other answer pointed out that weird for loop and I really don't know what you're going for anymore
Lol based on your discussion below the other answer, and assuming you don't find the real answer to your problem, if the negative numbers are between 0 and -50 then just use
totaldmg = Math.abs(randamage.NextInt(50));
and if the numbers are still negative and HUGELY negative:
totaldmg = Math.abs(randomage.NextInt(50)) % 50;
Awful, awful fix, but if it's honestly a bug or something this would be about as good in theory
So I figured it out. One I'm an idiot for having my totaldmg = randamage.nextInt(); twice, but when I took out one of them I was only getting 0's. So when I changed it to totaldmg = randamage.nextInt(50) it worked perfectly. Sweet. Thanks everyone for working with me. You all are fantastic individuals.

Categories