NoClassDefFoundError when using class - oop

I am learning Java from scratch. I installed the JDK, and I got the Hello World Program running. I am trying to run a simple accountdemo program. In Account.java, I have :
public class Account
{
protected double balance;
// Constructor to initialize balance
public Account( double amount )
{
balance = amount;
}
// Overloaded constructor for empty balance
public Account()
{
balance = 0.0;
}
public void deposit( double amount )
{
balance += amount;
}
public double withdraw( double amount )
{
// See if amount can be withdrawn
if (balance >= amount)
{
balance -= amount;
return amount;
}
else
// Withdrawal not allowed
return 0.0;
}
public double getbalance()
{
return balance;
}
}
On compiling this, I got the Account.class. In accountdemo.java, I have this
class AccountDemo
{
public static void main(String args[])
{
Account my_account = new Account();
my_account.deposit(250.00);
System.out.println("Current balance " + my_account.getbalance());
my_account.withdraw(80.00);
System.out.println("Remaining balance" + my_account.getbalance());
}
}
On compiling this, I got AccountDemo.class. But, when I try to run this as an application, I get the error java.lang.NoClassDefFoundError:
C:\Users\roymustang/NT\Documents\javaprogram\accountdemo/java
I have set the classpath to : C:\Users\roymustang.NT\Documents\javaprogram
Am I missing anything obvious? Like mismatched uppercase or something?
EDIT : Not homework, just trying to learn.
I am using Textpad, http://www.textpad.com/ . It has an option run commands. So, I have configured it to run javac.exe (C:\Program Files\SDK\jdk\bin\javac.exe $File $FileDir)
and run as application by java.exe ( C:\Program Files\SDK\jdk\bin\java.exe $File $FileDir)

Hi there I'll assume that you are trying to run this using no java IDE e.g. Eclipse or Netbeans. I tested your code and they worked just fine.
C:>java AccountDemo
Current balance 250.0
Remaining balance170.0
Your error Message is:
java.lang.NoClassDefFoundError:
C:\Users\roymustang/NT\Documents\javaprogram\accountdemo/java
meaning you used:
java accountdemo
to run your program. Remember that Java is case sensitive this can be corrected by using this.
java AccountDemo
Happy Coding ^_^

Related

Intellij intention 'Creates missing switch branches' not working

Intellij's 'Creates missing switch branches' intention seems not to be working for me. I have enabled/disabled/enabled it with restarts of intellij, but I never get the alt-enter possibility to create a completed switch statement.
Am I missing something? I'm working with the latest version of intellij ultimate.
Here's an example that works :
class SwitchBranches {
public static final int ONE = 1;
public static final int TWO = 2;
public static final int THREE = 3;
void x(#MagicConstant(intValues = {ONE, TWO, THREE}) int i) {
switch (i) { // position the text caret on the `i` expression or on the switch keyword
}
}
}
If you need this functionality to create a switch statement for enum values, use the Enum 'switch' statement that misses case inspection. It is enabled by default at the "No highlighting, only fix" level. Example:
enum EnumExample {
A, B, C;
void x(EnumExample e) {
switch (e) {
}
}
}

How to use ByteBuddy in a java project

I made a simple project of java to test ByteBuddy . I typed exactly the same code in a tutorial made by Rafael Winterhalter but it showing some errors
1) ByteBuddyAgent cannot be resolved.
2) type cannot be resolved to a variable.
3) builder cannot be resolved.
4) method cannot be resolved to a variable.
I added the byte-buddy-1.7.1.jar as a referenced library.
public class LogAspect {
public static void main(String[] args){
premain("", ByteBuddyAgent.installOnOpenJDK());
Calculator calculator = new Calculator();
int sum = calculator.sum(10, 15, 20);
System.out.println("Sum is "+ sum);
}
public static void premain(String arg, Instrumentation inst){
new AgentBuilder.Default()
.rebase(type -> type.getSimpleName().equals("Calculator"))
.transform((builder, typeDescription) -> builder
.method(method -> method.getDeclaredAnnotations().isAnnotationPresent(Log.class))
.intercept(MethodDelegation.to(LogAspect.class).andThen(SuperMethodCall.INSTANCE)))
.installOn(inst);
}
public static void intercept(#Origin Method method){
System.out.println(method.getName()+" is called.");
}
}
#interface Log{
}
class Calculator {
#Log
public int sum(int... values) {
return Arrays.stream(values).sum();
}
}
It looks like you are using a very outdated tutorial of the 0.* ara. Use an IDE to check your compile-time errors and check the webpage for more recent tutorials.

How can I have #After run even if a cucumber step failed?

