This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 5 years ago.
Building a survey application, and I am running into a roadblock with this problem. I am not understanding where my issue is exactly but when I am trying to create a two option menu, it is not allowing me to compile or run it.
errors:
Compiling 2 source files to C:\Users\martin.shaba\Documents\NetBeansProjects\Survey\build\classes
C:\Users\martin.shaba\Documents\NetBeansProjects\Survey\src\survey\Survey.java:71: error: cannot find symbol
System.out.print("Enter text for question " + (i+1) + ": ");
symbol: variable i
location: class Survey
C:\Users\martin.shaba\Documents\NetBeansProjects\Survey\src\survey\Survey.java:75: error: cannot find symbol
questions[i] = new IntegerQuestion(input.nextLine(),maxResponses);
symbol: variable i
location: class Survey
2 errors
C:\Users\martin.shaba\Documents\NetBeansProjects\Survey\nbproject\build-impl.xml:930: The following error occurred while executing this line:
C:\Users\martin.shaba\Documents\NetBeansProjects\Survey\nbproject\build-impl.xml:270: Compile failed; see the compiler error output for details.
BUILD FAILED (total time: 1 second)
Here's how I want it to be...
Choose from the following options:
S - Create a question in a string
N - Create a question in an integer
my current code:
package survey;
import java.util.Scanner;
import java.io.Serializable;
public class Survey implements Serializable
{
private String surveyName;
private Question[] questions;
private int numQuestions;
private int maxResponses;
private boolean initialized;
public Survey(String n)
{
surveyName = n;
initialized = false;
}
//initialize() sets up the numQuestions, MaxResponses, and questions for the survey
public char Questions()
{
Scanner input = new Scanner(System.in);
System.out.println("Initializing survey \"" + surveyName + "\"\n");
//add a method for password validation!?!?!? yes!!! see the bank accounts lab
System.out.print("Enter max number of responses: ");
maxResponses = input.nextInt();
System.out.print("Enter number of questions: ");
numQuestions = input.nextInt();
input.nextLine(); //have to do this to "eat" the new line character or the next input won't work correctly
System.out.println();
questions = new Question[numQuestions];
for(int i = 0; i < numQuestions;i++)
{
char choice;
//output menu options
System.out.println();
System.out.println(" S - Create String Question");
System.out.println(" N - Create Integer Question");
//loop until a valid input is entered
System.out.print("Enter choice: ");
choice = input.next().charAt(0);
//if choice is one of the options, return it. Otherwise keep looping
if(choice == 'S' || choice == 'N' )
return choice;
else
{
System.out.println("Invalid choice. Ensure a capital letter. Please re-enter.");
choice = '?';
}
(choice == '?');
return choice; //will never get here, but required to have a return statement to compile
}
System.out.print("Enter text for question " + (i+1) + ": ");
//you will also need to ask what KIND of question - right now, defaults to integer question
questions[i] = new IntegerQuestion(input.nextLine(),maxResponses);
initialized = true;
}
/*
run() gives the survey to a new survey taker, basically asks all the questions in the survey
*/
public void startSurvey()
{
if(initialized)
{
System.out.println("Welcome to the survey \"" + surveyName + "\"\n");
for(int i = 0;i < numQuestions; i ++)
{
questions[i].askQuestion();
}
System.out.println("Thank you for participating!");
}
else
{
System.out.println("Survey has not yet been setup. Please initialize first.");
}
}
/*
displayResults() displays the raw data for the survey
*/
public void Results()
{
System.out.println("Displaying data results for \"" + surveyName + "\"\n");
for(int i = 0;i < numQuestions; i ++)
{
questions[i].displayResults();
System.out.println();
}
}
/*
displayReportSummary() should run tests on your data
Examples could be: the most common response (median), the average response (mean), or display a graph of the results?
The choices are endless!
*/
public void reportSummary()
{
}
}
You're using i outside the loop. Because you declared i in the for loop, the scope of i is the loop only. It ceases to exist as soon as the loop ends.
The error messages from the compiler tell you which line of code the error is on, and exactly what the error is. It's worth learning to read these.
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
Hi developers on Stackoverflow! I have a problem on this exercise:
"Write a program that asks user to input a list of N names using the keyboard, then user continues
inputting a name for searching. The program should print out the position of this name in the list.
In case the name doesn’t appear in the list, the program should print out value -1."
Here is my code:
package Tut_01;
import java.util.ArrayList;
import java.util.Scanner;
public class Ex_04 {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
ArrayList<String> elements = new ArrayList<> ();
System.out.print ("How many numbers do you want to input: ");
int n = sc.nextInt (); // Count numbers that user want to input
// Ask the user input values
for (int i = 0; i < n; i++) {
System.out.print ("Enter your name " + (i + 1) + ": ");
String name = sc.next ();
elements.add (name);
}
System.out.println ("Which name do you want to search ?");
String searchName = sc.next ();
// Problem?
for (int p = 0; p < n; p++) {
if (searchName == elements.get (p)) {
System.out.println ("Your name is at index " + p + ": " + elements.get (p));
}
}
}
Here is my console:
How many numbers do you want to input: 2
Enter your name 1: Hoa
Enter your name 2: Hieu
Which name do you want to search ?
Hoa
Process finished with exit code 0
I mean I don't know why my code stops there instead of printing the position of the index. Anyone knows this issue? Thanks for showing me!
You are comparing String in the wrong way. String is an object not a primitive, so you cannot use ==.
The proper way is:
searchName.equals(elements.get(p))
Below the simple code will give the same output.Make use of indexOf method
System.out.println("Your name is at index " + elements.indexOf(searchName) + ": " + searchName);
This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 3 years ago.
I have to create a method to find the biggest number via an array.
I have tried this:
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner enter = new Scanner (System.in);
int[] tab = {10,4,23,45,28,34,89,9,16,55};
int choice = 0;
do{
System.out.println("*********Menu*********");
System.out.println("1) - The biggest number : ");
System.out.println("9) - Exit :");
System.out.print("Enter your choice please : ");
choice = enter.nextInt();
switch(choice){
case 1:
System.out.println("Option 1 :");
biggest_number(big);
break;
}
} while(choice != 9);
}
public static int biggest_number(int big){
for(int i=0;i<tab.length;i++){
if(tab[i] > big){
big = tab[i];
}
}
return big;
System.out.print("The biggest number is => " + big);
}
}
I have several error messages:
Main.java:23: error: cannot find symbol
biggest_number(big);
^
symbol: variable big
location: class Main
Main.java:34: error: cannot find symbol
for(int i=0;i<tab.length;i++){
^
symbol: variable tab
location: class Main
Main.java:35: error: cannot find symbol
if(tab[i] > big){
^
symbol: variable tab
location: class Main
Main.java:36: error: cannot find symbol
big = tab[i];
^
I don't understand my errors? I have declared a parameter which is called big.
Is it return is correct also according you?
For information: I am obliged to use a method for my learning in Java.
You need to correct/change the following things in your program to make it work as you are expecting:
Pass the array itself to the method, biggest_number(...) because the scope of the array, tab is local to public static void main(String[] args) i.e. it won't be visible to the method, biggest_number(...)
Remove System.out.print("The biggest number is => " + big); after the return big; statement as it be unreachable. The program control exits the method/function after the return statement; therefore, any code after the return statement will be treated unreachable/dead which will fail compilation.
Given below is the correct program incorporating the points mentioned above:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner enter = new Scanner(System.in);
int[] tab = { 10, 4, 23, 45, 28, 34, 89, 9, 16, 55 };
int choice = 0;
do {
System.out.println();
System.out.println("*********Menu*********");
System.out.println("1) - The biggest number : ");
System.out.println("9) - Exit :");
System.out.print("Enter your choice please : ");
choice = enter.nextInt();
switch (choice) {
case 1:
System.out.println("Option 1 :");
System.out.print("The biggest number is => " + biggest_number(tab));
break;
}
} while (choice != 9);
}
public static int biggest_number(int[] tab) {
int big=tab[0];
for (int i = 0; i < tab.length; i++) {
if (tab[i] > big) {
big = tab[i];
}
}
return big;
}
}
Output:
*********Menu*********
1) - The biggest number :
9) - Exit :
Enter your choice please : 1
Option 1 :
The biggest number is => 89
*********Menu*********
1) - The biggest number :
9) - Exit :
Enter your choice please :
The method biggest_number needs only the array as input:
static int biggest_number( int[] arr) {
if ( arr.length > 0 ) [
int big = arr[0];
for ( int i=1; i < arr.length; i++ ) {
if ( arr[i] > big ) {
big = arr[i];
}
}
return big;
}
return 0; // or throw an exception
}
As the error messages says:
You have are using the parameter big the wrong way, remove it.
you can't access the array tab from public static int biggest_number. either pass it as a parameter, or declare it as a static field.
I'm creating a text based game, I have a class made for the main character so you can set the characters name, etc. What I'm trying to figure out is, is there any way to pass a mutator (character.setname(input)) as an argument to another method. When I try to do it I'm told that I can't use a void type as an argument to a method. When I was writing out the code for the user to enter their name, and everything else it was repetitive with the error checking so I wanted to create my own method I could call that would error check for me. A couple sentences use the setname method to reset the name if it was entered incorrectly but I can't directly use setname in the error checking method because it's going to be using the same method to check other inputs of data.
Is there any way around this?
Here is the code as requested: I indeed may be overcomplicating the problem, I'm pretty new to java so I'm still learning.
The following code is the code I use to check if the user entered something correctly, it accepts an array which contains all the possible correct answers the user can type in, I've tried to design it in a way that I can error check anything with it, not just "yes" or "no" statements, getVariable is the accessor method, and setVariable is the one I'm trying to get to work, I'm trying to pass the mutator as well so I can reset the error
public void confirmEntry(String question, String[] options, String getVariable, setVariable) throws InterruptedException
{
boolean correctEntry = false;
System.out.print("Is this correct? ");
for(int i = 0; i < options.length - 1; i++)
{
System.out.print(options[i] + ", ");
}
System.out.print("or ");
System.out.print(options[options.length - 1] + ": ");
input = in.nextLine();
for(int i = 0; i < options.length; i++)
{
if(input.equals(options[i]))
{
correctEntry = true;
System.out.println(correctEntry);
}
}
System.out.println(correctEntry);
while(correctEntry == false)
{
Thread.sleep(2000);
System.out.print("You must enter ");
for(int i = 0; i < options.length - 1; i++)
{
System.out.print("\"" + options[i] + "\", ");
}
System.out.print("or ");
System.out.print("\"" + options[options.length - 1] + "\" to continue: ");
Thread.sleep(2000);
System.out.println();
System.out.println("You chose " + getVariable);
Thread.sleep(2000);
System.out.print("Is this correct? ");
for(int i = 0; i < options.length - 1; i++)
{
System.out.print(options[i] + ", ");
}
System.out.print(" or ");
System.out.print(options[options.length - 1] + ": ");
input = in.nextLine();
for(int i = 0; i < options.length; i++)
{
if(input.equals(options[i]))
{
correctEntry = true;
}
}
}
}
The following code is what is currently in the method where you enter information about the character. I'm trying to move more of the code into the error checking method so that each time I ask the user a question, name, age, etc. I just simply need to call the method.
public void characterCreation() throws Exception
{
//create an instance of the class player (your character creation)
Player character = new Player();
//Initial Introduction to the game
System.out.println("Welcome to Stranded!");
Thread.sleep(2000);
System.out.println("Tell us a little about yourself!");
Thread.sleep(2000);
//______________________________________________________________________________________________________________
//SET YOUR CHARACTER'S NAME
String[] yesNo = {"yes", "no"}; //array to feed into confirmEntry method
System.out.print("Enter your character's name: ");
input = in.nextLine(); //asks for input of the name
character.setName(input); //sets name in the player class
System.out.println("You chose " + character.getName()
+ " for your character's name");
Thread.sleep(2000);
confirmEntry("Enter your character's name: ", yesNo, character.getName(), character.setName(input));
while(input.equals("no"))
{
Thread.sleep(2000);
System.out.print("Enter your character's name: "); //prompt to enter name again
input = in.nextLine();
character.setName(input); //sets name in player class
Thread.sleep(2000);
System.out.println("You chose " + character.getName()
+ " for your character's name"); //confirms what user entered for name
Thread.sleep(2000);
confirmEntry("Enter your character's name: ", yesNo, character.getName(), character.setName(input));
}
I'm trying to move more code after the SET CHARACTER NAME comment into the confirmEntry method, however the rest of the code involved with the character's name uses the mutator to set the name. That's the problem. I wanted to try to get as much code into confirmEntry as possible so whenever I ask the user to enter something about their character I basically just have to call the method.
If you are using java 8 you can create your method with a method reference param :
public void functionName(Consumer<String> setter){setter.
accept(string);}
and to call your method you can use : functionName(character::setname);
you can see : http://www.informit.com/articles/article.aspx?p=2171751&seqNum=3
What is an entry? It appears to be some value that the user has entered.
class Entry{
String value;
public Entry(String value){
this.value = value;
}
public boolean confirm(String input){
return value.equals(input);
}
}
How about you store all of your entries.
Map<String, Entry> entries = new HashMap<>();
String message = "Enter your character's name: ";
System.out.println(message);
String input = in.nextLine();
entries.put(message, new Entry(input));
Now when you want to confirm.
public void confirmEntries(){
for(String message: entries.keySet()){
System.out.println(message);
System.out.println(entries.get(message) + "yes/no?");
//get some input and update the value. etc.
}
}
Another way to do it would be to create a Runnables.
List<Runnable> entryRunnables = new ArrayList<>();
Then anytime you want to add an action.
Runnable r = ()->{
System.out.println("Enter your players name, yes/no");
String input = in.readLine();
//check input and do stuff.
}
entryRunnables.add(r);
Now to check entries. (stream method)
entryRunnables.forEach(Runnable::run);
Or
for(Runnable r: entryRunnables){
r.run();
}
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 = ....
.....
}
This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 7 years ago.
import java.util.Scanner;
public class GuessingGameV1
{
public static void main(String [] args)
{
//
int counter = 0;
double randNum = 0.0;
randNum = Math.random();
int rand = (int)(randNum*100);
System.out.println("Please enter your guess: ");
int guess = in.nextInt();
while(guess !=rand)
{
if((guess< rand)&&(guess>=0))
{
System.out.println("Your guess is too low");
}
else if((guess> rand)&&(guess<=100))
{
System.out.println("Your guess is too high");
}
else if (guess<0)
{
System.out.println("Out of Range! Please choose a number more than 0");
}
else if (guess<100)
{
System.out.println("Out of Range! Please choose a number less than or 100");
}
counter++;
}
System.out.println("You are correct! The number was " + rand);
System.out.println("It took you " + counter + " tries to get it!");
}
}
My program is supposed to be a guessing game. Note I am very new to Java and I have re-written my program twice and it still gives me the error! What is wrong with my program?
Basically the user should input a number and the program will spit back wether it should be higher or lower, go again until the user gets it right. After they do it tells them the number and how many times it took them to do it.
Thanks!
You havent declared variable in.
Declare it :
Scanner in = new Scanner(System.in);