Reached end of file while parsing compilation error - parsing

I am a java programming beginner. What did i do to get the error: reached end of file while parsing
import java.util.Scanner;
class eng{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String value;
String direct = "answer true or false to the following statement.";
String ques = "Twelve is greater than seven";
System.out.println(direct);
System.out.println(ques);
value = input.nextLine();
if ((value = "true")) {
System.out.println("you are correct");
} else {
System.out.println("you are wrong my friend");
}
}

Add Another "}" at end of your code you missed one
2.There is another error in your code
if((value = "true"))
is not a proper way to check string equality and has syntax error it should be
if(value.equals("true"))

You're simply missing a closing brace }. From what the compiler sees you never closed the brace after class eng{

Please re-indent/re-format your code first. Maybe you'll find a missing end brace "}".

Related

String constant reference as value of Annotation attribute causes compile error

I am using my properties file to get the values for #Scheduled annotation attributes.I am able to get the values from properties file but when I tries to pass String constant reference to Annotation attribute then compile time exception is raised.
#Slf4j
#CompileStatic
class TestJobService {
static lazyInit = false
public static String jobInterval = getSomePropertiesFileValues?.fixedRateInMS instanceof String? getSomePropertiesFileValues.fixedRateInMS:'10000'
#Scheduled(fixedDelayString = TestJobService.jobInterval)
void executeEveryTenSeconds() {
def date = new Date()
println date.format('yyyy/MM/dd HH:mm', TimeZone.getTimeZone('IST'))
}
}
Attribute 'fixedDelayString' should have type 'java.lang.String'; but
found type 'java.lang.Object' in
#org.springframework.scheduling.annotation.Scheduled
Then I tried to use String to pass like:
#Slf4j
#CompileStatic
class TestJobService {
static lazyInit = false
#Scheduled(fixedDelayString = '${getSomePropertiesFileValues.fixedRateInMS}')
void executeEveryTenSeconds() {
def date = new Date()
println date.format('yyyy/MM/dd HH:mm', TimeZone.getTimeZone('IST'))
}
}
OR
public static final String jobInterval = getSomePropertiesFileValues?.fixedRateInMS instanceof String? getSomePropertiesFileValues.fixedRateInMS:'10000'
prevents the variable from being treated as an inline constant and compiler complains of not being inline constant.
I understand that using single quote '${getSomePropertiesFileValues.fixedRateInMS}'we can get compiler to know that I want GString behaviour. But I don't know is this a bug in Groovy or its a functionality which I need to implement in some other way to pass the string values as annotation attributes. Any lead or any help is highly appreciable.

Dart: Using Interface gives the error: "isn't a valid override of"

I've created a small interface:
import ...
abstract class IController {
void navigateTo(BuildContext context, String routeName);
Future<LocationData> get location;
// registration process
void registerGender(Gender gender);
void registerBirthday(DateTime birthday);
Future<bool> register(String email, String password);
}
And then I tried to implement this:
import ...
class Controller implements IController {
static final Controller _instance = Controller._internal();
final ServiceAuthenticate _serviceAuth = ServiceAuthenticate();
final ServiceDatabase _serviceDb = ServiceDatabase();
final ServiceGPS _serviceGPS = ServiceGPS();
User _user;
String _routeName;
UserData _userData;
Controller._internal() {
this._routeName = ROUTE_WELCOME;
}
factory Controller() => _instance;
void navigateTo(BuildContext context, String routeName) {
this._routeName = routeName;
Navigator.pushReplacementNamed(context, routeName);
}
Future<LocationData> get location async{
this._userData.location = await this._serviceGPS.location;
print(this._userData.location);
return this._userData.location;
}
void registerGender(Gender gender){
this._userData = UserData();
this._userData.gender = gender;
}
void registerBirthday(DateTime birthday) {
this._userData.birthday = birthday;
}
Future<bool> register(String email, String password) async {
User user = await this._serviceAuth.registerWithEmailAndPassword(email, password);
if(user == null){
return false;
}
this._user = user;
return true;
}
}
But that code produces the following error:
error: 'Controller.navigateTo' ('void Function(BuildContext, String)') isn't a valid override of 'IController.navigateTo' ('void Function(dynamic, String)'). (invalid_override at [prototype] lib\controller\controller.dart:30)
It looks like Dart thinks, that the BuildContext in the IController is dynamic, but this is obviously not the case.
How can I fix this? I'm new to Dart and don't know what to do.
Thanks for help :)
I'm stupid.
My import statement was wrong.
The line
import 'package:prototype/Controller/IController.dart';
produced this error, because the folder controller starts with a lowercase Letter.
The correct import statement is
import 'package:prototype/controller/IController.dart';
But regardless of my stupid mistake is the error message quite interesting.
A had a similar error and in my case the problem was that the return type of the buggy function was such that there were two different classes in the codebase with the same name. And the interface was using one and the implementation the other.
The one line answer is :
Your import statement is wrong.
But now , you need to take care in which file the import statement is going wrong.
There can be many scenarios, but I would like to give an example where I was stuck.
I had two different files in different package, but both files were importing some method where the method names were same.
So while importing the file which contain this method, I had imported the same name method from one file, and at other place, the same name method from second file.
So that's where everything went wrong!
So if import file is correct in the file which is giving some error, check the other dependent file, where same method import statement is written, that may be wrong.

