error: '.class' expected [duplicate] - java

This question already has an answer here:
What does "error: '.class' expected" mean and how do I fix it
(1 answer)
Closed 4 years ago.
Hi friends while compiling the below error is coming
error: '.class' expected
I'm not able to find what is the error. I checked in many websites but not able to find why this error is coming. Plz Help
Thanks in advance.
import java.io.*;
class Test
{
boolean isGoodEmployee(boolean ismarried,int noofchild,String middlename,String childnames[])
{
boolean child,letter,last,child;
if (noofchild <= 2)
child=true;
boolean firstletter = middlename.startsWith("k");
boolean lastletter = middlename.endssWith("e");
if (firstletter && (!lastletter))
letter = true;
int lastnameletterscount = lastname.length();
if (lastnameletterscount > 4)
last = true;
String name = raju;
for (int i=0; i < noofchild; i++)
if(name.equalsIgnoreCase(childnames[i]))
{
child = true;
break;
}
}
}
class GoodEmployee
{
public static void main(String args[]) throws IOException
{
String firstname, middlename, lastname;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the first name of employee");
firstname = br.readLine();
System.out.println("enter the middle name of employee");
middlename = br.readLine();
System.out.println("enter the last name of employee");
lastname = br.readLine();
//System.out.println("full name of employee is:"+first+middle+last);
System.out.println("enter employee is married or not");
boolean ismarried = Boolean.parseBoolean(br.readLine());
if (ismarried)
System.out.println("enter number of childrens");
int noofchild = Integer.parseInt(br.readLine());
String childnames[] = new String[noofchild];
System.out.println("enter children names");
for (int i=0; i < noofchild; i++)
childnames[i] = br.readLine();
Test t = new Test();
t.isGoodEmployee(ismarried,noofchild,middlename,childnames[]);
}
}
I'm using "javac GoodEmployee.java" to compile the program

You have a mis-matching method call in isGoodEmployee.
The childnames argument is defined as an array, so you can simply pass in the argument, replace:
t.isGoodEmployee(ismarried,noofchild,middlename,childnames[]);
with
t.isGoodEmployee(ismarried,noofchild,middlename,childnames);
Aside from that, do not ignore other compilers errors such as
middlename.endssWith("e");
^---------extra 's'
Familiarize yourself with the javadocs.

there's plenty wrong with this code:
you've declared boolean child twice in isGoodEmployee() (1st line)
endssWith should be endsWith()
and so on, but nont of them are the issue you stated. what command line are you using for compiling this class?

#Reimeus has nailed it.
The strange compilation error can be explained as follows. In this line:
t.isGoodEmployee(ismarried,noofchild,middlename,childnames[]);
the childnames[] phrase is supposed to be a Java expression. But in fact, the syntax most closely resembles a type ... in fact an array of some (non-existent) class called childnames. The Java compiler's syntax error recovery code has decided that if it inserts .class after the typename (i.e. childnames[].class) that will give a syntactically valid expression.
Of course, the correction that the compiler is suggesting is nonsensical ... not least because there won't be a class or interface named childnames in your application.
The moral of the story is that unusual syntax errors sometimes cause a compiler to produce peculiar error messages that only make sense if you can figure out how the parser would have parsed the erroneous input.

Make the class with the main method public if you are using an IDE.
In case you are trying to run it using command window I don't think a '.class' file is required for compiling rather it would be required for execution. So after you have a .class file by entering javac GoodEmployee and you have no errors enter java GoodEmployee which will execute the .class file you have.

Related

Is there a Java function that can read a dictionary file and output the definition when asked for a word in standard input? [duplicate]

