Cannot find symbol in function. [duplicate] - java

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 5 years ago.
I am trying to get some user input in a function but for some reason my code will not recognize my input streams. When I go to compile I get an error on line 81 saying reader.readLine() can not be found. Does anyone know how to fix this? Or is it possible to have the run function happen in the initial do-while loop without any issues?s
import java.io.*;
public class JavaLab3 {
public static void main(String[] args) {
// first we define our input streams.
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
// variable declarations
String sName, playAgain;
// we catch exceptions if some are thrown.
// an exception would be entering a string when a number is expected
try {
System.out.println("what is your name?");
// we read a string from the stream
sName = reader.readLine();
do {
run();
System.out.println(sName + "would you like to play again?");
System.out.println("Please answer in lowercase 'yes' or 'no'.");
playAgain = reader.readLine();
} while (playAgain != "no");
} catch (IOException e){
System.out.println("Error reading from user");
}
}
public static int maxRun (int runTotal) {
int highScore = 0;
if (runTotal > highScore) {
highScore = runTotal;
} else {
`highScore = highScore`}
return highScore;
}
public static int run () {
Integer currentRun = 0, uNumber, counter;
final Integer MAX = 4;
final Integer MAX_NUMBER = 100;
//While current total is less than the max
while (currentRun < MAX) {
System.out.println("Please enter a number.");
//store user number
uNumber = Integer.parseInt(reader.readLine()); //Line throwing the error.
//for each number under 5 repetitions
for (counter = 0; counter <= MAX_NUMBER ; counter++ ) {
if (uNumber < 0) {
System.out.println("Please enter a positive number.");
} else if ((uNumber % 2) != 0) {
System.out.println("Please enter an even number.");
} else {
//sets current total and restarts the loop
currentRun = uNumber + currentRun;
}
}
}
//Calls maxRun function to see if score the score is the highest.
maxRun(currentRun);
System.out.println("The max for this run was, " + currentRun + ".");
return currentRun;
}
}

reader is defined within the scope of the main() method. It doesn't exist in the scope of run().
You can define it as a member of the class, so both methods will have access to it. Or pass it as a parameter between the methods.

reader is defined inside the main method and its scope is inside that, to access that in run method, you can pass that in run() method so that it can be available there.

The BufferedInput reader definition should be declared outside of the main function i.e inside the class then It will be global and accessible by any method of the class.
Class name {
buffereInput reader = ....
.....
}

Related

I put my try catch in a do while loop, but the commands after the do-while loop continue running even though there is an exception caught

