Netbeans error when trying to run java project - java

I am getting an error when trying to run my code in Java. I am trying to run an output to a file where the user uses dialog boxes to input name, pay rate, and hours worked.
This is the code I have:
package output.to.a.file.broc.east;
import javax.swing.JOptionPane;
public class OutputToAFileBrocEast
{
public static void main(String[] args)
{
OutputFile payFile;
payFile = new OutputFile ("payroll.txt");
String name;
String rate;
String hours;
String answer;
do
{
int number1;
int number2;
name = JOptionPane.showInputDialog("Enter first and last name: ");
rate = JOptionPane.showInputDialog("Enter hourly rate: ");
hours = JOptionPane.showInputDialog("Enter hours for previous week: ");
number1 = Integer.parseInt (rate);
number2 = Integer.parseInt (hours);
payFile.writeWord(name);
payFile.writeWord(rate);
payFile.writeWord(hours);
payFile.writeEOL();
answer = JOptionPane.showInputDialog("Do you have another employee? [y/n");
}
while (answer.equalsIgnoreCase ("yes"));
}
}
But I get this error when trying to run the code:
Error: Could not find or load main class output.to.a.file.broc.east.OutputToAFileBrocEast
Java Result: 1
I am using Netbeans 7.4. and I have already attempted to delete the netbeans cache.

If you build a jar, open it with 7zip or so, and you should find:
/output/to/a/file/broc/east/OutputToAFileBrocEast.class
The same when the same holds without jar: in the dist or target folder under classes.
Maybe you have an extra directory or such.

Related

How to search a file for a certain date and time (inputted from user) in java

