".class" error in Java - java

I am trying to run this program but I cannot, the compiler is sending me a ".class" error.
Can somebody help me with my problem and if it is possible a general tip about ".class" error?
Here is the program:
import java.io.*;
class Bus
{
private int kostos;
private int plithos;
private int typepiv;
Bus(int x,int y,int z)
{
kostos=x;
plithos=y;
typepiv=z;
}
public void KB(int[] x)
{
try{
for(int i=1;i<5;i++)
{
if(typepiv==2)
{
plithos=plithos+plithos/2;
kostos=kostos-kostos/2;
}
if(typepiv==3)
{
plithos=plithos-plithos/5;
kostos=kostos-kostos*25/100;
}
if(typepiv==1)
{
plithos=plithos;
kostos=kostos;
}
x[i]=plithos*kostos;
}
} catch(Exception ex){
ex.printStackTrace();
}
}
}
class testBus
{
public static void main(String args[])
{
String leof[]=new String[4];
int leof1[][]=new int[4][3];
for(int i=1;i<5;i++)
{
System.out.println("dwste onoma leoforiou");
leof[i]=UserInput.getString();
System.out.println("dwste kostos thesis enilika");
leof1[i][1]=UserInput.getInteger();
System.out.println("dwste plithos thesewn");
leof1[i][2]=UserInput.getInteger();
System.out.println("dwste tupos epibath gia enilikes=1,gia
paidia=2,gia suntaksiouxous=3");
leof1[i][3]=UserInput.getInteger();
Bus leof2=new Bus(leof1[i][1],leof1[i][2],leof1[i][3]);
}
int KostEnoik[]=new int[4];
----->leof2.KB(KostEnoik);
System.out.print("onoleo");
System.out.print(" ");
System.out.print("plithos");
System.out.print(" ");
System.out.print("kost(EURO)");
System.out.print("typepiv");
System.out.print(" ");
System.out.print("apotelesma kostEnoik");
for(int g=1;g<5;g++)
{
System.out.print(leof[g]);
System.out.print(leof1[g][2]);
System.out.print(leof1[g][1]);
System.out.print(leof1[g][3]);
System.out.print(KostEnoik[g]);
}
}
}
the compiler message says :
testBus.java:56:error:cannot find symbol
leof2.KB(KostEnoik);
symbol:bariable leof2
location:class testBus
1 error

Remove the array brackets [] when invoking KB
leof2.KB(KostEnoik);
and remove the preceding enclosing brace }.
Aside: Java naming conventions indicate that variables start with a lowercase letter e.g. kostEnoik. Also consider giving the method KB a meaningful name, e.g. calculateCost
Read Java naming conventions

concern is with your access
leof2.KB(KostEnoik[]);
You are trying to access the "leof2" variable outside of the scope in which it is defined i.e. outside for loop and scope is upto for loop and that's why the compiler will not be able to find that varialble .

leof1[i][3]=UserInput.getInteger();
Bus leof2=new Bus(leof1[i][1],leof1[i][2],leof1[i][3]);
}
int KostEnoik[]=new int[4];
leof2.KB(KostEnoik[]);
You are trying to access the "leof2" variable outside of the scope in which it's defined (in this particular case, the for loop) and that's not allowed.
method KB takes an int array as argument, but you don't have to add the [] when passing the argument. The correct line is
leof2.KB(KostEnoik);
However, there's something pretty odd with you logic: you're repeatedly (for loop) setting leof2, but only the last iteration of the loop will have any effect. I'm almost certain that that's not what you actually want, but the correct answer to where Bus leof2 should actually be defined depends on the correction of that issue.

leof2.KB(KostEnoik); this is the main culprit. whether you have imported UserInput.
Also try to go through the Java Basics
any method can be invoked using object when it is non static or class name when it is static. Please consider this link

Get leof2 object out side the For Loop.
Don't type [] when you pass the array as argument "leof2.KB(KostEnoik[]);".

Related

How to deal with an unitialized constructor in an if statement (Java)

