Duplicate local variable - java

I recently started programming with java and need help.
Using Programming Java for Dummies, I'm trying to make a game where a user has to guess a number. The amount of attempts are recorded and displayed once the user finally gets the answer right.
The starred line is giving me trouble, any help?
import static java.lang.System.out;
import java.util.Scanner;
import java.util.Random;
import javax.swing.JOptionPane;
public class HelloWorld
{
public static void main(String args[])
{
Scanner keyboard = new Scanner (System.in);
out.println("Hello, welcome to the Guessing Game.");
out.println("To begin, pick a random number from 1 - 10: ");
int inputNumber = keyboard.nextInt();
int randomNumber = new Random(1).nextInt(10);
int numGuesses = 0;
while (inputNumber != randomNumber){
out.println();
out.println("You're guess was wrong, try again.");
out.println("Pick an integer from 1-10.");
**int inputNumber = keyboard.nextInt();**
numGuesses++;
}
{
out.println("You won in " + numGuesses + " guesses.");
out.println("Thanks for playing!");
}
}
}

Replace
**int inputNumber = keyboard.nextInt();**
with
inputNumber = keyboard.nextInt();
With the original version, you are creating a new variable within the scope of the while, rather than assign to the old variable outside.
Since it is destroyed after the while block, the condition itself uses the variable in functions scope.

This line is redeclaring inputNumber, which has already been declared.
int inputNumber = keyboard.nextInt();
change it to
inputNumber = keyboard.nextInt();

You already defined at the top so you dont have to redefine it. Instead it should be inputNumber = keyboard.nextInt();

Related

What's the problem in this while statement?

so I'm a beginner I just started like 3 days ago and I'm trying to make a While statement in java and I can't seem to find a way to make a loop without not having a user input again in the while block, My idea in this code is to ask the user for the wanted operation and if it's empty or non of the operations available, the program will give him an error message then loop the program
import java.util.*;
public class calc{
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("1.Sum\n2.Subtraction\n3.Multiplication\n4.Division");
int oper = sc.nextInt();
while (oper > 4 || oper < 1) {
System.out.println("Please enter a valid number");
System.out.println("1.Sum\n2.Subtraction\n3.Multiplication\n4.Division");
int oper = sc.nextInt();
}
}
}
The only thing really wrong is the second int oper = sc.nextInt();. You've already got a variable oper in scope, you can't declare another.
Remove the int.
You might instead want to consider restructuring the loop, so you don't have to repeat the messages and the reading from the scanner:
int oper;
while (true) {
System.out.println("1.Sum\n2.Subtraction\n3.Multiplication\n4.Division");
oper = sc.nextInt();
if (oper >= 1 && oper <= 4) {
break;
}
System.out.println("Please enter a valid number");
}

Second scanner in my program wont put the input value into my integer?