I am trying to figure out how I would go about searching a .txt file for a certain date and time that is given by the user. Currently my code does this:
PRINT "Enter the date of the task: "
READ into task_date (string)
PRINT "Enter the time of the task: "
READ into task_time (string)
PRINT "Enter the name of the task: "
READ into task_name (string)
LOAD tasks.txt file
I want to be able to read the data from the user in those three steps (yes i know it would probably be better to do it in one step but this is more of a proof of concept to a friend), then search a the tasks.txt file for a space to insert the task_date + task_time + task_name. Any help would be appreciated. Thanks
Edit:
Ok, I am creating a calendar app that is currently terminal based.
What it does is it takes the user inputs task date/time/name and appends it in the correct position in a file called tasks.txt (the file example is below)
10-6-2020 6:30 am Wake up
10-6-2020 7:00 am Take mom to school
10-6-2020 7:30 am arrive back home
10-6-2020 8:30 am leave for class
10-6-2020 9:00 am arrive on campus
10-6-2020 12:00 pm leave campus
10-6-2020 12:30 pm arrive back home
10-6-2020 1:00 pm Meeting with advisors
So lets say the user inputs '10-06-2020 10:00 am Walk into class'
I want the code to insert that line between 9:00 am and 12:00 pm
I apologize if the first question i posted was incomplete.
Edit 2:
My question isn't for others to code for me. My question is can anyone point me in the direction of how to append a string in the correct position of the txt file. (If you're confused look above). Again I'm not asking anyone to code it for me.
System.out.print("Enter the date of the task: ");
// // STRING task_time = INPUT
task_date = scan.nextLine();
// // PRINT "Enter the name of the task: "
System.out.print("Enter the time of the task: ");
// // STRING task_name = INPUT
String task_time = scan.nextLine();
// // CREATE new_task = task_date + task_time + task_name (STRING)
// String new_task = task_date;
System.out.print("Enter the name of the task: ");
// STRING task_date = INPUT
String task_name = scan.nextLine();
String task = task_date + " " + task_time + " " + task_name;
System.out.println(task);
// LOADFILE tasks.txt
String search_date = task_date;
String search_time = task_time;
int lineNumber = 0;
File taskstxt = new File("tasks.txt");
Scanner filereader = new Scanner(taskstxt);
// SEARCH tasks.txt for corresponding date and time
while (filereader.hasNextLine()) {
final String lineFromFile = filereader.nextLine();
if (lineFromFile.contains(search_date)) {
}
}
above is the code snippet in question. I want to search the txt file for for the date and time inputted by the user, and if it exists print "you have a task for that time already", if it doesn't exist I want to append the file with the task date/time/name. I'm sorry if this is confusing for anyone (I find it hard sometimes to write out exactly what I'm thinking)
Q: How do a build a "Calendar app" in Java?
A: Per your design above, your app will have the following:
A UI for adding records (currently command line, but you might want to consider a web UI, Android, Swing or other alternatives)
A UI for displaying records
A data store for saving records (currently a text file, but you might want to consider a "structured text" format like JSON or XML, or a database).
Q: How do I save a new calendar record in the correct position?
A: I would suggest:
Write a "TaskList" class for holding your calendar records.
SIMPLE EXAMPLE:
public class TaskList {
public List<TaskRecord> tasks;
public void save(string filename) { ... }
public void load(string filename) { ... }
}
Write a "TaskRecord" class for individual tasks:
SIMPLE EXAMPLE:
public class TaskRecord {
public Date dateTime;
public String taskText;
}
It's important to keep the "date" separate from your "text" in your class.
If you want a simple text file, and you want everything on the same line, then choose a delimiter that makes it easy to parse. For example, you can separate "date" and "time" with a tab (\t):
10-6-2020 6:30 am\tWake up
It might be unimportant to "insert the record in the right place" until you're ready to "save" the updated file. You can simply "sort()" (by date/time) before you "write()":
SIMPLE EXAMPLE:
public class TaskRecord implements Comparator<Date> {
public Date dateTime;
public String taskText;
#Override
public int compare(TaskRecord a, TaskRecord b) {
return a.datetime.compareTo(b.datetime);
}
}
If you really wanted to sort each new record as you insert it, you'd still probably want to implement "Comparator" (as above). You'd loop through your list until you find a time/date >= your new date, then List.add() at that index.
You'd probably also want to add methods to your "TaskList" class to add, modify and/or delete records.
"Encapsulation" can make your classes more robust. You want to hide everything about the class that's not "essential" from users of that class
SIMPLE EXAMPLE:
public class TaskRecord implements Comparator<Date> {
private Date dateTime;
private String taskText;
// Initialize object state in constructor
public TaskRecord(Date dateTime, String taskText) {
this.dateTime = dateTime;
this.taskText = taskText;
}
// "Getter" methods for read-only access
Date getDateTime() { return dateTime; }
String getTaskText() { return taskText; }
#Override
public int compare(TaskRecord a, TaskRecord b) {
return a.datetime.compareTo(b.datetime);
}
}
'Hope that helps ... at least a little

Cplex Java Library set up path problem in Eclipse

I have a newbie problem with taking the Cplex library in Eclipse,
Error: Could not find or load main class Files\IBM\ILOG\CPLEX_Studio1210\cplex\bin\x64_win64
Caused by: java.lang.ClassNotFoundException: Files\IBM\ILOG\CPLEX_Studio1210\cplex\bin\x64_win64
I added cplex.jar from external libraries and also added the native path by editing it,
CPLEX library path error in eclipse
under VMArguments I added,
-Djava.library.path=C:\Program Files\IBM\ILOG\CPLEX_Studio1210\cplex\bin\x64_win64
where cplex12100.dll stands. I managed to work with it before but I couldn't find why it is not working right now.
Everything is 64bit.
Thanks in advance!
Your error message references the following path:
Files\IBM\ILOG\CPLEX_Studio1210\cplex\bin\x64_win64
Notice that it does not start with "C:Program Files". My guess is that you need to put quotes around the path you are providing, like so:
-Djava.library.path="C:\Program Files\IBM\ILOG\CPLEX_Studio1210\cplex\bin\x64_win64"
This should allow Java to handle your path which includes a space character.
thanks for the answer,
Unfortunately, I forgot to add that I already tried that, but it gives another error when I try like that.
Error: Unable to initialize main class model(my package name).model(my class name)
Caused by: java.lang.NoClassDefFoundError: ilog/concert/IloException
Here is part of my code, I cut half of it(after ...) since I guess it is unrelated to the question.
package model;
import ilog.concert.*;
import ilog.cplex.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.*;
import java.time.Instant;
import java.util.concurrent.TimeUnit;
public class model {
public static void main(String[] args) throws Exception {
long startTime = Instant.now().toEpochMilli();
int a = 45; //matrisin boyutu
int b = 45; //matrisin 2. boyutu
int maxdistance = 90; //mesela 90 dan küçük deðerler
int depot = 0;
double alfa = 0.9;
double beta = 0.1;
float[][] distance = new float[a][b]; // bunu scanner dan çektik
int m = 3;
int C = 1200;
System.out.println();
System.out.println("m : " + m + " C : " + C );
System.out.println();
ArrayList<ArrayList> Nlist = new ArrayList<ArrayList>();
Scanner reader = null;
File burdurData = new File("burdur45.txt");
...
try {
long timeElapsed = endTime - startTime;
System.out.println("Execution time in milliseconds: " + timeElapsed);
System.out.println("Execution time in seconds: " + timeElapsed/1000);
} // try'ýn parantezi
catch (IloException exc) {
System.out.println(exc);
System.out.println("sýkýntý");
}
}
}
surely you should edit your question. In fact, for getting error:
java.lang.NoClassDefFoundError: ilog/concert/IloException
I had this error before and I solved it just by importing cplex.jar in ClassPath section of my project Java Build Path not in ModulePath. Also set Native Library Location path to cplex's dlls folder too. Furthermore you can check your details in java configuration->show command line too.

Extract Data From Multiple Files

I have exactly 278 Html files of essays from different students, every file contains student id, first name and last in the following format
<p>Student ID: 000000</p>
<p>First Name: John</p>
<p>Last Name: Doe</p>
I'm trying to extract Student IDs from all this files, is there a way to extract data between X and Y? X being "<p>Student ID: " and Y being "</p>" which should leave us with ID
What Method/Language/Concept/Software would you recommend to get this work done?
Using java:
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
public class StudentIDsRetriever {
public static void main(String[] args) throws IOException {
File dir = new File("htmldir");
String[] htmlFiles = dir.list();
List<String> studentIds = new ArrayList<>();
List<String> emailDs = new ArrayList<>();
for (String htmlFile : htmlFiles) {
Path path = FileSystems.getDefault().getPath("htmldir", htmlFile);
List<String> lines = Files.readAllLines(path);
for (String str : lines) {
if (str.contains("<p>Student ID:")) {
String idTag = str.substring(str.indexOf("<p>Student ID:"));
String id = idTag.substring("<p>Student ID:".length(), idTag.indexOf("</p>"));
System.out.println("Id is "+id);
studentIds.add(id);
}
if (str.contains("#") && (str.contains(".com") || str.contains(".co.in"))) {
String[] words = str.split(" ");
for (String word : words)
if (word.contains("#") && (word.contains(".com") || word.contains(".co.in")))
emailDs.add(word);
}
}
}
System.out.println("Student list is "+studentIds);
System.out.println("Student email list is "+emailDs);
}
}
P.S: This works from Java7+
I recommand you python script. If you first use python, It's OK. python is so easy script language and has many references in google.
1) Language: python (version 2.7)
2) Library: beautifulsoup (you can download this with pip(pip is package manager program, pip can be installed in python installer)
traverse files one by one and open your local files. and parse HTML content using beautifulsoup. (see this part https://www.crummy.com/software/BeautifulSoup/bs4/doc/#tag)
then, extract content from <p> tag. It return "Student ID: 000000".
split this string with ":". this return str[0] and str[1].
str[1] is student number you want (maybe you erase space character... call ' Hel lo '.strip() -> Hello
If you need a help, reply.

No main method detected

The compiler keeps saying there is no main method but there is one:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
class StarWarsFinal
{
final static Map<String, String> firstNameMap = new HashMap<>();
static {
firstNameMap.put("A", "Cho");
firstNameMap.put("B", "R2");
firstNameMap.put("C", "C-3po");
firstNameMap.put("D", "Yod");
firstNameMap.put("E", "Nas");
firstNameMap.put("F", "Slea");
firstNameMap.put("G", "Jan");
firstNameMap.put("H", "Zhur");
firstNameMap.put("I", "Boba");
firstNameMap.put("J", "Thre");
firstNameMap.put("K", "Bib");
firstNameMap.put("L", "Kit");
firstNameMap.put("M", "Kyp");
firstNameMap.put("N", "Gonk");
firstNameMap.put("O", "Zlung");
firstNameMap.put("P", "Adi");
firstNameMap.put("Q", "Nat");
firstNameMap.put("R", "Ru");
firstNameMap.put("S", "Cla");
firstNameMap.put("T", "Kir");
firstNameMap.put("U", "Obi");
firstNameMap.put("V", "Ken");
firstNameMap.put("W", "Ziro");
firstNameMap.put("X", "Zev");
firstNameMap.put("Y", "Tavion");
firstNameMap.put("Z", "Jar");
}
final static Map<String, String> lastNameMap = new HashMap<>();
static {
lastNameMap.put("A", "tzki");
lastNameMap.put("B", "hut");
lastNameMap.put("C", "der");
lastNameMap.put("D", "kzos");
lastNameMap.put("E", "vos");
lastNameMap.put("F", "vader");
lastNameMap.put("G", "thrawn");
lastNameMap.put("H", "mesk");
lastNameMap.put("I", "thuo");
lastNameMap.put("J", "skywalker");
lastNameMap.put("K", "D2");
lastNameMap.put("L", "maul");
lastNameMap.put("M", "sith");
lastNameMap.put("N", "muzzar");
lastNameMap.put("O", "jusik");
lastNameMap.put("P", "horn");
lastNameMap.put("Q", "phisto");
lastNameMap.put("R", "farlander");
lastNameMap.put("S", "dunhaussan");
lastNameMap.put("T", "jar");
lastNameMap.put("U", "binks");
lastNameMap.put("V", "lbis");
lastNameMap.put("W", "gnarzlo");
lastNameMap.put("X", "anakin");
lastNameMap.put("Y", "ackbur");
lastNameMap.put("Z", "axmis");
}
final static Map<String, String> jobMap = new HashMap<>();
static{
jobMap.put("Jan","Clone");
jobMap.put("Feb","Bounty Hunter");
jobMap.put("Mar","Droid");
jobMap.put("Apr","Jedi Knight");
jobMap.put("May","Gungan");
jobMap.put("Jun","Gangster");
jobMap.put("Jul","commander");
jobMap.put("Aug","ewok");
jobMap.put("Sep","Queen");
jobMap.put("Oct","Empirer");
jobMap.put("Nov","Darth");
jobMap.put("Dec","captain");
}
public static void main ( String[] args )
{
String[] planet = null, rank = null, rebbelion = null, letter1 = null, letter2= null , Map , HashMap;
Scanner input = new Scanner( System.in ); //scanner initilized
planet = new String[11]; //Planet options
planet[0] = "Alderaan";
planet[1] = "Bespin";
planet[2] = "Coruscant";
planet[3]= "Forest moon of Endor";
planet[4] = "Hoth";
planet[5] = "Kamino";
planet[6] = "Kashyyk";
planet[7] = "Mustafar";
planet[8] = "Yavin";
planet[9] = "DEATH STAR";//Planet options -END
System.out.println("Welcome to the Star Wars name generator");
System.out.println("What is your first name?"); //Name Generation
String firstName = input.nextLine();
String newFirst = firstNameMap.get(firstName.toUpperCase().substring(0,1)); //Name Generation (i want to take the first letter of there input and get the output from letter1 matching that # ie c = letter1 [2] a= letter1 [0])
System.out.println("What is your last name?"); //Name Generation
String lastName = input.nextLine(); //Name Generation (i want to take the first letter of there input and get the output from letter2 matching that # ie c = letter2 [2] a= letter2 [0])
String newLast = lastNameMap.get (lastName.toUpperCase().substring(0,1));
System.out.println("What is your Birth month(first 3 letters)?"); //Name Generation
String month = input.nextLine();
String job = jobMap.get(firstName.toUpperCase().substring(0,3));
System.out.println("If you had to choose 1)dark or 2)light side? please input the number"); //Selection of Dark or Light side
int side = input.nextInt();
//Selection of Dark or Light side
System.out.println("There are now several places you could live please choose one of the following by number:"); //Planet selections
System.out.println("1) Alderaan 2) Bespin 3) Coruscant 4) Forest moon of Endor 5) Hoth "); //Planet selections
System.out.println("6) Kamino 7) Kashyyk 8) Mustafar 9) Yavin 10)DEATHSTAR"); //Planet selections
String location =input.nextLine();
if (side == 1)
{
System.out.println("You Have chosen to be part of the dark side!");
System.out.println("You "+ newFirst + newLast +" now fight for the dark side As a proud "+ job +"of the"+ location +"Good luck against your enemy's and may the force be with you");
}
else
{
System.out.println("You are now part of the light side!");
System.out.println("You "+ newFirst + newLast +" now fight for the light side As a proud "+ job +"of the"+ location +"Good luck against your enemy's and may the force be with you");
}
System.out.println("Thank you for doing the starwars name generator!");
}
}
I don't know why it won't read it, because it was working earlier. I'mm using NetBeans as IDE.
There is nothing wrong with the program.
I did the following:
[steve#newbox tmp]$ cat > StarWarsFinal.java
<paste-program-from-question>
[steve#newbox tmp]$ javac StarWarsFinal.java
[steve#newbox tmp]$ java StarWarsFinal
Welcome to the Star Wars name generator
What is your first name?
^D
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1585)
at StarWarsFinal.main(StarWarsFinal.java:112)
[steve#newbox tmp]$
From this we must conclude that the problem you are experiencing is one of the following:
You are not compiling it properly.
You are not running it properly.
There is something non-standard in the way that NetBeans is deciding that a class is runnable. (This is highly unlikely ... IMO)
Maybe you are doing something else that you haven't mentioned ...
For the record:
It is NOT necessary for the class to be declared as public for it to be runnable, at least when you run it from the command line using the java command.
It is not a Java compilation error for there to be no main method. It is a runtime error. A class only needs a main method if you are going to attempt to run it. The compiler has no way of knowing if you are going to do that, so it cannot complain about it.
The "Hello World!" for the NetBeans IDE page runs you through the steps of compiling and running a simple program using NetBeans. Maybe this will give you some clues as to what you are doing wrong.

Java Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous tree type:

I am receiving a Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous tree type: error in netbeans when I try to run the code below. I am supposed to input from a file and then display the data using the formulas below in the output window. I don't see any errors that are given with the code itself until I try to run the code. I am new to Java and having a hard time grasping some of the concepts. I have cleared out the netbeans cache and restarted and now am getting this error. Thanks for any help.
package input.from.a.file.broc.east;
public class InputFromAFileBrocEast
{
public static void main(String[] args)
{
String name;
int hours;
int rate;
int grossPay;
InputFile wageFile;
wageFile = new InputFile("payroll.txt");
while (!wageFile.eof())
{
name = wageFile.readString();
hours = wageFile.readInt();
rate = wageFile.readInt();
if (hours <= 40)
{
grossPay = (rate * hours);
System.out.println("grossPay");
}
else
{
grossPay = (int) ((rate * 40) + (hours-40) * 1.5 * rate);
System.out.println("Gross Pay: " + grossPay);
}
}
}
}
Netbeans allows you to run the code even if certain classes are not compilable. During the application's runtime, if you access this class it would lead to this exception.
To ensure you get the exact compilation error, you need to deselect 'Compile On Save' in the project options.
Also have a look at https://netbeans.org/bugzilla/show_bug.cgi?id=199293

Categories

Resources