I'm looking for a way to run a cluster of classes under the same package from the command line, but despite successfully compiling, I keep getting "could not load main" errors. I've changed the path and classpath to what they need to be, as well as tried building a subfolder named for the package I'm using ("com.company"), but to no avail. I've tried the following on command line while in the package-named subfolder directory, as well as the folder above that:
>java com.company.myclassname
>java myclassname
>java com\company\myclassname
>java -cp . com.company.myclassname
All have left me with the same "Error: Could not find or load main class".
At this point I've been poring over StackOverflow questions and tutorials for 3 hours to avoid having a repeat question, but I'm desperate. I've got to turn this homework assignment in in two hours. It works just fine within my IDE, and even through my backup beta IDE, but not command line. Can anyone please shed some light on this for me?
Edit: Source code:
package com.company;
import static com.company.myclassname.quantInput;
import static com.company.myclassname.costInput;
public class GroceryList {//This is the parent class for the program.
private static int counter = 0;//Used to ensure that the number of items is limited to ten.
private static GroceryList[] List = new GroceryList[10];//Used to hold the first ten grocery items in the add method.
public GroceryList(){//Basic constructor
}
.... Plus a few methods.
Client code:
package com.company;
import java.io.File;
import java.io.FileNotFoundException;
import java.text.DecimalFormat;
import java.util.Scanner;
public class myclassname {
private static String[] nameInput = new String[10];//for holding names from each line, then gets sent to constructor by index
public static int[] quantInput = new int[10];//for holding quantity from each line, then gets sent to constructor by index
public static double[] costInput = new double[10];//for holding price from each line, then gets sent to constructor by index
public static GroceryItemOrder[] GIOList = new GroceryItemOrder[10];//for holding GroceryItemOrder objects, then gets sent to toString() for printing
public static double TotalCost = 0;//initializes total cost variable
public static DecimalFormat f = new DecimalFormat("#####0.00");//Ensures proper output format for doubles
private static int counter;//Used for indexing
private static String target;//File path
public static void main(String[] args) throws FileNotFoundException, NullPointerException {
target = args[0];//User-supplied file path is assigned to variable "target"
try {//protects against NullPointerException
input();//Sends file path to input method, which sends that data to all other relevant methods and classes
System.out.printf("%-20s", "Item");//These lines provide headers for output message
System.out.printf("%-10s", "Quantity");
System.out.printf("%-10s", "Price");
System.out.printf("%-12s", "Total Price");
System.out.println();
for (int i = 0; i < counter; i++) {//Ensures only correct objects are printed to user
System.out.println(GIOList[i].toString());//public object array sends data to the toString() method, which
//then prints formatted output string, limited by counter in order to ensure only proper data prints
}if (counter<10){//If the file contains under 11 items, this prints to the user
System.out.println("Total cost: $" + f.format(TotalCost));}
else{//if the file contains 11 or more lines, this statement makes clear that only the first 10 items
//will be included in the total cost.
System.out.println("Total cost of the first ten items in your file: $" + f.format(TotalCost));
}
} catch (NullPointerException e){//safeguard against printing null strings to user
}
}
Plus an input method
Please try this quick workaround.
create a folder hierarchy com\company or com/company (depending on you OS).
Put the myclassname.class file inside the com\company folder.
from top level folder (which is at same level as com folder), run
java com.company.myclassname
Regards,
Ravi
Related
I'm currently working on a project and I'm running into a couple of issues. This project involves working with 2 classes, Subject and TestSubject. Basically, I need my program (in TestSubject class) to read details (subject code and subject name) from a text file and create subject objects using this information, then add those to an array list. The text file looks like this:
ITC105: Communication and Information Management
ITC106: Programming Principles
ITC114: Introduction to Database Systems
ITC161: Computer Systems
ITC204: Human Computer Interaction
ITC205: Professional Programming Practice
the first part is the subject code i.e. ITC105 and the second part is the name (Communication and Information Management)
I have created the subject object with the code and name as strings with getters and setters to allow access (in the subject class):
private static String subjectCode;
private static String subjectName;
public Subject(String newSubjectCode, String newSubjectName) {
newSubjectCode = subjectCode;
newSubjectName = subjectName;
}
public String getSubjectCode() {
return subjectCode;
}
public String getSubjectName() {
return subjectName;
}
public void setSubjectCode(String newSubjectCode) {
subjectCode= newSubjectCode;
}
public void setSubjectName(String newSubjectName) {
subjectName = newSubjectName;
}
The code I have so far for reading the file and creating the array list is:
public class TestSubject {
#SuppressWarnings({ "null", "resource" })
public static void main(String[] args) throws IOException {
File subjectFile = new File ("A:\\Assessment 3 Task 1\\src\\subjects.txt");
Scanner scanFile = new Scanner(subjectFile);
System.out.println("The current subjects are as follows: ");
System.out.println(" ");
while (scanFile.hasNextLine()) {
System.out.println(scanFile.nextLine());
}
//This array will store the list of subject objects.
ArrayList <Object> subjectList = new ArrayList <>();
//Subjects split into code and name and added to a new subject object.
String [] token = new String[3];
while (scanFile.hasNextLine()) {
token = scanFile.nextLine().split(": ");
String code = token [0] + ": ";
String name = token [1];
Subject addSubjects = new Subject (code, name);
//Each subject is then added to the subject list array list.
subjectList.add(addSubjects);
}
//Check if the array list is being filled by printing it to the console.
System.out.println(subjectList.toString());
This code isn't working, the array list is just printing as blank. I have tried doing this several ways including a buffered reader but I can't get it to work so far. The next section of code allows a user to enter a subject code and name, which is then added to the array list as well. That section of code works perfectly, I'm just stuck on the above part. Any advice on how to fix it to make it work would be amazing.
Another small thing:
File subjectFile = new File ("A:\\Assessment 3 Task 1\\src\\subjects.txt"); //this file path
Scanner scanFile = new Scanner(subjectFile);
I'd like to know how I can change the file path so that it will still work if the folder is moved or the files are opened on another computer. The .txt file is in the source folder with the java files. I have tried:
File subjectFile = new File ("subjects.txt");
But that doesn't work and just throws errors.
That is because you have already read through the file
while (scanFile.hasNextLine()) {
System.out.println(scanFile.nextLine());
}
The contents are exhausted. So when you do
while (scanFile.hasNextLine()) {
token = scanFile.nextLine().split(": ");
there is no data left.
Remove the first loop or re-open the file.
Or as #UsagiMiyamoto mentions
Or read the line to a String variable, print it, then split it... All in one loop.
I assume you are just beginning with learning Java and hence the below code is probably way too advanced, but it may help others who are trying to do something similar to you and also give you a glimpse of what you will probably learn in future.
The below code uses the following (in no particular order):
Streams
Accessing resources
Records
try-with-resources
Multi-catch
Method references
NIO.2
More notes after the code.
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public record Subject(String subjectCode, String subjectName) {
private static final String DELIMITER = ": ";
private static Path getPath(String filename) throws URISyntaxException {
URL url = Subject.class.getResource(filename);
URI uri = url.toURI(); // throws java.net.URISyntaxException
return Paths.get(uri);
}
private static Subject makeSubject(String line) {
String[] parts = line.split(DELIMITER);
return new Subject(parts[0].trim(), parts[1].trim());
}
/**
* Reads contents of a text file and converts its contents to a list of
* instances of this record and displays that list.
*
* #param args - not used.
*/
public static void main(String[] args) {
try {
Path path = getPath("subjects.txt");
try (Stream<String> lines = Files.lines(path)) { // throws java.io.IOException
lines.map(Subject::makeSubject)
.collect(Collectors.toList())
.forEach(System.out::println);
}
}
catch (IOException | URISyntaxException x) {
x.printStackTrace();
}
}
}
A Java record is applicable for an immutable object and it simply saves you from writing code for methods including getters as well as equals, hashCode and toString. (There are no setters since a record is immutable.) It's a bit like Project Lombok. I would say that a Subject is immutable since I don't think the code or name would need to be changed and that's why I thought making Subject a record was applicable.
Running the above code produces the following output:
Subject[subjectCode=ITC105, subjectName=Communication and Information Management]
Subject[subjectCode=ITC106, subjectName=Programming Principles]
Subject[subjectCode=ITC114, subjectName=Introduction to Database Systems]
Subject[subjectCode=ITC161, subjectName=Computer Systems]
Subject[subjectCode=ITC204, subjectName=Human Computer Interaction]
Subject[subjectCode=ITC205, subjectName=Professional Programming Practice]
Regarding
I'd like to know how I can change the file path so that it will still work if the folder is moved
I placed file subjects.txt in the same folder as file Subject.class, which allowed me to use method getResource. Refer to the Accessing resources link, above. Note that this can't be used if
the files are opened on another computer
Alternatively, there are several directories whose paths are stored in System properties including
java.home
java.io.tmpdir
user.home
user.dir
what did your debug console said about the exception?
your code works very well in my editor.
code result
and you should code like below if you want to read file through relative path
before ->
new File ("A:\Assessment 3 Task 1\src\subjects.txt");
after ->
new File (".\\subjects.txt");
I have a simple java class as shown below:
public class Add2Numbers
{
public static void main(String[] args)
{
int num1=2, num2=4, sum;
sum = num1 + num2;
System.out.println("Sum of these numbers: "+sum);
}
}
I compile the class and run in matlab using:
obj = Add2Numbers;
javaMethod('main', o,"");
and I get the output: Sum of these numbers: 6 which is, of course, correct.
Next I change the code in my text editor (e.g. set num1=4) compile, execute the clear statements below:
clear all
clear java
clear import
clear CLASSES
clear ALL
clear
then run again:
obj = Add2Numbers;
javaMethod('main', o,"");
But the calculation result remains the same as before. If I close and restart MATLAB the modified java class runs correctly. So how on earth do I clear a java class without having to close MATLAB and restart it?
set
I am a new programmer in my first Java class . Here is my code but I am getting an error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:0 at CmdLine.main(CmdLine.java:13)
import java.util.Scanner;
import java.util.Arrays;
public class CmdLine{
public static void main( String [] args ){
int[] array;
array = new int [ 10 ];
for(int counter = 0; counter < array.length;counter++ )
array[counter]=Integer.parseInt (args[counter]);
System.out.printf( "%s%8s\n", "Index", "Value" );
for(int counter = 0; counter < array.length; counter++ )
System.out.printf( "%5d%8d\n", counter, array[ counter ] );
}
}
There are many approaches to solve this.
- Methods:
I know most IDEs allow you to add command line arguments. If you are interested in this, try checking out IntelliJ and this link for further instructions:
How do you input commandline argument in IntelliJ IDEA?
There is also another way which is using a jar file,
Passing on command line arguments to runnable JAR
Basically, a Jar file works on a terminal command line like this
java -jar (type_Something)
you can write a file path or a word.
- Explanations:
When you pass in a command line arguments, the first thing you pass in is for args[0].
Ex.
java -jar Hello
Hello gets stored in args[0], and then you can use it like this:
public class Test{
public static void main(String[] args){
String argument1 = args[0];
}
}
But if you now add
java -jar Hello Friend
Hello is stored in args[0] and Friend in args[1]. Therefore, you can use it like
this:
public class Test{
public static void main(String[] args){
String argument1 = args[0];
String argument2 = args[1];
}
}
- Personal Experience:
I have used the second method, using a jar, before. I believe I had to add a Jar in my IDE before using it on terminal inside my IDE (IntelliJ). I had to send a folder path to my program, and the only way allowed was using a jar to send in command line arguments.
package q1;
import java.io.FileNotFoundException;
import java.util.ArrayList;
/**
* <p>This is where you put your description about what this class does. You
* don't have to write an essay but you should describe exactly what it does.
* Describing it will help you to understand the programming problem better.</p>
*
* #author Your Name goes here
* #version 1.0
*/
public class Household {
/**
* <p>This is the main method (entry point) that gets called by the JVM.</p>
*
* #param args command line arguments.
* #throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
// your code will go here!!!
Survey s1 = new Survey();
s1.getSurveyList();
System.out.println();
}
};
-------------------------------------------------------------------------------------------
package q1;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Survey {
ArrayList<Integer> surveyList = new ArrayList<Integer>();
public Survey(){
}
public ArrayList<Integer> getSurveyList() throws FileNotFoundException{
Scanner sc = new Scanner(new File("survey.txt"));
while (sc.hasNextLine()) {
sc.useDelimiter(" ");
int i = sc.nextInt();
surveyList.add(i);
}
System.out.println(surveyList.get(0));
sc.close();
return surveyList;
}
}
Now it says that the system cannot find the file specified. Not sure how to use the File class because it is the first time I have had to do it.
Any ideas? Also how would one format the output of the text file so that it displays it in a table? Is there some method that does that?
The error "Could not find main class" has nothing to do with the way you are using the File or Scanner class. It sounds like your classpath is wrong. Ensure that your project root is configured correctly. You could try to use this tutorial for using Eclipse for a reference on how to set up your project correctly. If you are not using an IDE, check out the contents of the file you are running and make sure the correct information is in there. It would help a lot if you could specify your question a lot more such as which operating system are you using, are you using an IDE (if yes, which one), are you compiling it as a jar file or are you running it from a directory with class files... etc.
Changed Array to Double instead of Integer and changed the scanner line to this:
Scanner sc = new Scanner(
new File("src" + File.separator + "survey.txt"));
Okay I'll try to be direct.
I am working on a file sharing application that is based on a common Client/Serer architecture. I also have HandleClient class but that is not particularly important here.
What I wanna do is to allow users to search for a particular file that can be stored in shared folders of other users. For example, 3 users are connected with server and they all have their respective shared folders. One of them wants to do a search for a file named "Madonna" and the application should list all files containing that name and next to that file name there should be an information about user(s) that have/has a wanted file. That information can be either username or IPAddress. Here is the User class, the way it needs to be written (that's how my superiors wanted it):
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class User {
public static String username;
public static String ipAddress;
public User(String username, String ipAddress) {
username = username.toLowerCase();
System.out.println(username + " " + ipAddress);
}
public static void fileList() {
Scanner userTyping = new Scanner(System.in);
String fileLocation = userTyping.nextLine();
File folder = new File(fileLocation);
File[] files = folder.listFiles();
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < files.length; i++) {
list.add(i, files[i].toString().substring(fileLocation.length()));
System.out.println(list.get(i));
}
}
public static void main(String args[]) {
System.out.println("Insert the URL of your shared folder");
User.fileList();
}
}
This class stores attributes of a particular user (username, IPAddress) and also creates the list of files from the shared folder of that particular user. the list type is ArrayList, that's how it has to be, again, my superiors told me to.
On the other hand I need another class that is called RequestForFile(String fileName) whose purpose is to look for a certain file within ArrayLists of files from all users that are logged in at the moment of search.
This is how it should look, and this is where I especially need your help cause I get an error and I can't complete the class.
import java.util.ArrayList;
public class RequestForFile {
public RequestForFile(String fileName) {
User user = new User("Slavisha", "84.82.0.1");
ArrayList<User> listOfUsers = new ArrayList();
listOfUsers.add(user);
for (User someUser : listOfUsers) {
for (String request : User.fileList()) {
if (request.equals(fileName))
System.out.println(someUser + "has that file");
}
}
}
}
The idea is for user to look among the lists of other users and return the user(s) with a location of a wanted file.
GUI aside for now, I will get to it when I fix this problem.
Any help appreciated.
Thanks
I'm here to answer anything regarding this matter.
There are lots of problems here such as:
I don't think that this code can compile:
for (String request : User.fileList())
Because fileList() does not return anything. Then there's the question of why fileList() is static. That means that all User objects are sharing the same list. I guess that you have this becuase you are trying to test your user object from main().
I think instead you should have coded:
myUser = new User(...);
myUser.fileList()
and so fileList could not be static.
You have now explained your overall problem more clearly, but that reveals some deeper problems.
Let's start at the very top. Your request object: I think it represents one request for one user with one file definition. But it needs to go looking in the folders of many users. You add the the requesting user to a list, but what about the others. I think that this means that you need another class responsible for holding all the users.
Anyway lets have a class called UserManager.
UserMananger{
ArrayList<User> allTheUsers;
public UserManager() {
}
// methods here for adding and removing users from the list
// plus a method for doing the search
public ArrayList<FileDefinitions> findFile(request) [
// build the result
}
}
in the "line 14: for (String request : User.fileList()) {" I get this error: "void type not allowed here" and also "foreach not applicable to expression type"
You need to let User.fileList() return a List<String> and not void.
Thus, replace
public static void fileList() {
// ...
}
by
public static List<String> fileList() {
// ...
return list;
}
To learn more about basic Java programming, I can strongly recommend the Sun tutorials available in Trials Covering the Basics chapter here.
It looks like you're getting that error because the fileList() method needs to returns something that can be iterated through - which does not include void, which is what that method returns. As written, fileList is returning information to the console, which is great for your own debugging purposes, but it means that other methods can't get any of the information fileList sends to the console.
On a broader note, why is RequestForFile a separate class? If it just contains one method, you can just write it as a static method, or as a method in the class that's going to call it. Also, how will it get lists of other users? It looks like there's no way to do so as is, as you've hard-coded one user.
And looking at the answers, I'd strongly second djna's suggestion of having some class that acts as the controller/observer of all the Users.