I am going to post my code right away and ask the question below it.
System.out.println("Enter your starting integer: ");
firstInt = scnr.nextInt();
System.out.println("Enter your last integer: ");
secondInt = scnr.nextInt();
int i = firstInt;
while (i < secondInt) {
The first input is taken just fine. But when I try to input to secondInt, I hit enter and it wont move onto my while loop it is just stuck in the scanner. I hit enter and i just move down a line to input more. I watn it to move to my while loop. This is probably an easy fix but im pretty new to coding so any help would be appreciated. Thanks in advance!
import java.util.Scanner;
public class Tyler
{
public static void main(String[] args)
{
Scanner stdin = new Scanner(System.in);
// input first int
System.out.print("Enter your starting integer: ");
int firstInt = stdin.nextInt();
//input second int
// consume line
stdin.nextLine();
System.out.print("Enter your last integer: ");
int secondInt = stdin.nextInt();
// output data
// There was no way to break out of your while loop so this should be done with an If/else
if (firstInt <= secondInt)
{
System.out.println("First number is less then second number");
}
else
{
System.out.println("Second number is less then first number");
}
}
}

I'm supposed to be writing a program but no matter what i try to fix it, like delete something and then

it tells me it needs it, It wont fix. where exactly am i going wrong?
What I have so far is this:
public class DistanceTraveled {
public static void main(String[] args) {
int speed = 0,
hours = 0;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the speed: ");
speed = keyboard.nextInt();
while(speed < 0){
System.out.print("Enter the speed: ");
speed = keyboard.nextInt();
}
System.out.print("Enter the amount of hours traveled: ");
hours = keyboard.nextInt();
while(hours < 1){
System.out.print("Enter the amount of hours traveled (MPH): ");
hours = keyboard.nextInt();
}
System.out.println("Hours" + " Distance Traveled");
System.out.println("------------------------------------");
int hr = 1;
while(hours >= 1){
System.out.println(" " + hr + " " + hr * speed + " MPH");
hr++;
hours--;
}
}
}
This is the error I keep getting:
symbol : class Scanner
location: class DistanceTraveled
Scanner keyboard = new Scanner(System.in);
^
DistanceTraveled.java:8: cannot find symbol
symbol : class Scanner
location: class DistanceTraveled
Scanner keyboard = new Scanner(System.in);
^
You forgot to import Scanner. Put this at the top of your file:
import java.util.Scanner;
More generally, you shouldn't just "delete something" and hope for the best. That's called shotgun debugging, and it will only lead to worse headaches. Instead, take the time to google the error and understand what's going on.
I tried your code, the only compiler error seem to be missing an import
import java.util.Scanner;
Or, you can use the full name in your code and then you don't need the import -
java.util.Scanner keyboard = new java.util.Scanner(System.in);

Beginner Java program, loops

I am trying to create a simple program which creates a random number and asks the user to guess. It will then say higher or lower until the user guesses correct. The problem is, after the user guesses correctly the program will keep looping. I thought that putting the code into a separate method and then calling it in a while loop would work but unfortunately it was no avail. Could anyone suggest how I would correct this?
Below is my code.
package main;
public class NumberGuesser {
public static void main(String[] args) {
code mycode = new code();
while (mycode.guess != mycode.random){
mycode.codebit();
}
}
}
package main;
import java.util.Random;
import java.util.Scanner;
public class code {
Random rand = new Random();
int random = rand.nextInt(1000);
double guess;
public void codebit(){
System.out.println("Guess the number");
Scanner input = new Scanner(System.in);
Double guess = input.nextDouble();
if (guess > random){
System.out.println("Lower");
}
else if (guess < random){
System.out.println("Higher");
}
else if (guess == random){
System.out.println("Well done");
}
}
}
You are re-declaring guess within your method body, which hides your instance member.
Try removing:
Double guess = input.nextDouble();
... and replacing with:
guess = input.nextDouble();
Also non-related to your issue:
As general coding guidelines go, class names should be CamelCase
You don't need to instantiate a Scanner each time. If you experiment with your code structure, you'll be able to have more efficient usage. Just a hint, try looking for the hasNext[...] methods of Scanner.
Double guess = input.nextDouble();
You're initializing a local variable which has the same name as the field here. The field, that is checked by the main class, is never modified. Also, why do you use a double and not an int for the guess?
I think you do not have to go into a separate method here. Just put the code you have in your code class into your main method into an infinite loop. This way, you will be able to stop the program by returning when the guess is correct:
else if (guess == random) {
System.out.println("Well done");
return;
}
your global value guess never be assigned with a value except it first assign a value (that is 0) from system as global variable.
This is caused as you declared a local variable and assigning the local variable every time instead global variable as default java properties.
Removing the declaration of local variable guess can be a solution of that problem. You can solved it other ways to like assign global with local using this.guess = guess.
I'm also pretty new to Java but I would keep it simple and do it like this:
package main;
import java.util.Random;
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
Random rand = new Random();
Scanner input = new Scanner(System.in);
int guess;
int randomNum;
String answer = "";
System.out.println("~ WELCOME! ~");
System.out.println("Can you guess the secret number?");
do {
System.out.print("\nPicking a number between 1-1000........ ");
randomNum = rand.nextInt(1000)+1; //number will be between 1-1000
System.out.println("Done!");
System.out.print("\nGuess the number: ");
guess = input.nextInt();
while(guess<1 || guess>1000) {
System.out.println("\nOut of range! Try again.");
System.out.print("Your guess: ");
guess = input.nextInt();
}
if(guess==randomNum)
System.out.print("You were right!");
else
System.out.println("\nWrong! Better luck next time.");
System.out.println("\nThe secret number was " + randomNum + ".");
System.out.println("Your guess was " + guess + ".");
System.out.print("\nPlay again (yes/no)? ");
answer = input.next();
if(answer.equalsIgnoreCase("no")) {
System.out.print("\nThanks for playing!");
input.close();
System.exit(0);
}
}while(answer.equalsIgnoreCase("yes"));
}
}
I don't think it's really necessary to create another class. Try it out and see what you think!

