I want to make a random number guessing game but I keep getting thrown this error:
"java: cannot find symbol
symbol: variable randNum
location:
class Main".
How can I resolve this?
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main (String[] args) {
makeRandNum();
readInput();
checkInput();
}
public static void makeRandNum() {
// creating number generator
Random randNumGen = new Random();
// generates the number
int randNum = randNumGen.nextInt(11);
System.out.println(randNum);
}
public static void readInput() {
//creates a new instance of the util scanner class
Scanner userInput = new Scanner(System.in);
// reads user input (int)
int guessedNum = userInput.nextInt();
}
public static void checkInput(){
if (guessedNum.equals(randNum)) {
System.out.println("Correct");
} else {
System.out.println("Incorrect");
}
}
}
You are using randNum and guessedNum in checkInput() function but the variables are declared in makeRandNum() and readInput() function. To make the values accessible, make the return type of makeRandNum() and readInput() as int and then pass the returned value to the checkInput function as parameter.
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int randNum = makeRandNum();
int guessedNum = readInput();
checkInput(randNum, guessedNum);
}
public static int makeRandNum() {
// creating number generator
Random randNumGen = new Random();
// generates the number
int randNum = randNumGen.nextInt(11);
System.out.println(randNum);
return randNum;
}
public static int readInput() {
// creates a new instance of the util scanner class
Scanner userInput = new Scanner(System.in);
// reads user input (int)
int guessedNum = userInput.nextInt();
return guessedNum;
}
public static void checkInput(int randNum, int guessedNum) {
if (guessedNum == randNum) {
System.out.println("Correct");
} else {
System.out.println("Incorrect");
}
}
}
and the output is as follows :
5
15
Incorrect
Related
I wanted to create a simple program for user to insert 3 strings to a private string array in a class and then print it back by creating a new object using object reference but I think I am facing problem in the setter/getter.(Pretty new to class and setter/getter) Here is what I have so far:
import java.util.Scanner;
public class Stringtest {
public static void main(String[] args)
{ Scanner input=new Scanner(System.in);
Stringer Strung=new Stringer();
System.out.println("Strings:"+Strung.print());
}
}
class Stringer
{ Scanner input=new Scanner(System.in);
private String[] aa=new String[3];
aa[0]="zero";
aa[1]="one";
aa[2]="two";
Stringer()
{}
{ System.out.println("Please enter 3 strings:");
for(int i=0;i<4;i++)
{
aa[i]=input.next();
}
}
public void setaa(String[] a)
{
aa=a;
}
public String[] getaa()
{
return aa;
}
public void print(String[] a)
{
for(int b=0;b<4;b++)
{
System.out.printf("%s",a[b]);
}
}
}
Due to populating the array while creating a class instance, you don't require any setters. The only getter requires.
Divide the logic from the runner.
Always use array.length() while looping or use a simple for loop otherwise you'll be getting an indexOfBoudException error.
Didn't get why you are using printf() while printing results.
My solution:
import java.util.Scanner;
public class App {
public static void main(String[] args) {
App.run();
}
private static void run() {
Stringer stringer = new Stringer();
stringer.print(stringer.getStrings());
}
}
class Stringer {
private String[] strings = new String[3];
Stringer() {
System.out.println("Please enter 3 strings:");
for (int i = 0; i < 4; i++) {
Scanner scanner = new Scanner(System.in);
strings[i] = scanner.next();
}
}
String[] getStrings() {
return strings;
}
void print(String[] strings) {
System.out.println("Strings are:");
for (String string : strings) {
System.out.println(string);
}
}
}
I need to know how to fetch the input for the operator for this simple program I am making that does this; the person enters a number, and if it's greater than 10, it displays the message "it worked". Where it says "NEED INPUT" is where I need the system scanner entry to go.
Operators class:
class Classes {
private int Numbers;
public Classes() {}
Classes(String namez) {
Numbers = Numbers;
}
public int getNumbers() {
return Numbers;
}
public void setNumbers(int numberz) {
if((Integer.parseInt(INPUT HERE.getText().toString()) )<=10) {
System.out.print("It worked.");
}
}
}
Main class:
import java.util.Scanner;
public class OneTwoThree {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a number: ");
Classes.Numbers(keyboard.nextLine());
}
}
package mavens.dais.test;
public class ClassesTest {
private int Numbers;
public ClassesTest() {}
ClassesTest(String namez) {
Numbers = Integer.parseInt(namez);
}
public int getNumbers() {
return Numbers;
}
public void setNumbers(int numberz) {
if(numberz > 10){
System.out.print("It is worked.");
}else{
System.out.print("It is not worked.");
}
}
}
package mavens.dais.test;
import java.util.Scanner;
public class OneTwoThre {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a number: ");
new ClassesTest().setNumbers(Integer.parseInt(keyboard.nextLine()));
}
}
Firstly
Classes.Numbers(keyboard.nextLine());
this should be replaced by Classes(keyboard.nextLine()); to begin with, in your class named OneTwoThree
Secondly
Classes(String namez) {
Numbers = Numbers;
}
this seems pretty much wrong.
Should be replaced by something like
Classes(String namez) {
Numbers = Integer.parseInt(namez); //if you are entering integers only through keyboard
}
As far as I could understand your question,
you can go like this then,
Classes(String namez) {
Numbers = Integer.parseInt(namez); //if you are entering integers only through keyboard
performOperation(Numbers);// call a method you want,pass number as arg
}
public static void performOperation(int num){
if(Numbers >10){
//do stuff
}
else{
//else part
}
}
}
Also ,just as a good practice you should name your variable Numbers to number.
I Hope it helped.
You just need to pass the String.
public static void testScanner() {
try (Scanner keyboard = new Scanner(System.in);) {
System.out.print("Enter a number: ");
while (true) {
String input = keyboard.nextLine();
if (input.equalsIgnoreCase("exit")) {
break;
}
Handler.handleInput(input);
}
System.out.println("Done.");
}
}
static class Handler {
public Handler() {
}
public static void handleInput(String input) {
try {
int x = Integer.parseInt(input);
if (x <= 10) {
System.out.println("It worked!");
} else {
System.out.println("Aw, Id didn't work.");
}
} catch (Exception ex) {
System.out.println("Hey, watch it buddy. Don't throw any letters in there, I don't like them.");
}
}
}
I am creating an object of a class from 2 separate classes and both objects are returning different values for the same method. I suspect it may be an issue with the while loop but here are the classes. The main class works, the setup class is the class that is being turned into and object and the game loop class has the object that doesn't return the right values. it returns the values defined at the beginning of setup and not the modified versions.
import java.util.Scanner;
public class MainClass {
static Scanner input = new Scanner(System.in);
//String x = input.nextLine();
public static void main(String[] args)
{
setup setupGov = new setup();
gameLoop gameLoop = new gameLoop();
setupGov.statsSetup();
System.out.println("happyness: " + setupGov.getHappyness() + " money: £" + setupGov.getMoney() + " population: " + setupGov.getPopulation());
gameLoop.loop();
}
}
import java.util.Scanner;
public class setup {
static Scanner input = new Scanner(System.in);
String goverment;
int happyness;
double money;
int population = 1000000;
public setup()
{
}
public void statsSetup()
{
System.out.println("Choose a goverment: 1. democracy 2. monarchy 3. dictatorship");
goverment = input.nextLine();
if (goverment.equals("1"))
{
happyness = 75;
money = 250000.0;
}
else if (goverment.equals("2"))
{
happyness = 50;
money = 500000.0;
}
else if (goverment.equals("3"))
{
happyness = 25;
money = 750000.0;
}
else
{
System.out.println("ENTER A VALID VALUE");
}
}
public int getHappyness()
{
return happyness;
}
public double getMoney()
{
return money;
}
public int getPopulation()
{
return population;
}
}
import java.util.Scanner;
public class gameLoop
{
static Scanner input = new Scanner(System.in);
static int turn = 0;
int happyness;
double money;
int population;
public gameLoop()
{
}
setup setupGov = new setup();
public static void main(String[] args)
{
}
public void loop()
{
while (true)
{
System.out.println("Turn: "+turn);
input.nextLine();
turn++;
}
}
}
You are creating two different instances of class setup. One is created directly in main function and other is created in gameLoop object. They do not share their attributes so methods may return different value. Every time you use 'new' operator, a new instance of class is created with it's own attributes (only static member are shared since static member belongs to class instead of instances). If you want to have same instances you could write:
public class gameLoop
{
static Scanner input = new Scanner(System.in);
static int turn = 0;
int happyness;
double money;
int population;
public gameLoop(setup setupGov)
{
this.setupGov = setupGov;
}
setup setupGov;
public static void main(String[] args)
{
}
public void loop()
{
while (true)
{
System.out.println("Turn: "+turn);
input.nextLine();
turn++;
}
}
}
And in main:
public class MainClass {
static Scanner input = new Scanner(System.in);
//String x = input.nextLine();
public static void main(String[] args)
{
setup setupGov = new setup();
gameLoop gameLoop = new gameLoop(setupGov);
setupGov.statsSetup();
System.out.println("happyness: " + setupGov.getHappyness() + " money: £" + setupGov.getMoney() + " population: " + setupGov.getPopulation());
gameLoop.loop();
}
}
Now both of objects setupGov will be the same instance.
Please note:
It is good practice to have class name written with capitalized first letter eg. GameLoop instead of gameLoop
I don't really understand what you're trying to do or what the question is, but in your main class you have an object with the same exact name of the class.
gameLoop gameLoop = new gameLoop();
I don't know if that's the exact cause of your problem, but I'm almost sure that that isn't supposed to be like that.
Hello So I have a entire class called tractor with different data's stored in it but now I'm suppose to create an object call tractor with a zero parameter constructor but This is the code I have so far and its giving em errors
First off this my Tractor Class which is in a different file:
import java.util.Scanner;
class Tractor
{
private int RentalRate;
private int RentalDays;
private int VehicleID;
private int RentalProfit;
public void setRentalRate(int r)
{
Scanner input = new Scanner(System.in);
System.out.println("What's the Rental Rate?");
int num = input.nextInt();
num = r;
if(r<0 || r >1000)
RentalRate = r;
RentalRate= 1;
}
public int getRentalRate()
{
return RentalRate;
}
public void setVehicleID(int v)
{
Scanner input = new Scanner(System.in);
System.out.println("What's the vehicleID?");
int num1 = input.nextInt();
num1 = v;
if(v<0)
VehicleID = v;
VehicleID = 1;
}
public int getVehicleID()
{
return VehicleID;
}
public void setRentalDays(int d)
{
Scanner input = new Scanner(System.in);
System.out.println("How many rental days?");
int num2 = input.nextInt();
num2 = d;
if(d<0)
RentalDays = d;
RentalDays = 1;
}
public int getRentalDays()
{
return RentalDays;
}
public String toString()
{
String str;
str = "RentalDays:" + RentalDays +"\nRenalRate:" + RentalRate + "\nVehicleID " + VehicleID;
return str;
}
public void RentalProfit(int RentalRate, int RentalDays)
{
RentalProfit = RentalRate * RentalDays;
}
}
import java.util.Scanner;
public class testTractor
{
public static void main(String[] args)
{
public tractor()
{
this.RentalDays = d;
this.RentalRate = r;
this.VehicleID = v;
}
}
}
The error is :
testTractor.java:7: error: illegal start of expression
public tractor()
^
testTractor.java:7: error: ';' expected
public tractor()
^
2 errors
You have compilation errors. You need to first declare the Tractor class then add the constructor inside it. One way to do is declare in a separate file. Also in Java unless you had defined d you couldnt have assigned it. Maybe you wanted to assign the day as a String look in the examples I provide below.
You need to to first create a file call Tractor.java and then define variables there. For example contents of Tractor.java:
public class Tractor {
String rentaldays,someOtherValue;
public Tractor(){
rentaldays ="monday";
someOtherValue="value";
}
//or
public Tractor(String rentalDays){
this.rentaldays = rentalDays;
someOtherValue = "asf";
}
}
Then in your main method You can do Tractor trac = new Tractor(); or Tractor trac = new Tractor("tuesday"); also after that you can print the rentaldays of trac using System.out.println(trac.rentaldays);
From the looks of it you will probably be making a tractor rental system. In that case, rentalDays may be an array of Strings. And then you would have an array of Tractor objects to store in the rental system. You can look at these terms and keywords to point you in the right direction.
You are defining it wrong, define your methods inside class then call them in main() method.
class Test{
public void greeting(){
System.out.print("hello to JAVA..");
}
public static void main(String[] args){
Test testObj = new Test();
testObj.greeting();
}
}
you use an illegal of java syntax, if you already have class tractor in your project. for calling it to in other class, try below code
public class TestTractor(){
Tractor objTractor;
public static void main(String[] args){
//create new tractor object with no parameter
objTractor = new Tractor();
//create new tractor object with parameter
objTractor = new Tractor(parameter here);
//do some action of object here
...........
}
}
//This is just a sample
in your tractor class add below code
public tractor()
{
this.RentalDays = d;
this.RentalRate = r;
this.VehicleID = v;
}
And keep your TestTractor class as
public class TestTractor(){
public static void main(String[] args){
Tractor objTractor = new Tractor();
// objTractor.yourMethodName
}
}
What is identifier expected error?
import java.util.Scanner;
class MyClass {
public static void fizzBuzz(Integer)
{
int x=0,n;
System.out.println("give any number");
Scanner Scan = new Scanner(System.in);
int n = Scan.nextInt();
for(x=0;n<x;x++)
{
if(x==3)
{
System.out.println("fizz");
x=x+1;
}
else if(x==5)
{
System.out.println("buzz");
x=x+1;
}
else
{
System.out.println("x");
x=x+1;
}
}
}
}
error
user_file.java:5: error: <identifier> expected
public static void fizzBuzz(Integer)
^
Two changes
1.) You should have if not done already public static void main(String[] args) { // call your method here}
2.) n is declared twice.
3.) public static void fizzBuzz(Integer) is wrong, variable name is missing.
change to public static void fizzBuzz(Integer a)
int x=0,n; and int n = Scan.nextInt();
Here public static void fizzBuzz(Integer)
You have given only Type Integer not the variable which will hold Integer type value.
public static void fizzBuzz(Integer)
app a variable like code below
public static void fizzBuzz(Integer z)
You have declared n tow time int x=0,n; and at int n = Scan.nextInt();
remove int from second declation.