I'm building a small program that checks if the user input is a number. The program runs but when my catch block catches an exception, it somehow exited the nested do-while loop it is in.
Here's my program :
package TESTCLASS;
import java.util.Scanner;
public class Apples {
static int readValidInt(Scanner in, String prompt, int min, int max){
int validUserInput;
int userInput = 0; //have to initialize this variable since I will be using it in a block, setting it to 0 for now
int checker =1;
while(!in.hasNextInt()) { //Makes sure that user inputs an Integer, not String, double, etc
System.out.println("Sorry, only numbers in integer form is allowed. Please enter your choice as an integer between 1 and 4");
in.next();
}
do {
do {
try {
userInput = in.nextInt();
checker = 0;
}
catch (Exception e) {
System.out.println("Exception detectedddd");
in.nextLine(); // This line is to *clear the buffer* for Scanner
}
}while (checker ==1 );
if ( userInput >= min && userInput <= max) {
System.out.println("you have chosen board " + userInput );
validUserInput = userInput;
}
else {
System.out.println(prompt);
validUserInput = 0;
}
}while (validUserInput==0);
return validUserInput;
}
// Main function
public static void main (String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Choose a board style");
readValidInt(input, "Bruh that's not valid", 1, 4);
}
}
Here is my output(As you can see, when I put "five", two things get printed out - "Exception detectedddd" & "Bruh that's not valid", but the latter sentence is part of the if else statement, which should not have been reached since there is an exception :
Choose a board style
100
Bruh that's not valid
five
Exception detectedddd
Bruh that's not valid
six
Exception detectedddd
Bruh that's not valid
10
Bruh that's not valid
1
you have chosen board 1
After the first input (100) you set checker = 0;. Since the value is too large you print "Bruh that's not valid" and stay within the outer loop.
That means that you read another value (five) which leads to the exception. However, since checker is already 0 (from the first pass) the inner loop is not repeated.
You need to reset checker to 1 before each start of the inner loop:
do {
checker = 1;
do {
try {
userInput = in.nextInt();
checker = 0;
}
catch (Exception e) {
System.out.println("Exception detectedddd");
in.nextLine(); // This line is to *clear the buffer* for Scanner
}
} while (checker == 1);
//... remainder of the outer loop
} while (validUserInput == 0);

Java Do-While Try-Catch exception handling loop error and symbol: variable error

Fixed(new working code below). I am running into a little problem that I cannot figure out. The first do-while works as intended and will go through until it gets a valid input. However the Second loop will end whether I input a valid or invalid #. And then in the 3rd loop, I get 2 errors:
I am not sure why I am getting these errors when the variables have already been declared?
A little explanation on what I am trying to do:
I am supposed to get 3 inputs: years of experience (yearsexp), performance (performance) and a random int generated between 1-10(level). The program will ask the user for their experience if it is between 3-11 they are qualified. If not, it will tell them they are not qualified and ask to re-enter a value. Same thing with performance. If they enter a number less than or equal to 11 it will procede to generate the random int (level) at which point level will be used to asses their bonus.
import java.util.Scanner;
import java.util.Random;
class assignment {
public static void main( String args[]){
//
int bonus;
int x;
//
Random rand = new Random();
//
Scanner input = new Scanner(System.in); // scanner for name
System.out.println("Enter your name: "); // ask for name
String name = input.nextLine(); // assign name to variable
System.out.println( name ); // output name
//
Scanner input2 = new Scanner(System.in); // scanner for yearsexp
System.out.println(name + ", Enter the years of your experience: "); // ask for yearsexp
int yearsexp = 0 ;
int performance = 0;
do
{
yearsexp = input2.nextInt(); // assign yearsexp to variable
System.out.println( yearsexp); // out yearsexp
try
{
if (yearsexp >= 3 && yearsexp <24)// acceptable critera
{
System.out.println("You are qualified");// output
x=2; // x = 2 to close do while
}
else
{
throw new Exception ();
}
}
catch (Exception e1)
{
System.out.println("You have entered an invalid number! Try again..."); //output is unacceptable
x=1;
}
}
while (x==1); // keep do loop going if exception e
//
Scanner input3 = new Scanner(System.in); // scanner for performance
System.out.println(name + ", Enter the performance: "); // ask for performance
//
do
{
performance = input3.nextInt(); // assign performance to variable
System.out.println( performance ) ; // output performance
try
{
if (performance <= 11) // acceptable criteria
{
System.out.println("You are qualified"); //output
x=2; // x = 2 to close do while
}
else
{
throw new Exception ();
}
}
catch (Exception e2)
{
System.out.println("You have entered an invalid number! Try again..."); //output if criteria is unacceptable
x=1;
}
}
while (x==1); // keep doing while
//
int level = rand.nextInt(11); // fix to be between 1-10 to not include 0
System.out.println("Random Level: " + level); //output level
//
do
{
try
{
if (level >=5 && level <=8)//acceptable criteria
{
System.out.println("Expected Bonus: $5000.00"); //output
x = 2; // x = 2 to close while
}
else if (level <= 4) // else if criteria
{
bonus = 5000 * yearsexp * performance * level; // calculate bonus if level <=4
System.out.println(bonus); // output bonus
if (bonus < 15000)
{
System.out.println(bonus);
}
else if (bonus > 15000)
{
System.out.println("Your bonus is TBL");
{
x = 2; // x = 2 to close while
}
}
}
}
catch (Exception e3)
{
System.out.println("You do not get a bonus"); //output if criteria is unacceptable
x=1;
}
}
while (x==1);
}
}
The reason you're getting those compilation errors is because performance is only scoped to the try statement of your second do/while loop.
If you need 'knowledge' of the value of performance and yearsexp to propagate from the second do/while loop to the third, you need to declare the variables before both loops, such that they're scoped to be visible to both.
To go into a bit more detail,
if (foo()) {
int myValue = 1;
}
System.out.println(myValue);
doesn't work because the myValue variable is scoped to the if statement, meaning as far as the println statement is concerned, it doesn't exist. The same is also true for for, while, do/while and try/catch statements.
try {
String a = "hello";
} catch (Exception e) {
}
System.out.println(a);
Doesn't work either.

How to end a while loop [duplicate]

This question already has answers here:
Cant figure out how to exit the loop of my program
(3 answers)
Closed 6 years ago.
My program for class asks to run the program as long as the user doesn't enter the input of -99. When I run the program and enter a usable number that isn't -99, the console will run a continuous looping answer until I have to press end.
How can I change the program so for each input there will be one answer and the program restarts until user inputs -99?
import java.util.Scanner; //import scanner
import java.io.*; //import library
public class is_odd_or_even_number {//begin class
public static void main(String []args) {//begin main
Scanner input = new Scanner(System.in);
//use try/catch method to test for invalid input
try{
//promt user to input a value
System.out.print("Enter a positive integer value: ");
int number = input.nextInt();
//PART I NEED HELP WITH **************
while (number != -99){
//Start of if statement to test which to print and call of isEven method
if (isEven(number)) {
System.out.println("Your number is Even!");
}
else
System.out.println("Your number is Odd!");
}
}
//open catch method and print invalid
catch(Exception notNumber) {
System.out.println("Input not a number, try again.");
}
}
//begin testing for odd or even in new method
public static boolean isEven(int num){
return(num & 1) == 0;
}
}
Here, you don't let the user entry other thing that the first input before the loop.
The retrieval of the input from the user :
int number = input.nextInt();
should be in the loop.
Try that :
int number = 0;
//PART I NEED HELP WITH **************
while (number != -99){
number = input.nextInt();
//Start of if statement to test which to print and call of isEven method
if (isEven(number)) {
System.out.println("Your number is Even!");
}
else
System.out.println("Your number is Odd!");
}
}
You can do like this way ;)
System.out.print("Enter a positive integer value: ");
int number = input.nextInt();
//PART I NEED HELP WITH **************
while (number != -99){
System.out.print("Not good, please enter a new one : ");
number = input.nextInt();
}
//Start of if statement to test which to print and call of isEven method
if (isEven(number)) {
System.out.println("Your number is Even!");
}
else {
System.out.println("Your number is Odd!");
}
So it will ask until you're not writing -99 as you said, but if you're asking for "a positive int" normally nobofy would write -99 :p
End a while loop
You can use a boolean value shouldContinue to control whether the programs should continue to the next input.
if (number != -99) {
shouldContinue = true;
} else {
shouldContinue = false;
}
This can be simplified as follow:
shouldContinue = number != -99 ? true : false;
// or even shorter
shouldContinue = number != -99;
Read the value correctly
But you need to ensure that you input number is reset at each loop execution so that you can read the next number:
while (shouldContinue) {
...
number = input.nextInt();
}
Other enhancements
Do not import unused packages or classes
Use camel case for Java class name
Use comment style /** ... */ for Javadoc
Always try to avoid infinite loop, e.g. use an integer count tries and count down at each loop.
Here's the final answer look like:
import java.util.Scanner;
public class IsOddOrEvenNumber {
public static void main(String []args) {
Scanner input = new Scanner(System.in);
boolean shouldContinue = true;
int tries = 0;
while (shouldContinue && tries < 10) {
try {
System.out.print("Enter a positive integer value: ");
int number = input.nextInt();
if (isEven(number)) {
System.out.println("Your number is Even!");
} else {
System.out.println("Your number is Odd!");
}
shouldContinue = number != -99 ? true : false;
} catch (Exception notNumber) {
System.out.println("Input not a number, try again.");
}
tries--;
}
System.out.println("Game over.");
}
/**
* Begin testing for odd or even in new method
*/
public static boolean isEven(int num){
return (num & 1) == 0;
}
}
Here you are the main method which will be running as long as user is not entering -99;
You should include all your code in the while loop (even try/catch).
public static void main(String []args) {//begin main
Scanner input = new Scanner(System.in);
int number = 0;
//Keep application running as long as the input is not -99
while (number != -99){
//use try/catch method to test for invalid input
try{
//promt user to input a value
System.out.print("Enter a positive integer value: ");
number = input.nextInt();
//Start of if statement to test which to print and call of isEven method
//if the entered number is -99, the following code will skipped.
if(number == -99) continue;
if (isEven(number))
System.out.println("Your number is Even!");
else
System.out.println("Your number is Odd!");
}
//open catch method and print invalid
catch(Exception notNumber) {
System.out.println("Input not a number, try again.");
}
}
}
You could accept this answer, in case it is what you are looking for :)