Java output error

I can't get this to work properly. It functions as it is supposed to, and does the math, but then it loops once, and ends. I need it to either loop until the users decides to end it, or only run once.
import java.util.Scanner;
public class java {
public static void main(String args[]) {
System.out.println("Welcome to the simple Calculator program");
System.out.println("Please type what type of math you would like to do: ");
System.out.println("1=Addition");
System.out.println("2=Subtraction");
System.out.println("3=Multiplication");
System.out.println("4=Division");
System.out.println("5=Sqrt");
Scanner input = new Scanner(System.in);
int math = input.nextInt();
if (math == 1) {
Scanner a = new Scanner(System.in);
int a1;
int a2;
int asum;
System.out.print("Please enter the first number: ");
a1 = a.nextInt();
System.out.print("Please enter the second number: ");
a2 = a.nextInt();
asum = a2 + a1;
System.out.print("The sum is: " + asum + "Thank You for using this program");
}
Scanner number = new Scanner(System.in);
int number1;
int number2;
int sum;
System.out.print("Enter first number: ");
number1 = number.nextInt();
System.out.print("Enter Second number: ");
number2 = number.nextInt();
sum = number1 + number2;
System.out.printf("Sum is %d\n", sum);
}
}
Use
do{
// do something.
} while(some condition);
And reapeat the same scanner to get input. You can also add one more option to your menu for repeating and evaluate that with while condition.
It is working as it should.
If you want it to loop as per some user input,you must use any looping construct like while.
Instead of if (math == 1) use
`while (math != exit)`
Make a new entry for exit like 0
Try using while loop. Give the user an option to quit the program.
import java.util.Scanner;
public class java
{
public static void main(String args[])
{
Scanner a = new Scanner(System.in);
System.out.println("Welcome to the simple Calculator program");
while(true)
{
System.out.println("Please type what type of math you would like to do: ");
System.out.println("1=Addition");
System.out.println("2=Subtraction");
System.out.println("3=Multiplication");
System.out.println("4=Division");
System.out.println("5=Sqrt");
System.out.println("6=Quit"); // added an option to quit the program
int math = a.nextInt();
if (math == 1)
{
int a1,a2,asum;
System.out.print("Please enter the first number: ");
a1 = a.nextInt();
System.out.print("Please enter the second number: ");
a2 = a.nextInt();
asum = a2 + a1;
System.out.println("The sum is: " + asum + "Thank You for using this program");
}
// Include actions for math = 2 to 5
if(math == 6)
{
System.out.println("Thank You for using this program");
System.exit(0);
}
}
}
}
The options are displayed again and again after each calculation until the user wants to exit the program by entering 6.
If you want the program to run only once, you should leave out the outer while loop. Everything else remains the same.
PS - You don't need to reopen Scanner again and again (at least not in this problem).
That is because you are only reading the input from the console once..you need to keep the console up with something like while(true) {} or monitor the console for an exit conditon like (" 0 = exit ") .
Also, I don''t think you will need to read two numbers again and again like you are doing right now.
1) You can use a do-while loop with a condition till which you wish to execute.
2) Use a switch case and perform the math operations inside the switch case with different operators. As of now you are trying to perform only addition. So you a switch case where you can perform all the operations.
3) In the switch case have an option which calls the exit(0) method. So that you can run the program until the user wish to exit.
4) By using a switch case you can make the user to choose his own option.
Your entire program is correct dude.
Just add
System.exit(0);
In every if(math==1) ,if(math==2)...before their statement ending.
like if(math==1)
{
...
System.exit(0);
}
You can fix your error...
Like me if your error is fixed. If not tell me the error

Categories

Resources