We have several cucumber step definitions that are modifying the database which would mess up the test afterwards if it doesn't get cleaned up after the test runs. We do this by having a function with the #After annotation that will clean things up.
The problem is that if there's a failure in one of the tests, the function with #After doesn't run, which leaves the database in a bad state.
So the question is, how can I make sure the function with #After always runs, regardless if a test failed or not?
I saw this question, but it's not exactly what I'm trying to do, and the answers don't help.
If it helps, here is part of one of the tests. It's been greatly stripped down, but it has what I think are the important parts.
import static org.hamcrest.MatcherAssert.assertThat;
import cucumber.api.java.After;
public class RunMacroGMUStepDefinition
{
#Autowired
protected ClientSOAPRecordkeeperInterface keeper;
#Given( "^the following Macro exists:$" )
#Transactional
public void establishDefaultPatron( final DataTable dataTable )
{
for ( final DataTableRow dataTableRow : dataTable.getGherkinRows() )
{
// Stuff happens here
keeper.insert( macroScriptRecord );
}
}
#After( value = "#RunMacroGMU" )
#Transactional
public void teardown()
{
for ( int i = 0; i < macroScripts.size(); i++ )
{
keeper.delete( macroScripts.get( i ) );
}
}
// Part of #Then
private void compareRecords( final String has, // Other stuff )
{
// Stuff happens here
if ( has.equals( "include" ) )
{
assertThat( "No matching data found", foundMatch, equalTo( true ) );
}
else
{
assertThat( "Found matching data", foundMatch, equalTo( false ) );
}
}
}
I personally use Behat (The PHP dist of Cucumber), and we use something like this to take screenshots after a failed test. Did a bit of searching, and found this snippet in Java, that may help with this situation.
#After
public void tearDown(Scenario scenario) {
if (scenario.isFailed()) {
(INSERT FUNCTIONS YOU WOULD LIKE TO RUN AFTER A FAILING TEST HERE)
}
driver.close();
}
I hope this helps.

What are "watches" in IntelliJ and how to use them?

When I debug an app, in the debug tool window there is a Watches window. I have read this manual over and over, but cannot find any practicle usage of Watches.
Somehow, I think this is a cool and useful tool and I lack from not using it.
Can someone explain when should I use it and give a few samples? Ideally, the description will be bound to a concrete (imaginary) situation so that I better apply it in my work.
This section allows you to define expressions which you'd like to see how they evolve/change with every step of your debug process, without manually inspecting all the available objects and their properties. Let's take the following simple sample which intentionally throws a NullPointerException (NPE):
public class WatchSample {
static class Student {
public static final int CREDITS_REQUIRED_FOR_GRADUATION = 10;
private String name;
private Integer credits;
public Student(String name, Integer credits) {
this.name = name;
this.credits = credits;
}
String getName() {
return name;
}
public boolean hasGraduated() {
return credits >= CREDITS_REQUIRED_FOR_GRADUATION;
}
public Integer getCredits() {
return credits;
}
}
public static void main(String[] args) throws Exception {
List<Student> students = simulateReadingFromDB();
for (Student student : students) {
if (student.hasGraduated()) {
System.out.println("Student [" + student.getName() + "] has graduated with [" + student.getCredits() + "] credits");
}
}
}
private static List<Student> simulateReadingFromDB() {
List<Student> students = new ArrayList<>(3);
students.add(new Student("S1", 15));
students.add(new Student("S2", null)); // <- simulate some mistake
students.add(new Student("S3", 10));
return students;
}
}
At some point in time you may wonder how come you get a NPE and what needs fixing. So just set a breakpoint, add a few watches and carefully step through the lines. Eventually you'll end up with the troublemaker in sight:
Of course this is a basic example and should be taken as such. Within a regular app you'll probably have more complex scenarios and expressions you'd like to inspect, and this will make more sense, for example: if (((position > 0 && position < MAX) || (position < 0 && position > MIN) && (players(currentPlayer).isNotDead() && move.isAllowed()) && time.notUp())..... In this case you can evaluate the sub-expressions to see which one returns false
**Note**: You could also make the breakpoint conditional so that the program will pause only when that specific event occurs:

unresolved token - c++

I am trying to solve a lesson in my study. I am going to have an abstract class, CFigure, on top and different figures below, currently I have made a circle class. I am going to call this from a C# program.
But when I try to build my code I get the following error messages:
unresolved token (06000001) arealBeregnerCPP.CFigure::area
unresolved token (06000002) arealBeregnerCPP.CFigure::circumference
2 unresolved externals
I hope anyone can give me a hint in what I do wrong... Thanks!
This is my program:
// arealBeregnerCPP.h
#pragma once
using namespace System;
namespace arealBeregnerCPP {
public ref class CFigure
{
public:
virtual double area();
virtual double circumference();
};
public ref class CCircle : public CFigure
{
private:
double m_radius;
public:
CCircle(double radius)
{
m_radius = radius;
}
virtual double area() override
{
return 0; //not implementet
}
virtual double circumference() override
{
return 0; //not implementet
}
};
}
if CFigure::area() and CFigure::circumference() are abstract functions then put = 0 in declaration:
virtual double area() = 0;
virtual double circumference() = 0;
Probably you haven't defined area and circumference.
Since you fail to present complete code there are some other possibilities, such as failing to link with the relevant files.
By the way, please don't tag c++/cli questions as c++. Microsoft's c++/cli is not c++. It's a language similar to c++, but it's not c++.
Cheers & hth.,