Loops in Loops in Loops in Java

I need to build an array with 10 entries that the program prompts from the user, if the first entry is 9999, i need to program to quit. I also need to use try/catch for errors. Below is what I have but I can't get the variable 'number' to be recognized throughout when I input the try/catch loop... HELP!!!
public static void main(String[] args) {
int nextIndex = 1;
int[] numberFun;
numberFun = new int [10]; //creates the array with 10 entries
Scanner Keyboard = new Scanner (System.in);
int entry = 0;
//I'm trying to get the first entry to determine if it equals 9999 with this section
int firstNumber=0;
System.out.println ("Please enter a number");
firstNumber = Keyboard.nextInt();
numberFun[0] = firstNumber;
if (firstNumber != 9999)
{
while (entry < 9) //this loop is supposed to obtain the other 9 entries for the array from the user
{
int number;
System.out.println ("Please enter a number");
try // this is supposed to provide an error if the user enters something that is not a number
{
number = Keyboard.nextInt();
}
catch (Exception ex)
{
//display error message here
}
numberFun[nextIndex] = number;
++nextIndex;
++entry;
}
}
else
{
System.err.println("Command Accepted. Exiting Program.");
}
it works properly until I put the try/catch in.
Change,
int number;
to
int number = 0;
The variable that you are accessing later in the program needs to be initialized because Java will not compile if there's no guarantee that the variable you're using does not have a value to be worked with. Since you did not give number an initial value when you declared it, yet still use a try catch block to access it, Java won't know for sure whether number will have a value by the time it reaches the try catch block, which is why it's not currently working.
write firstNumber = Keyboard.nextInt(); in try catch block
and you need to initialize int number; before use

Why is my try and catch stuck in a loop?

I want the user to enter integers into an array. I have this loop I wrote which has a try and catch in it, in case a user inserts a non integer. There's a boolean variable which keeps the loop going if is true. This way the user will be prompted and prompted again.
Except, when I run it, it gets stuck in a loop where it repeats "Please enter # " and "An Integer is required" without letting the user input a new number. I reset that number if an exception is caught. I don't understand.
import java.util.*;
public class herp
{
//The main accesses the methods and uses them.
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Hello and welcome!\n");
System.out.print("This program stores values into an array"+" and prints them.\n");
System.out.println("Please enter how many numbers would like to store:\n");
int arraysize = scan.nextInt();
int[] mainarray = new int[arraysize+1];
int checkint = 0;
boolean notint = true;
int prompt = 1;
while (prompt < mainarray.length)
{
// Not into will turn true and keep the loop going if the user puts in a
// non integer. But why is it not asking the user to put it a new checkint?
while(notint)
{
try
{
notint = false;
System.out.println("Please enter #"+ prompt);
checkint = scan.nextInt();
}
catch(Exception ex)
{
System.out.println("An integer is required." +
"\n Input an integer please");
notint = true;
checkint = 1;
//See, here it returns true and checkint is reset.
}
}
mainarray[prompt] = checkint;
System.out.println("Number has been added\n");
prompt++;
notint = true;
}
}
}
Once the scanner has thrown an InputMismatchException it cannot continue to be used. If your input is not reliable, instead of using scanner.nextInt() use scanner.next() to obtain a String then convert the string to an int.
Replace:
checkint = scan.nextInt();
With:
String s = scan.next();
checkint = Integer.parseInt(s);
I have corrected it like below. I don't rely on exception, but check if the next Scanner input is int (using hasNextInt()). If not int, just consume Scanner token and wait for the next user input.
Looks like it is working, apart from 0 being inserted as a first array element, because you started indexing prompt from 1.
public class Herp {
//The main accesses the methods and uses them.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Hello and welcome!\n");
System.out.print("This program stores values into an array" + " and prints them.\n");
System.out.println("Please enter how many numbers would like to store:\n");
int arraysize = scan.nextInt();
int[] mainarray = new int[arraysize + 1];
int checkint = 0;
boolean notint = true;
int prompt = 1;
while (prompt < mainarray.length) {
while (notint) {
notint = false;
System.out.println("Please enter #" + prompt);
// check if int waits for us in Scanner
if (scan.hasNextInt()) {
checkint = scan.nextInt();
} else {
// if not, consume Scanner token
scan.next();
System.out.println("An integer is required."
+ "\n Input an integer please");
notint = true;
}
}
mainarray[prompt] = checkint;
System.out.println("Number has been added\n");
prompt++;
notint = true;
}
for (int i : mainarray) {
System.out.print(i + " ");
}
}
}

Categories