public void populateNotesFromFile()
{
try{
BufferedReader reader = new BufferedReader(new FileReader(DEFAULT_NOTES_SAVED));
String fileNotes = reader.readLine();
while(fileNotes != null){
notes.add(fileNotes);
fileNotes = reader.readLine();
}
reader.close();
}
catch (IOException e){
System.err.println("The desired file " + DEFAULT_NOTES_SAVED + " has problems being read from");
}
catch (FileNotFoundException e){
System.err.println("Unable to open " + DEFAULT_NOTES_SAVED);
}
//make sure we have one note
if (notes.size() == 0){
notes.add("There are no notes stored in your note book");
}
}
Whenever i compile the above i get a message saying cannot find symbol class IOException e
can someone tell me how to fix it please :d
thanks
Raedwald
45.4k39 gold badges149 silver badges234 bronze badges
asked May 16, 2009 at 10:03
2
IOException is a class from the java.io package, so in order to use it, you should add an import
declaration to your code. import java.io.*;
(at the very top of the java file, between the package name and your class declaration)
FileNotFoundException is a IOException. It’s a specialisation of IOException. Once you have caught the IOException, the flow of the program will never get to the point of checking for a more specific IOException. Just swap these two, to test for the more specific case first (FileNotFound) and then handle (catch) any other possible IOExceptions.
answered May 16, 2009 at 10:08
Peter PerháčPeter Perháč
20.3k21 gold badges117 silver badges152 bronze badges
7
You need
import java.io;
at the top of your file.
Also, FileNotFoundException needs to be above IOException since it’s a subclass of IOException.
answered May 16, 2009 at 10:05
TheSoftwareJediTheSoftwareJedi
34.1k19 gold badges108 silver badges151 bronze badges
0
Your probably missing an import
reference to IOException
class
. I’ts located in the java.io
package.
Can I suggest a litle change in you method? Always close the stream in a finally block:
public void populateNotesFromFile() {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(DEFAULT_NOTES_SAVED));
String fileNotes = reader.readLine();
while (fileNotes != null) {
notes.add(fileNotes);
fileNotes = reader.readLine();
}
} catch (FileNotFoundException e) {
System.err.println("Unable to open " + DEFAULT_NOTES_SAVED);
} catch (IOException e) {
System.err.println("The desired file " + DEFAULT_NOTES_SAVED
+ " has problems being read from");
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// make sure we have one note
if (notes.size() == 0) {
notes.add("There are no notes stored in your note book");
}
}
answered May 16, 2009 at 10:17
bruno condebruno conde
47.6k14 gold badges98 silver badges117 bronze badges
You need to either import the java.io.* package at the top of the file, or fully-qualify the exception as java.io.IOException
answered May 16, 2009 at 10:05
thecoopthecoop
44.8k19 gold badges130 silver badges186 bronze badges
Switch the order of FileNotFoundException and IOException
answered May 16, 2009 at 10:11
Stephen DenneStephen Denne
35.9k10 gold badges45 silver badges60 bronze badges
2
public void populateNotesFromFile()
{
try{
BufferedReader reader = new BufferedReader(new FileReader(DEFAULT_NOTES_SAVED));
String fileNotes = reader.readLine();
while(fileNotes != null){
notes.add(fileNotes);
fileNotes = reader.readLine();
}
reader.close();
}
catch (IOException e){
System.err.println("The desired file " + DEFAULT_NOTES_SAVED + " has problems being read from");
}
catch (FileNotFoundException e){
System.err.println("Unable to open " + DEFAULT_NOTES_SAVED);
}
//make sure we have one note
if (notes.size() == 0){
notes.add("There are no notes stored in your note book");
}
}
Whenever i compile the above i get a message saying cannot find symbol class IOException e
can someone tell me how to fix it please :d
thanks
Raedwald
45.4k39 gold badges149 silver badges234 bronze badges
asked May 16, 2009 at 10:03
2
IOException is a class from the java.io package, so in order to use it, you should add an import
declaration to your code. import java.io.*;
(at the very top of the java file, between the package name and your class declaration)
FileNotFoundException is a IOException. It’s a specialisation of IOException. Once you have caught the IOException, the flow of the program will never get to the point of checking for a more specific IOException. Just swap these two, to test for the more specific case first (FileNotFound) and then handle (catch) any other possible IOExceptions.
answered May 16, 2009 at 10:08
Peter PerháčPeter Perháč
20.3k21 gold badges117 silver badges152 bronze badges
7
You need
import java.io;
at the top of your file.
Also, FileNotFoundException needs to be above IOException since it’s a subclass of IOException.
answered May 16, 2009 at 10:05
TheSoftwareJediTheSoftwareJedi
34.1k19 gold badges108 silver badges151 bronze badges
0
Your probably missing an import
reference to IOException
class
. I’ts located in the java.io
package.
Can I suggest a litle change in you method? Always close the stream in a finally block:
public void populateNotesFromFile() {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(DEFAULT_NOTES_SAVED));
String fileNotes = reader.readLine();
while (fileNotes != null) {
notes.add(fileNotes);
fileNotes = reader.readLine();
}
} catch (FileNotFoundException e) {
System.err.println("Unable to open " + DEFAULT_NOTES_SAVED);
} catch (IOException e) {
System.err.println("The desired file " + DEFAULT_NOTES_SAVED
+ " has problems being read from");
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// make sure we have one note
if (notes.size() == 0) {
notes.add("There are no notes stored in your note book");
}
}
answered May 16, 2009 at 10:17
bruno condebruno conde
47.6k14 gold badges98 silver badges117 bronze badges
You need to either import the java.io.* package at the top of the file, or fully-qualify the exception as java.io.IOException
answered May 16, 2009 at 10:05
thecoopthecoop
44.8k19 gold badges130 silver badges186 bronze badges
Switch the order of FileNotFoundException and IOException
answered May 16, 2009 at 10:11
Stephen DenneStephen Denne
35.9k10 gold badges45 silver badges60 bronze badges
2
Introduction to Symbol Tables
Symbol tables are an important data structure created and maintained by compilers to store information associated with identifiers [1] in a given source code. This information is entered into the symbol tables during lexical and syntax analysis and is used in the later phases of compilation. As the declarations of classes, interfaces, variables, and methods are processed, their identifiers are bound to corresponding entries in the symbol tables. When uses of these identifiers are encountered in the source code, the compiler looks them up in the symbol tables and relies on this information for things such as verifying that a variable has been declared, determining the scope of a variable, and verifying that an expression is semantically correct with type checking. Symbol tables are also used for code generation and optimization [2].
A simplified representation of a symbol table entry (or simply, a symbol) in Java has the following format: <symbol name (identifier), type, scope, [attributes]>
. Given a global variable declaration like final double ratio;
the corresponding symbol would then be <ratio, double, global, [final]>
.
Install the Java SDK to identify and fix exceptions
Cannot Find Symbol Error
As its name implies, the cannot find symbol
error refers to a symbol which cannot be found. While there are multiple ways and reasons this can occur, they all boil down to the fact that the Java compiler is unable to find the symbol associated with a given identifier.
The message produced by the compiler for the cannot find symbol
error includes two additional fields:
- “symbol”—the name and type of the referenced identifier; and
- “location”—the specific class in which the identifier has been referenced.
What Causes the Cannot Find Symbol Error
The most common triggers for the cannot find symbol
compile-time error include:
- missing variable and method declarations;
- out-of-scope references to variables and methods;
- misspelled identifiers; and
- omitted import statements.
Cannot Find Symbol vs Symbol Not Found vs Cannot Resolve Symbol
As different Java compilers use slightly different terminology, the cannot find symbol
error can also be found under the terms symbol not found
and cannot resolve symbol
. Besides the naming, there is no difference between what these terms stand for.
Cannot Find Symbol Error Examples
Undeclared variable
When the Java compiler encounters a use of an identifier which it cannot find in the symbol table, it raises the cannot find symbol
error. Consequently, the most common occurrence of this error is when there is a reference to an undeclared variable. Unlike some other languages that don’t require explicit declaration of variables [3], or may allow declaring a variable after it has been referenced (via hoisting [4]), Java requires declaring a variable before it can be used or referenced in any way.
Fig. 1(a) shows how an undeclared variable, in this case the identifier average
on line 9, results in two instances of the cannot find symbol
error, at the positions where they appear in the code. Declaring this variable by specifying its data type (or, alternatively, inferring its type with the var
keyword in Java 10+) resolves the issue (Fig. 1(b)).
(a)
1
2
3
4
5
6
7
8
9
10
11
12
package rollbar;
public class UndeclaredVariable {
public static void main(String... args) {
int x = 6;
int y = 10;
int z = 32;
average = (x + y + z) / 3.0; // average is not declared
System.out.println(average);
}
}
UndeclaredVariable.java:9: error: cannot find symbol
average = (x + y + z) / 3.0;
^
symbol: variable average
location: class UndeclaredVariable
UndeclaredVariable.java:10: error: cannot find symbol
System.out.println(average);
^
symbol: variable average
location: class UndeclaredVariable
2 errors
(b)
1
2
3
4
5
6
7
8
9
10
11
12
package rollbar;
public class UndeclaredVariable {
public static void main(String... args) {
int x = 6;
int y = 10;
int z = 32;
double average = (x + y + z) / 3.0;
System.out.println(average);
}
}
16.0
Out of scope variable
When a Java program tries to access a variable declared in a different (non-inherited or non-overlapping) scope, the compiler triggers the cannot find symbol
error. This is demonstrated by the attempt to access the variable counter
on lines 17 and 18 in Fig. 2(a), which is accessible only within the for
statement declared on line 11. Moving the counter
variable outside the for
loop fixes the issue, as shown on Fig. 2(b).
(a)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package rollbar;
import java.util.Arrays;
import java.util.List;
public class OutOfScopeVariable {
public static void main(String... args) {
final List<String> strings = Arrays.asList("Hello", "World");
final String searchFor = "World";
for (int counter = 0; counter < strings.size(); counter++) {
if (strings.get(counter).equals(searchFor)) {
break;
}
}
if (counter < strings.size()) {
System.out.println("The word " + searchFor + " was found at index " + counter);
} else {
System.out.println("The word " + searchFor + " wasn't found");
}
}
}
OutOfScopeVariable.java:17: error: cannot find symbol
if (counter < strings.size()) {
^
symbol: variable counter
location: class OutOfScopeVariable
OutOfScopeVariable.java:18: error: cannot find symbol
System.out.println("The word " + searchFor + " was found at index " + counter);
^
symbol: variable counter
location: class OutOfScopeVariable
2 errors
(b)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package rollbar;
import java.util.Arrays;
import java.util.List;
public class OutOfScopeVariable {
public static void main(String... args) {
final List<String> strings = Arrays.asList("Hello", "World");
final String searchFor = "World";
int counter;
for (counter = 0; counter < strings.size(); counter++) {
if (strings.get(counter).equals(searchFor)) {
break;
}
}
if (counter < strings.size()) {
System.out.println("The word " + searchFor + " was found at index " + counter);
} else {
System.out.println("The word " + searchFor + " wasn't found");
}
}
}
The word ‘World’ was found at index 1
Misspelled method name
Misspelling an existing method, or any valid identifier, causes a cannot find symbol
error. Java identifiers are case-sensitive, so any variation of an existing variable, method, class, interface, or package name will result in this error, as demonstrated in Fig. 3.
(a)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package rollbar;
public class MisspelledMethodName {
static int fibonacci(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
}
public static void main(String... args) {
int fib20 = Fibonacci(20); // Fibonacci ≠ fibonacci
System.out.println(fib20);
}
}
MisspelledMethodName.java:11: error: cannot find symbol
int fib20 = Fibonacci(20);
^
symbol: method Fibonacci(int)
location: class MisspelledMethodName
(b)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package rollbar;
public class MisspelledMethodName {
static int fibonacci(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
}
public static void main(String... args) {
int fib20 = fibonacci(20);
System.out.println(fib20);
}
}
6765
Missing import statement
Using classes, either from the Java platform or any library, requires importing them correctly with the import
statement. Failing to do so will result in the cannot find symbol
error being raised by the Java compiler. The code snippet in Fig. 4(a) makes use of the java.util.List
class without declaring the corresponding import, therefore the cannot find symbol
error occurs. Adding the missing import
statement (line 4 in Fig. 4(b)) solves the problem.
(a)
package rollbar;
import java.util.Arrays;
public class MissingImportList {
private static final List<String> CONSTANTS = Arrays.asList("A", "B", "C");
public static void main(String... args) {
System.out.println(CONSTANTS);
}
}
MissingImportList.java:6: error: cannot find symbol
private static final List<String> CONSTANTS = Arrays.asList("A", "B", "C");
^
symbol: class List
location: class MissingImportList
(b)
1
2
3
4
5
6
7
8
9
10
11
12
package rollbar;
import java.util.Arrays;
import java.util.List;
public class MissingImportList {
private static final List<String> CONSTANTS = Arrays.asList("A", "B", "C");
public static void main(String... args) {
System.out.println(CONSTANTS);
}
}
[A, B, C]
Less common examples
The root cause for the cannot find symbol
Java error can occasionally be found in some unexpected or obscure places. Such is the case with accidental semicolons that terminate a statement ahead of time (Fig. 5), or when object creation is attempted without a proper constructor invocation which has to have the new
keyword (Fig. 6).
(a)
package rollbar;
public class LoopScope {
public static void main(String... args) {
int start = 1, end = 10;
for (int i = start; i <= end; i++); {
System.out.print(i == end ? i : i + ", ");
}
}
}
LoopScope.java:7: error: cannot find symbol
System.out.print(i == end ? i : i + ", ");
^
symbol: variable i
location: class LoopScope
LoopScope.java:7: error: cannot find symbol
System.out.print(i == end ? i : i + ", ");
^
symbol: variable i
location: class LoopScope
LoopScope.java:7: error: cannot find symbol
System.out.print(i == end ? i : i + ", ");
^
symbol: variable i
location: class LoopScope
3 errors
(b)
package rollbar;
public class LoopScope {
public static void main(String... args) {
int start = 1, end = 10;
for (int i = start; i <= end; i++) {
System.out.print(i == end ? i : i + ", ");
}
}
}
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
(a)
package rollbar;
public class ObjectCreation {
public static void main(String... args) {
String s = String("Hello World!");
System.out.println(s);
}
}
ObjectCreation.java:5: error: cannot find symbol
String s = String("Hello World!");
^
symbol: method String(String)
location: class ObjectCreation
(b)
package rollbar;
public class ObjectCreation {
public static void main(String... args) {
String s = new String("Hello World!");
System.out.println(s);
}
}
Hello World!
Other causes for the cannot find symbol
error may include:
- using dependencies with old or incompatible versions;
- forgetting to recompile a program;
- building a project with an older JDK version;
- redefining platform or library classes with the same name;
- the use of homoglyphs in identifier construction that are difficult to tell apart;
- etc.
Conclusion
The cannot find symbol
error, also found under the names of symbol not found
and cannot resolve symbol
, is a Java compile-time error which emerges whenever there is an identifier in the source code which the compiler is unable to work out what it refers to. As with any other compilation error, it is crucial to understand what causes this error, pinpoint the issue and address it properly. In the majority of cases, referencing undeclared variables and methods, including by way of misspelling them or failing to import their corresponding package, is what triggers this error. Once discovered, resolution is pretty straightforward, as demonstrated in this article.
Track, Analyze and Manage Errors With Rollbar
![Rollbar in action](https://rollbar.com/wp-content/uploads/2022/04/section-1-real-time-errors@2x-1-300×202.png)
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!
References
[1] Rollbar, 2021. Handling the <Identifier> Expected Error in Java. Rollbar Editorial Team. [Online]. Available: https://rollbar.com/blog/how-to-handle-the-identifier-expected-error-in-java/. [Accessed Nov. 22, 2021].
[2] ITL Education Solutions Limited, Principles of Compiler Design (Express Learning), 1st ed. New Delhi: Pearson Education (India), 2012.
[3] Tutorialspoint.com, 2021. Python — Variable Types. [Online]. Available: https://www.tutorialspoint.com/python/python_variable_types.htm. [Accessed: Nov. 23, 2021].
[4] JavaScript Tutorial, 2021. JavaScript Hoisting Explained By Examples. [Online]. Available: https://www.javascripttutorial.net/javascript-hoisting/. [Accessed: Nov. 23, 2021]
Symbols and Symbol Table
Before diving into the details of the “cannot find a symbol” error, here is a brief introduction to symbols and symbol tables in Java. A symbol refers to an identifier in the compilation process in Java. All the identifiers used in the source code are collected into a symbol table in the lexical analysis stage. The symbol table is a very significant data structure created and maintained by the compilers to store all the identifiers and their information.
This information is entered into the symbol tables during lexical and syntax analysis which is then used in multiple phases of compilation.
From classes, variables, interfaces to methods, all of them require an identifier for declaration. During the code generation process, when these identifiers are encountered in the source code, the compiler checks for them in the symbol tables and the stored information is then used to verify the declarations, the scope of a variable, and verifying that the expression is semantically correct or not.
The compilation process usually does not go as smooth as you would think. Errors are inevitable in any development stage and one of the very commonly occurring errors during the compilation process is Java “cannot Find Symbol” Error. In this article, we will be discussing the reasons behind the occurrence of Java cannot find symbol errors and how you can resolve them.
As the name suggests, the Java cannot find symbol error occurs when a required symbol cannot be found in the symbol table. Although there can be various reasons behind this, it points to one fact the Java compiler was unable to find the symbol and its details associated with a given identifier.
As there are a variety of Java compilers available, many of them use slightly different terminologies, because of that, you can also find the “cannot find symbol” error termed as the “symbol not found” or “cannot resolve symbol” error. Besides the name, there is simply no difference between these errors.
Structure of Java Cannot Find Symbol Error
The compiler output a specific error message with the cannot find symbol error.
It contains the following two fields that indicate the missing symbol and its location:
- Symbol: The name and type of the identifier you are looking for.
- Location: The particular class in which that identifier has been referenced.
Causes of Java Cannot Find Symbol Error
We will be discussing the following most common causes of the cannot find symbol error during compilation,
- misspelt identifiers
- Undeclared variables
- Out of scope references to variables and methods
- The unintentional omission of import statements
Misspelt identifier names
This is the most common and most occurring reason behind the Java cannot find symbol error. Misspelling an existing variable, class, interface, package name or a method causes the “cannot find symbol error” as the compiler cannot recognize the symbol and identifies it as an undeclared variable. Java identifiers are also case-sensitive, so even a slight variation of an existing variable will result in this error.
See code example below:
1. public class MisspelledMethodNameExample { 2. static int findLarger(int n1, int n2) { 3. if (n1 > n2) return n1; 4. if (n2 > n11) return n2; 5. if (n2 == n11) return -1; 6. } 7. 8. public static void main(String... args) { 9. int value = findlarger(20, 4); // findlarger ≠ findLarger 10. System.out.println(value); 11. } 12. }
MisspelledMethodNameExample.java:9: error: cannot find symbol int value = Fibonacci(20); ^ symbol: method findLarger(int, int) location: class MisspelledMethodNameExample
It can be easily resolved by correcting the spelling of the function in line 9.
Undeclared variables
When the Java compiler come across an identifier used in the code but it cannot be found in the symbol table, the “cannot find symbol” error is shown. The only reason behind the absence of a variable from the symbol table is that it is not declared in the code. Some new programming languages do not require explicit declaration of variables but it is mandatory in Java to always declare a variable before it is used or referenced in the source code.
The code snippet below demonstrates an undeclared variable in the code. In this case, the identifier sum on line 7, causes the Java “cannot find symbol error”.
See code example below:
1. public class UndeclaredVariableExample 2. { 3. public static void main(String... args) { 4. int num1 = 5; 5. int num2 = 10; 6. int num3 = 43; 7. sum = (num1 + num2 + num3) // sum is not declared 8. System.out.println(sum); 9. } 10. }
UndeclaredVariableExample.java:7: error: cannot find symbol sum = (num1 + num2 + num3); ^ symbol: variable sum location: class UndeclaredVariableExample UndeclaredVariableExample.java:8: error: cannot find symbol System.out.println(sum); ^ symbol: variable sum location: class UndeclaredVariableExample 2 errors
Declaring this variable by specifying the appropriate data type can easily resolve the error.
See this corrected code below,
1. public class UndeclaredVariableExample 2. { 3. public static void main(String args) { 4. int num1 = 5; 5. int num2 = 10; 6. int num3 = 43; 7. 8. int sum = (num1 + num2 + num3); 9. System.out.println(sum); 10. } 11. }
Out of scope variable
When a Java code attempts to access a variable declared out of scope such as in a non-inherited scope the compiler will result in issuing the “cannot find symbol” error. This commonly happens when you attempt to access a variable declared inside a method or a loop, from outside of the method.
See this code example below where the “cannot find symbol” error has occurred when the counter variable which is declared inside a for loop is attempted to be accessed from out of the loop.
See code below:
1. public class OutOfScopeExample 2. { 3. public static void main(String args) { 4. 5. for (int counter = 0; counter < 100; counter++) 6. { … } 7. 8. System.out.println(“Even numbers from 0 to 100”) 9. if (counter mod 2 == 0) 10. { 11. System.out.println(counter); 12. } 13. } 14. }
OutOfScopeVariableExample.java:9: error: cannot find symbol if (counter mod 2 == 0) ^ symbol: variable counter location: class OutOfScopeVariableExample OutOfScopeVariableExample.java:12: error: cannot find symbol System.out.println(counter); ^ symbol: variable counter location: class OutOfScopeVariableExample 2 errors
I can be easily resolved by just moving the if block inside the for loop (local scope).
See this code example,
1. public class OutOfScopeExample 2. { 3. public static void main(String... args) { 4. 5. for (int counter = 0; counter < 100; counter++) 6. { 7. System.out.println(“Even numbers from 0 to 100”) 8. if (counter mod 2 == 0) 9. { 10. System.out.println(counter); 11. } 12. } 13. } 14. }
Missing import statement
Java allows you to use built-in classes or any imported libraries in your code to save your time by reusing the code but it requires importing them properly using the import statements at the start. Missing the import statement in your code will result in the cannot find symbol error.
java.util.Math class is utilized in the code given below but it is not declared with the “import” keyword, resulting in the “cannot find symbol error”.
See code below:
1. public class MissingImportExample { 2. 3. public static void main(String args) 4. { 5. double sqrt19 = Math.sqrt(19); 6. System.out.println("sqrt19 = " + sqrt19); 7. } 8. }
MissingImportExample.java:6: error: cannot find symbol double sqrt19 = Math.sqrt(19); ^ symbol: class Math location: class MissingImportExample
Adding the missing import statement can easily solve the issue, see code below:
1. import java.util.Math; 2. 3. public class MissingImporExample { 4. 5. public static void main(String args) 6. { 7. double sqrt19 = Math.sqrt(19); 8. System.out.println("sqrt19 = " + sqrt19); 9. } 10. }
Miscellaneous reasons
We have covered some of the main causes of the “cannot find symbol” Java error but occasionally it can also result due to some unexpected reasons. One such case is when attempting to create an object without the new keyword or an accidental semicolon at the wrong place that would terminate the statement at an unexpected point.
Also Read: Functional Interfaces In Java
Some other causes for the cannot find symbol error may include when you forget to recompile the code or you end up using the dependencies with an incompatible version of Java. Building a project with a very old JDK version can also be a reason as well as mistakenly redefining platform or library classes with the same identifier.
Conclusion
We have discussed that the “cannot find symbol Java” error is a Java compile-time error which is encountered whenever an identifier in the source code is not identified by the compiler. Similar to any other compilation error, it is very significant to understand the causes of this error, so that you can easily pinpoint the issue and address it properly.
Once you can discover the reason behind the error, it can be easily resolved as demonstrated by various examples in this article.
Пытаюсь скомпилировать через консоль файл result и выдает следующую ошибку(в idea все идеально работает). Есть 2 класса в разных файлах. result — это типо как main
package VSU.CS.VEGA;
import java.io.IOException;
public class result {
public static void main(String[] args) throws IOException {
inputAndOutput output = new inputAndOutput();
String error = "You entered a non-rectangular matrix, please check the data and re-enter.";
try {
output.readMtx();
}
catch (ArrayIndexOutOfBoundsException exception){
System.err.print(error);
}
}
}
package VSU.CS.VEGA;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.lang.ArrayIndexOutOfBoundsException;
public class inputAndOutput {
void readMtx() throws IOException {
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
ArrayList<String> lines = new ArrayList<>();
while (br.ready()) {
lines.add(br.readLine());
}
int matrixHeight = lines.size();
int[][] matrix = new int[matrixHeight][];
for(int i = 0; i < matrixHeight; ++i) {
String[] nums = lines.get(i).split("s*,s*");
matrix[i] = new int[nums.length];
for(int j = 0; j < nums.length; ++j) {
matrix[i][j] = Integer.parseInt(nums[j]);
}
}
int[][] matrixForOutput = calc(matrix);
try(PrintWriter out = new PrintWriter(new FileOutputStream("output.txt"))) {
for (int i = 0; i < matrixHeight; ++i) {
out.println(Arrays.toString(matrixForOutput[i]).replaceAll("^\[|]$", ""));
}
}
catch (ArrayIndexOutOfBoundsException ignored){
}
//out.println(Arrays.toString(matrixForOutput).replaceAll("^\[|]$", ""));
}
int[][] calc(int[][] array) {
int rows = array.length;
int cols = array[0].length;
boolean[] minRows = null, maxRows = null;
boolean[] minCols = null, maxCols = null;
Integer min = null;
Integer max = null;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (null == min || array[i][j] < min) {
minRows = new boolean[rows];
minRows[i] = true;
minCols = new boolean[cols];
minCols[j] = true;
min = array[i][j];
} else if (array[i][j] == min) {
minRows[i] = true;
minCols[j] = true;
}
if (null == max || array[i][j] > max) {
maxRows = new boolean[rows];
maxRows[i] = true;
maxCols = new boolean[cols];
maxCols[j] = true;
max = array[i][j];
} else if (array[i][j] == max) {
maxRows[i] = true;
maxCols[j] = true;
}
}
}
// uncomment to debug
// System.out.println("min=" + min + "; max=" + max);
// System.out.println("minRows=" + Arrays.toString(minRows));
// System.out.println("maxRows=" + Arrays.toString(maxRows));
// System.out.println("minCols=" + Arrays.toString(minCols));
// System.out.println("maxCols=" + Arrays.toString(maxCols));
int rowsToDelete = 0, colsToDelete = 0;
for (int i = 0; i < rows; i++) {
if (minRows[i] || maxRows[i]) {
rowsToDelete++;
}
}
for (int i = 0; i < cols; i++) {
if (minCols[i] || maxCols[i]) {
colsToDelete++;
}
}
if (rows == rowsToDelete || cols == colsToDelete) {
return new int[1][0];
}
int[][] result = new int[rows - rowsToDelete][cols - colsToDelete];
for (int i = 0, r = 0; i < rows; i++) {
if (minRows[i] || maxRows[i])
continue; // пропустить строку, содержащую минимум или максимум
for (int j = 0, c = 0; j < cols; j++) {
if (minCols[j] || maxCols[j])
continue; // пропустить столбец, содержащий минимум или максимум
result[r][c++] = array[i][j];
}
r++;
}
//out.println(Arrays.toString(array).replaceAll("^\[|]$", ""));
return result;
}
}
сама ошибка:
result.java:6: error: cannot find symbol
inputAndOutput output = new inputAndOutput();
^
symbol: class inputAndOutput
location: class result
result.java:6: error: cannot find symbol
inputAndOutput output = new inputAndOutput();
^
symbol: class inputAndOutput
location: class result
2 errors
6 Replies
-
IOException is a class from the java.io package, so in order to use it, you should add an import declaration to your code. import java.io.*; (at the very top of the java file, between the package name and your class declaration)
FileNotFoundException is an IOException. It’s a specialization of IOException. Once you have caught the IOException, the flow of the program will never get to the point of checking for a more specific IOException. Just swap these two, to test for the more specific case first (FileNotFound) and then handle (catch) any other possible IOExceptions.
Was this post helpful?
thumb_up
thumb_down
-
Hi
Did you tried the following:
* copy/paste the class file into your project src directory
* then copy your .java file and recompile it
* compile the IO.java File before you try and Run
More details see the answers from this URL:
http://www.dreamincode.net/forums/topic/54607-making-my-classes-available-to-myself/ Opens a new window Opens a new window
Was this post helpful?
thumb_up
thumb_down
-
Java is «stupid» with imports. You need to add imports to the top of the file, before any other code. It can be after the initial comments describing the file but before the first «class» statement.
Depending on the version of Java, one of the following:
// Wildcarded import
import java.IO.*;or
// If IO is a class vs. a namespace (I think this is the correct option)
import java.IO;or
// IO is a namespace — old method prior to Java 8 requires each method to be listed.
import java.IO.output;
import java.IO.inputDouble;
…Thank you for being upfront about this being a class exercise. A lot of these aren’t identified as such and result in members here getting riled up. Another good source I have used for Java is google (actually duckduckgo). For your error message, enter
java cannot find symbol — variable IO
into the search engine’s query bar. Put the language in the search to reduce the number of other language returns.
Was this post helpful?
thumb_up
thumb_down
-
Thanks.. I tried but same.
Was this post helpful?
thumb_up
thumb_down
-
tablesalt wrote:
Thanks.. I tried but same.
Java is case sensitive. Notice that I capitalized IO in my examples.
Was this post helpful?
thumb_up
thumb_down
-
What does this error mean?
The «Cannot find symbol» errors generally occur when you try to
reference an undeclared variable in your code. A «Cannot find symbol»
error means that the compiler cannot do this. Your code appears to be
referring to something that the compiler doesn’t understand.What things can cause this error?
The general causes for a Cannot find symbol error are things like:
- Incorrect spelling.
- Wrong case. Halo is different from halo.
- Improper use of acceptable identifier values (letters, numbers,
underscore, dollar sign), my-class is not the same as myclass. - No variable declaration or variable is outside of the scope you are
referencing it in.
More about…cannot find symbol Error Opens a new window Opens a new window
Dell
Was this post helpful?
thumb_up
thumb_down