I've run into a problem where I attempt to define a constructor in the first part of a switch/case statement, and then I can't run the code because the program can't get the definition later.
The idea behind passing the constructor information from a switch/case function is that the user chooses what to do, but for some options, one must be done before the other is possible (e.g. Create password and Check password).
If I try doing it this way, it throws a VarMayNotHaveBeenInitialized error (I get the sense the answer is in a try/catch statement, but I don't know enough about them to be sure). I've included some code that is what I've been essentially trying to do below. (The two classes are to best simulate the project I'm working on.)
Any help is appreciated! : )
TestMain.java:
package exitTest;
public class TestMain {
InitializeTest init;
public static void main(String[] args) {
while (true) {
String x = InitializeTest.askQuestion();
switch (x) {
case "set":
InitializeTest init = new InitializeTest();
break;
case "get":
if (init != null) {
init.showExample();
} else {
System.out.println("Error: init not initialized.");
} break;
}
}
}
}
InitializeTest.java:
package exitTest;
import java.util.Scanner;
public class InitializeTest {
static Scanner in = new Scanner(System.in);
public InitializeTest thing1;
public String example;
public static String askQuestion() {
System.out.println("set for set example\nget for check example");
String action = in.nextLine();
return action;
}
public InitializeTest() {
System.out.println("Input string:");
String example = in.nextLine();
}
void showExample() { System.out.println(example); }
}
You include the type when you're declaring variables, not when simply assigning to an existing one. When you write
InitializeTest init = new InitializeTest();
That makes a new init variable, unrelated to the previous one, which stores the newly constructed object. That new variable shadows the existing one, but it gets released after the switch block is over (variables in Java are block-scoped).
To put it to an analogy, it's as though you wanted to tell your friend Alice a secret. But when you went to her house, her neighbor whose name is also Alice happened to be there instead. If you tell that Alice your secret, then your friend doesn't find out. Even though the two happen to share a name, they don't share any memory.

Is there a way to force a variable out of existence in Java?