This question already has answers here:
Array Required, but java.lang.String found
(2 answers)
Closed 11 months ago.
I have a file definitions.dict which contains words and their respective definitions. A snippet of the file looks like this:
dictionary ? a book or electronic resource that gives a list of the words of a language in alphabetical order and explains what they mean
word ? a single unit of language that means something and can be spoken or written
computer ? an electronic machine that can store, organise and find information, do processes with numbers and other data, and control other machines
I'm trying to write Java code, that takes the word as standard input and outputs the definition of said word. The code I've written so far fails to even compile, giving the error:
Dictionary.java:25: error: array required, but String found
if(searchword.equals(line[i][0])){
^
Dictionary.java:26: error: array required, but String found
System.out.println(line[i][1]);
^
Here is the code I have so far:
import java.util.*;
import java.io.*;
public class Dictionary {
public static void main(String[] args) throws FileNotFoundException {
String searchword = "";
String[] line = {};
int i;
Scanner scanword = new Scanner(System.in);
if(scanword.hasNextLine()){
searchword = scanword.nextLine();
}
try{
Scanner scan = new Scanner(new File("sample.dict"));
while (scan.hasNextLine()){
line = Arrays.copyOf(line, line.length + 1);
line[line.length-1] = scan.nextLine();
}
for(i = 0; i < line.length; i++) {
line[i].split("\\ ? ");
if(searchword.equals(line[i][0])){
System.out.println(line[i][1]);
}
}
}
catch (FileNotFoundException ex) {
;
}
}
}
I will admit that this is part of an assignment which I've been struggling with for a while and I am asking here as a last resort.
(Note that I am only allowed to work with arrays and no other data structure.)
Slighlty different approach but what I did was actually create a dictionary object with two parameters:
public String term;
public String definition;
Then had a method to load dictionary objects into a Dictionary[] array from my sample.dict.
So then all I had to do in my main method was something like:
Dictionary[] definitions = loadDefinitions(f);
while (scan.hasNext()){
String userInput = scan.next();
for (int i = 0; i<definitions.length-1;i++){
if(userInput.contentEquals(definitions[i].term)){
System.out.println(definitions[i].definition);
Hope that logic kinda makes sense. Good luck on the task! (Have a look at the athletes tutorial example :) )

java: cannot find a symbol when trying to use .isDigit() [duplicate]

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 5 years ago.
Tried both in my IDE and in the online IDE my textbook on Zybooks.com gives me to work in. My goal is to check whether or not the variable passCode contains a digit. Here's the code:
public class CheckingPasscodes{
public static void main (String [] args) {
boolean hasDigit = false;
String passCode = "";
int valid = 0;
passCode = "abc";
if (passCode.isDigit(passCode.charAt(0)) || passCode.isDigit(passCode.charAt(1)) || passCode.isDigit(passCode.charAt(2))) {
hasDigit = true;
}
if (hasDigit) {
System.out.println("Has a digit.");
}
else {
System.out.println("Has no digit.");
}
}
}
I get the error on line 9 (where the first if starts):
java: cannot find symbol
symbol: method isDigit(char)
location: variable passCode of type java.lang.String
Tried changing passCode.charAt(0) (or 1 and 2) to simply 'a' (or 'b' and 'c') to test whether it was because I was putting a method inside another method, but I seem to get the same error.
I eventually solved the problem by asking a friend, who provided me this, instead:
char s = passCode.charAt(0);
char s1 = passCode.charAt(1);
char s2 = passCode.charAt(2);
if ((s>'0' && s<'9') || (s1>'0' && s1<'9') || (s2>'0' && s2<'9')) {
hasDigit=true;
}
It makes perfect sense, and I did think of doing something similar, but the chapter in which this exercise is isn't about .charAt()—we covered that before—but rather about .isDigit() and other character operations, so doing what I did is all but cheating.
This is driving me nuts.
P.S.: I'm pretty new to Java, so, if the answer is something really obvious, I'm really sorry. And thanks for taking your time to read all this!
You're calling .isDigit() on a String object, which doesn't have such a method. It's a static method of the Character class.
Character.isDigit(passCode.charAt(0));
A big hint is that your error message stated the following:
location: variable passCode of type java.lang.String
which should automatically prompt you to look at the String class for the documentation on whatever method you're looking for - and, subsequently, to discover it doesn't have such a method.
java.lang.String doesnt have a isDigit method, that is only for Char class...
use it as
boolean hasDigit = Character.isDigit('1');

Illegal start of type/expression (Bracket placement help?)

So I'm very new to java and I'm trying to write a program that will print a correct fine for overdue books. I've read multiple questions like this and most of them involve misplacement of curly brackets, but I cannot find a bracket error anywhere. I keep getting multiple errors in my program, but most of the read "illegal start of type" or "illegal start of expression" Could someone help me with my code/give me some tips on bracket placement?
Here is my code:
public class BookFine
{
public static void main(String[] args)
{
int daysLate = 0;
int bookCost = 0;
int result = 0;
System.out.print("Enter how many days your book is overdue: ");
int daysLate = IO.readInt();
System.out.println("Days Late = " + daysLate);
System.out.print("How much does your book cost(enter in cents): ");
int bookCost = IO.readInt();
System.out.println("Book Cost = " + bookCost);
if (daysLate=<7)
{
result=daysLate*10;
}
else
if(daysLate>7)
{
result=(daysLate-7)*20+70;
}
if(daysLate>90)
{
result= bookCost+1000;
}
IO.outputStringAnswer(result);
}
}
There is an issue regarding declaring variable twice in the program. I have corrected the code. Please refer below code.
public class BookFine {
public static void main(String[] args)
{ int daysLate = 0;
int bookCost = 0;
int result = 0;
System.out.print("Enter how many days your book is overdue: ");
daysLate = IO.readInt();
System.out.println("Days Late = " + daysLate);
System.out.print("How much does your book cost(enter in cents): ");
bookCost = IO.readInt();
System.out.println("Book Cost = " + bookCost);
if (daysLate<=7)
{
result=daysLate*10;
}
else
if(daysLate>7)
{
result=(daysLate-7)*20+70;
}
if(daysLate>90)
{
result= bookCost+1000;
}
IO.outputStringAnswer(result);
}
}
You appear to have no brackets for your else branch
else
if(daysLate>7)
{
result=(daysLate-7)*20+70;
}
if(daysLate>90)
{
result= bookCost+1000;
}
Should be
else
{
if(daysLate>7)
{
result=(daysLate-7)*20+70;
}
if(daysLate>90)
{
result= bookCost+1000;
}
}
There were several errors in the code I was able to identify.
first the expression:
if(daysLate=<7)
is backwards. It should read
if(daysLate<=7)
Next, at the start of the code just under main you are declaring your variables "daysLate, bookCost". Then, after your line:
System.out.print("Enter how many days your book is overdue: ");
you are redeclaring the variables as:
int DaysLate
Remove the "int" portion on both daysLate and bookCost and it should run fine assuming you have an IO class defined somewhere.
There's a few problems here.
daysLate=<7; I assume that you mean to use the <= operator. Fixing this will resolve the specific error you're asking about
int daysLate = IO.readInt();; The problem with this line is that you've already declared a variable named 'daysLate'. This can be fixed in one of two ways: either remove the 'int' at the start of this line, or remove the original declaration on line 4. (I prefer the former.)
IO.readInt(); there is no class named IO, at least not in terms of what's imported by your code. There are a number of different ways that you can read input from the keyboard, however. If this is your intent (and it appears like it is), you might want to look up the documentation and examples for the java.util.Scanner class. I repeat, there are more than one ways to accomplish this, even if you don't want to use Scanner, so pick your poison :)
IO.outputStringAnswer(result); Same as #3, except that this time it looks like you're trying to output the result somewhere. Perhaps System.out.println() is in order here.
int bookCost = IO.readInt(); Same as #2 and #3. 'bookCost' is already defined in this scope, so you don't need to declare it again (remove 'int'). And again, you will need to write working keyboard input.
Finally--and this isn't an error per se--you should work on your Indent Style. It will greatly help your code readability, which will in turn help you write better code. Code that you and your colleagues enjoy reading is good (and hopefully healthy) code. Most developers these days use the 1TBF style, from my experience.
Oh, and Welcome to Java!

Java - Scanner not asking for input, and then crashing

I am trying to get input from the Scanner class, but every time I call it, it crashes the entire program. When trying to catch the exception and print the message, nothing shows up, so I am not even sure what the root of the problem is. Some background info is that this class is being called by the main method, which also has a Scanner that was running, but is closed before this class's method is called.
public class UserHandler {
static Scanner userInput1 = new Scanner(System.in);
static void addInterface() throws IOException, FileNotFoundException{
boolean addMore = true;
while(addMore){
System.out.println("Please enter restaurant name: ");
String name = userInput1.next();
if(!FileHandler.containsName(name)){
System.out.println("Name already exists!");
}else{
String[] tags = new String[5];
System.out.print("\nPlease enter tags seperated by spaces: ");
for(int i = 0; i < tags.length; i++){
if(userInput1.hasNext()){
tags[i] = userInput1.next();
}
else{
break;
}
}
FileHandler.addName(name,tags);
}
}
}
}
I have tried several times, and was not able to reproduce this issue. I am assuming it is something to do with syntax, or something that is just not called properly. Either way I have spent quite some time trying to fix it, but to no avail.
I suppose that you get the access to the command-line from the first call to the Scanner(System.in), then you close it and when you try to access it the second time you receive IllegalStateException.
Try to use the same instance of the Scanner(System.in) in both situation.
For more info refer to http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

why's this program giving a runtime error on jcreator but not on netbeans?

This is my solution for sphere's online judge palin problem. It runs fine on Netbeans, but the judge is rejecting my answer saying it gives a RuntimeError. I tried it on JCreator and it says:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:468)
at java.lang.Integer.parseInt(Integer.java:497)
at Main.main(Main.java:73)
I'm not passing an empty string for it to parse, why is this?
The code:
import java.io.*;
import java.util.*;
class Main {
public static int firstPalinLargerThanNum(int num){
int foundPalin =0;
int evalThisNum = ++num;
while (true){
if (isPalin(evalThisNum))
break;
evalThisNum++;
}
foundPalin = evalThisNum;
return foundPalin;
}
public static boolean isPalin(int evalThisNum){
boolean isItPalin = false;
int dig=0;
int rev=0;
int n = evalThisNum;
while (evalThisNum > 0)
{
dig = evalThisNum % 10;
rev = rev * 10 + dig;
evalThisNum = evalThisNum / 10;
}
if (n == rev) {
isItPalin=true;
}
return isItPalin;
}
public static void main(String args[]) throws java.lang.Exception{
BufferedReader r1 = new BufferedReader(new InputStreamReader(System.in));
/*BufferedReader r1 = new BufferedReader (new FileReader(new File ("C:\\Documents and Settings\\Administrator\\My Documents\\NetBeansProjects\\Sphere\\src\\sphere\\sphere\\PALIN_INPUT.txt")));*/
String read = r1.readLine();
int numberOfTestCases = Integer.parseInt(read);
for (int i=0; i<numberOfTestCases;i++){
read = r1.readLine();
if (read!=null){
int num = Integer.parseInt(read);
System.out.println(firstPalinLargerThanNum(num));
}
}
}
}
Input:
2
808
2133
line 73 is: int num = Integer.parseInt(read);
You will get that error if you hit <Enter> when the program is expecting a number.
Suppose your input is
2
3
<Enter>
You will receive the error you have indicated after processing the number 3, as you have told your routine to iterate twice.
As an aside, on top of error handling around the number parsing, you might also want to introduce a trim() to the readLine() method calls:
String read = r1.readLine().trim();
This will allow you to handle gracefully the input in the event that the user to put in whitespace around the numbers.
Just a wild guess: Could there be a problem with different end-of-line separators.
E.g. your program actually gets 2<CR><LF>808<CR><LF>2133<CR><LF>, thinks that the line ends at the <CR> and processes the line.
Now when it tries to process the next line it finds <LF> which makes it think it read an empty String.
You cannot assume that the user knows how to use your program and will give you correct input. The judge probably hit enter, without typing any number. How is he/she supposed to know the input that your program requires? A program should fail gracefully, not blow up in the user's face with cryptic errors.
You should be doing something like the following, so that the user knows what to do:
private static function readInt(BufferedReader reader) throws IOException
{
boolean done = false;
int result = -1;
while ( ! done ){
System.out.print("Please enter an integer: ");
String str = reader.readLine();
try{
result = Integer.parseInt(str);
done = true;
}catch(NumberFormatException cantconvert){
System.out.println("That isn't an integer. Try again.");
}
}
return result;
}
Additionally, you shouldn't use an exception specifier with the main function (that is, don't use "throws" in the signature of "main"). You should handle those IOExceptions and print a pretty and intelligible message to the user, even if there is nothing you can do about the exception to fix it or make it go away.
I just ran your example code under Eclipse 3.4 without error. I was only able to induce a similar error when I did not provide the specified number of test cases, i.e.:
6
56
87
[Enter]
So I am inclined to agree with akf that there must be an extra Enter happening somewhere, because this error will only be generated when there are insufficient lines of input.

Categories

Resources