Unit test case for Domain class ( testing constraints) - Grails

I am actually new in the world of Grails. I am trying to write a test case for domain class which is having some constraints . I am getting a Null pointer exception on my object when i am trying to run my unit test. On debugging I got to know that there is something fishy with my toString method which is causing the object to set as Null. How should I move ahead ? Any help is highly appreciated.
Here is my domain class:
#MultiTenant
class OrderCharge {
static scaffold = [
exclude: ['tenantId'],
]
static belongsTo = [
order: SalesOrder
]
MiscOrderCharges miscOrderCharges
Date lastUpdated
double quantity
double price
SapInvoiceRecord sapInvoice
static constraints = {
order(nullable: true)
quantity(min:1d)
miscOrderCharges()
sapInvoice(nullable: true)
}
String toString(){
def pattern = "\$##,###.00"
def currency = new DecimalFormat(pattern)
String rate = currency.format(miscOrderCharges.price)
return "$miscOrderCharges x$quantity"
}
}
Here is my Unit test case:
import grails.test.mixin.TestFor
import spock.lang.Unroll
import spock.lang.Specification
#TestFor(OrderCharge)
//#TestMixin(GroovyPageUnitTestMixin)
class ChargeSpec extends Specification {
def setup() {
mockForConstraintsTests(
OrderCharge, [
new OrderCharge(order: Mock(SalesOrder),
miscOrderCharges: Mock(MiscOrderCharges),
quantity: 1.0,
price:20.0
/*, sapInvoice: Mock(SapInvoiceRecord) */
)
]
)
}
void validateConstraints(obj, field, error) {
def validated = obj.validate()
if (error && error != 'valid') {
assert !validated
assert obj.errors[field]
assert error == obj.errors[field]
} else {
assert !obj.errors[field]
}
}
#Unroll("test inventory all constraints #field is #error")
def "test Charge all constraints"() {
given:
def obj = new OrderCharge("$field": val)
expect:
validateConstraints(obj, field, error)
where:
error |field |val
'nullable' |'orderCharge' |null
'nullable' |'sapInvoice' |null
'min' |'quantity' |-1
'min' |'price' |0
}
}
Thanks in advance.
The only thing that jumps out at me is your return in the toString().
return "$miscOrderCharges x$quantity"
You're using gStrings there. It's my understanding that individual variables can be referred to using simple $ notation, as in the format $somevariable, whereas expressions are in the format ${expression}.
In your statement x$quantity seems like a typo. Did you mean to multiply them as an expression like below?
return "${miscOrderCharges * quantity}"
See http://groovy.jmiguel.eu/groovy.codehaus.org/Strings+and+GString.html for more information.

Error: cannot find symbol -- EC=Character.parseChar(JOptionPane.showInputDialog("enter employee code"));

My professor said that we need to input a letter to the dialog box in order for regular, probation etc. to show. I don't know how to resolve this problem. Is there something wrong? I'm new to java.
Here's my code:
import javax.swing.*;
public class EmployeeCode_input
{
public static void main (String[]args)
{
char EC;
EC=Character.parseChar(JOptionPane.showInputDialog("enter employee code"));
if ((EC=="R")&&(EC=="r"))
System.out.println("Regular");
else if((EC=="P")&&(EC=="p"))
System.out.println("Probationing");
else if((EC=="T")&&(EC=="t"))
System.out.println("Trainee");
else if ((EC=="C")&&(EC=="c"))
System.out.println("Contractual");
else
System.out.println("INVALID");
}
}
Character.parseChar is not available in Java.
As chinmay ghag pointed out there is no Character.parseChar in Java. You may use String's charAt() method instead.
Change :
EC=Character.parseChar(JOptionPane.showInputDialog("enter employee code"));
To :
EC=JOptionPane.showInputDialog("enter employee code").charAt(0);
See this for more information: How to convert/parse from String to char in java?
Also if EC is of type char then you shouldn't be comparing char's with strings. ie: EC = 'p' not EC = "p"

Why Logback/Slf4j logs wrong file and line numbers in Groovy?

I have noticed that sometimes Logback/Slf4j logs wrong file and line numbers in Groovy.
I have a lot of bad file/line number logs in my Grails application (more than 50% of all logs)
Is there any workaround?
Simplest example:
logback.groovy
appender("STDOUT", ConsoleAppender) {
encoder(PatternLayoutEncoder) {
pattern = '%d{HH:mm:ss.SSS} [%-5level] %msg \\(%file:%line\\)%n'
}
}
root(DEBUG, ["STDOUT"])
Test.groovy
#Slf4j
class Test {
static void main(String[] args) {
log.info("${'Wrong file and line number!'}")
}
}
Output
23:24:23.894 [INFO ] 0 Wrong file and line number! (NativeMethodAccessorImpl.java:-2)
Example of my grails log output with problem
10:16:44.881 [DEBUG] [org.grails.plugin.resource.ResourceProcessor] -------------------------------------------------- (null:-1)
The problem occurs when a GString is logged (any normal String logs the correct line number). I have no clue why it works like this but I have found two workarounds: Either convert GString to String by calling the toString() method (ugly) or use template format with parameters
import groovy.util.logging.Slf4j;
#Slf4j
class Test {
static void main(String[] args) {
def x = 1
log.info("Does not work: ${x}")
log.info("Works ${x}".toString())
log.info("Works {}", x)
}
}

Resources