Basically, my goal is to be as efficient as possible by "deleting" variables when I'm done with them, even if still in scope. So far, I've been using if(true) to manually create a scope that defines the lifetime of variables, but I'm looking for something like, var.close(), a function that's only purpose is to cause a variable to essentially go out of scope and no longer have a memory location reserved for it.
The example I use below could obviously use for() to sidestep this particular instance(the assignment wants me not to use for()), but my concern is wider than variables used as indexes.
(ignore any other logic/syntax errors present, as I haven't proofread this yet)
package root;
import javax.swing.JOptionPane;
public class DebugEight4
{
public static void main(String[] args)
{
String array[] = new String[100];
String entry = " ";
final String STOP = "/']";
StringBuffer message = new StringBuffer(
"The words in reverse order are:\n"
);
if(true)
/*
*forces x out of scope
* after while statement ends
*/
{
int x = 0;
while(!entry.equals(STOP))
{
entry = JOptionPane.showInputDialog(null,
"Enter another word\n" +
"Enter " + STOP + " when you want to stop");
if(!entry.equals(STOP) && x != 100)//prevents fragmentation error
{
array[x] = entry;
}
else
{
JOptionPane.showMessageDialog(null, "That\'s all! Let's see the results.");
}
++x;
}
}/* end x scoping if
* If the if(true) wasn't here, x would still exist!
*/
for(int y = array.length-1; y > 0; --y)
{
message.append(array[y]);
message.append("\n");
}
JOptionPane.showMessageDialog(null, message);
}
}
Any thoughts?
This is exactly what scopes are for. You don't need to invent your own scoping system. Any variable should be declared in the smallest possible enclosing scope. But that's as far as you need to go with this. It is a visibility principle, not an efficiency principle, as all the stack needed for a method is allocated on entry to the method, and inner scopes don't correspond to bytecode instructions in any way.
To create a more-limited scope is easy enough. Just create a new block:
public static void whatever() {
int a = 5; // Exists until end of method
{
int b = 5; // Exists until end of outer block
{
int c = 5; // Exists until end of inner block
}
// c is no longer accessible
}
// b is no longer accessible
}
I'd recommend against this for a few reasons:
It's harder to read for little gain
The compiler or JIT can automatically figure out the lifetime of variables and automatically handle what you're attempting to do
You can't overlap variable lifetimes this way (nesting means that the most-nested variable must expire off the stack before less-nested ones)

Increment the number by 1 whenever i call the funtion in java

I am trying to print the number increment by 1 whenever i call the function, but i am not able to get the solution, below is my code
The blow is the function
public class Functions<var> {
int i=0;
public int value()
{
i++;
return i;
}
}
I am calling the above function here
import Java.Functions;
public class Increment {
public static void main(String[] args)
{
Functions EF = new Functions();
System.out.println(EF.value());
}
}
Whenever i run the program , i am getting only the output as 1 , but i want the output to be incremented by 1 . Could you please help. Thanks in Advance.
I believe your answer is with the scope of your variables and your understanding of them. You only call the method once in your given examples, so 1 is arguably the correct answer anyway. Below is a working example which will persist during runtime one variable and increment it every time a function is called. Your methods don't seem to follow the common Java patterns, so I'd recommend looking up some small example Hello, World snippets.
public class Example{
int persistedValue = 0; // Defined outside the scope of the method
public int increment(){
persistedValue++; // Increment the value by 1
return persistedValue; // Return the value of which you currently hold
// return persistedValue++;
}
}
This is due to the scope of "persistedValue". It exists within the class "Example" and so long as you hold that instance of "Example", it will hold a true value to your incremented value.
Test bases as follows:
public class TestBases {
static Example e; // Define the custom made class "Example"
public static void main(String[] args) {
e = new Example(); // Initialize "Example" with an instance of said class
System.out.println(e.increment()); // 1
System.out.println(e.increment()); // 2
System.out.println(e.increment()); // 3
}
}
If your desire is out of runtime persistence (the value persisting between application runs) then it would be best to investigate some method of file system saving (especially if this is for your Java practice!)
Your main problem is to increment the number value 1.
But you are calling your function only once. Even though you call the function many times you will get the value 1 only because it is not static variable so it will every time initialize to 0.
So please check below answer using static context.
Functions.java
public class Functions{
static int i=0;
public int value()
{
i++;
return i;
}
}
Increment.java
public class Increment{
public static void main(String []args){
Functions EF = new Functions();
System.out.println(EF.value());
System.out.println(EF.value());
System.out.println(EF.value());
}
}
Output:
1
2
3
If you design multi-threaded application, it will be better to use AtomicInteger.
The AtomicInteger class provides you an int variable which can be read and written atomically.
AtomicInteger atomicInteger = new AtomicInteger();
atomicInteger.incrementAndGet();

Am I returning the correct value from my method & am I writing it correctly?

I'll preface my question with the statement that I am very new to Java, so I apologise if my code is totally disgusting to read.
What I'm trying to do: I'm writing a program that takes two integers from the user, a low value and a high value, and sends both integers to two different methods. Method #1 has a simple for loop and should print out all of the numbers between the lowest number and the highest number that are multiples of 3 or 5, and Method #2 does the same except for numbers that are multiples of 3 or 5 it also checks if that number is also a multiple of 6 and, if so, it prints the number and an asterisk next to it.
What I'm having trouble with: I'm pretty stumped on what I need to return from my methods & how to return anything at all. This is the first time I've worked on a method properly (just moved up from "Hello World) and from what I can see I don't really need to return anything at all. All the code that I've put in my methods pretty much complete the program, so I thought maybe returning the integers I sent would be enough, apparently it's not. So, without further ado, here's my code.
The Error:
javac BonusQ.java
.\MethodOne.java:19: error: illegal start of type
return(int lowestRange, int highestRange);
^
.\MethodTwo.java:36: error: illegal start of type
return(int lowestRange, int highestRange);
^
The Main:
import java.util.Scanner;
public class BonusQ
{
public static void main(String [] args)
{
Scanner scan = new Scanner(System.in);
int lowestRange = 0;
int highestRange = 0;
System.out.println("Enter the lowest integer in your range");
lowestRange = scan.nextInt();
System.out.println("Enter the highest integer in your range");
highestRange = scan.nextInt();
MethodOne.NoAsterisk(lowestRange, highestRange);
MethodTwo.Asterisk(lowestRange, highestRange);
}
}
MethodOne:
public class MethodOne
{
public static int NoAsterisk(int lowestRange, int highestRange)
{
for(int i = lowestRange; i <= highestRange; i++)
{
if (i%5 == 0)
{
System.out.println(i);
}
else if (i%3 == 0)
{
System.out.println(i);
}
}
}
return(int lowestRange, int highestRange);
}
MethodTwo:
public class MethodTwo
{
public static int Asterisk(int lowestRange, int highestRange)
{
for(int i = lowestRange; i <= highestRange; i++)
{
if (i%5 == 0)
{
if (i%5 == 0 && i%6 == 0)
{
System.out.println(i + "*");
}
else
{
System.out.println(i);
}
}
else if (i%3 == 0)
{
if (i%3 == 0 && i%6 == 0)
{
System.out.println(i + "*");
}
else
{
System.out.println(i);
}
}
}
}
return(int lowestRange, int highestRange);
}
Sorry if the post is a bit beefy to read, I just find that adding my thoughts on the code might help you explain to me what's going wrong, seeing as you may not know the extent of my incompetence :)
Thanks in advance.
Ok, Classes have members.
Members are either some variables or arrays of variables
and the methods of a class.
So you got
public class MyMethod
{
public static int Asterisk(int loRange, int hiRange)
{
// Do magic let's make a sum for this example
// You enter loRange and hiRange (you defined it above)
return loRange + hiRange // Here the method returns a result
}
}
// So then....
public static void main(String [] args)
{
// WHATEVER IS IN HERE RUNS ALWAYS FIRST.
z = Asterisk(1,2); // 1 and 2 is lo and hi range values ;)
// Z has a value of 3 now because Asterisk(1,2) returns 1 + 2
}
See how this works?
Now this works because you use the static definition (meaning there must not be an instance of MyMethod created first to use the method. It's not wrong, but if you can make a program do things with class instances, you better do it that way.
You make an instance of a class, this is called an object, using a special method. This method has the exact name of the Class and constructs an instance of it.
You should study now about constructors, abstract classes etc etc.
I can't say you do it wrong or right either. It is about what the program is all about and you should study the scope for variables and methods, and the encapsulation concept of Object Oriented Programming.
Using only static methods, goes against encapsulation principle, it is possibly wrong but I can't tell for sure.
I hope this helped you and gave you a good direction to go on with your study.
PS:
To return multiple results, you should return an array of variables, not just a variable.
You can also return nothing and just have it do the job to a needed array. This FORCES you though to make this array public. (Not a good practice)
Finally if multiple value returns are needed to just print them on the console... well, just do it in the method, no need to return anything really.
You don't need to return anything, being that the methods are printing out all the values.
You can change them into void methods, for example:
public static void asterisk(int lowest, int highest) {
//loops and if statements
//no return statement!
}
The code in the methods will run and voila, you are done!
EDIT: That being said, there's a lot more than can be done to make this code more Java-like, but for now this will work.
mmmmm...you can return types, and (int lowestRange, int highestRange) its not a type. Look at the method definition
public static int Asterisk(int lowestRange, int highestRange)
the return type is declared as int, so you should return an int value. You can do something like
return lowestRange;
return 1;
with that in consideration, the error should dissapear. The question is, why do you need to return a value? From what i've read, your methods are supose to print stuff, not to return stuff...
The return statements are out of the method. You have to put them before the close method brackets.
public class MyClass{
public int sum (int a, int b){
return a + b;
} // The return have to be before this brackets
}

While loop using Nested if functions/statement

import javax.Swing.JOPtionPane;
public class while looping {
public static void main (String []args){
String a= JOptionPane.ShowInputDialog("Please enter an Integer");
int b=Integer.parseInt(a);
int j=1;
while(j<=b){
j++;
int k=1;
while (k<j){
System.out.print("*");
k++;
}
System.out.println();
}
}
}
}
This is my program and when i run it it says that javac: invalid flag: while what does it mean?
The "invalid flag" is probably related to the way you call the compiler. Do you call the compiler from a command line? How does the call look like?
You also have an error in your code, unrelated to the error message: you call your class "while looping". This is wrong on 2 (or 3) points: a class name must be one word, a class name must not be a reserved word ("while"), and a class name should start with a capital letter.
The last point is just a naming convention, but it makes life easier for everyone who has to read your code.
You can even see your error in your question with the highlighting:
public class while looping {
}
A class name may not contain any blank character.
Also it is usual to start class names with a capital letter.
Please rename your class to
public class WhileLooping {
}
and also rename your .java file accordingly.

Categories