Post Compile error, check Console? [duplicate] - java

This question already has answers here:
Error Message: Int cann't be converted to type
(3 answers)
Closed 7 years ago.
The error message is posted below along with with the actual code. The code is able to compile and run but instead of printing at the end I receive a pop up error message (screen shot below) but I don't understand what it means or why I am getting it. Can anyone help? Thanks!
public class Employee10
{
public static void main ( String args[] )
{
Employee e1 = new Employee();
Employee[] arr = new Employee[2];
int j = 0;
for ( int i=0; i < 3; i++)
{
arr[0] = e1;
String nameF = Input.getString("Please enter a First Name");
String nameL = Input.getString("Please enter a Last Name");
int Number = Input.getInt("Please enter an Employee Number");
String Street = Input.getString("Please enter a Street address");
String City = Input.getString("Please enter a City");
String State = Input.getString("Please enter a State");
double Zip = Input.getDouble("Please enter a Zip Code");
int Month = Input.getInt("Please enter a Month");
int Day = Input.getInt("Please enter a Day");
int Year = Input.getInt("Please enter a Year");
e1.setNumber(Number);
e1.setName( new Name(nameF, nameL));
e1.setAddress(new Address(Street, City, State, Zip));
e1.setHireDate(new Date(Month, Day, Year));
System.out.println(e1.getEmployeeString());
arr[i] = e1;
}
for ( j=0; j < arr.length; j++ )
{
System.out.println( arr[j].getEmployeeString() );
}
}
}
ERROR MESSAGE:
( Unfortunately I am not able to embed a photo so I just have to type out the code so here it is):
The Java class file "Employee10.class" could not be launched. Check
the Console for possible error messages.
What does all of this mean? Where is the Console I can check?

TL;DR: The console depends on what software you're using to run your code (we call these Integrated Development Environments, or IDEs). If you tell us what software you're using, we can help.
Long answer:
There are generally 2 kinds of errors - compile time and runtime. Compile time errors are usually told to you by your IDE. These are things like misspelling keywords ("itn" instead of "int", "tSring" instead of "String", etc) and missing semicolons. Runtime errors are a different beast. These occur when your program actually runs. One example is lets say you have an array of size 10. If you try to look at the eleventh element, when you run your program, it will fail. These errors are the ones that usually show up in the console in the form of a stack trace - some message telling you which functions were called and where the specific error is from.

If you are using a very basic IDE like BlueJ(since you are a beginner),I would suggest you to place something like System.out.println("Beginning program");
or something similar which prints something onto the console.Make this the first statement in main.Now console could be considered as the place were you would see your output statements displayed(raw definition).Could be considered as a display window.
I used BlueJ long back when I was learning java and it never triggered the program until there was something to print on to the console.It always lookes for a print statement to begin with.
And the strangest part was-It never required a string array as an argument in the main function.I was surprised when I switched to eclipse and the program didn't compile without the argument in main.So things could be strange with some very basic IDEs.
I would suggest that you try out this solution and also try to use a good IDE like eclipse or netbeans.These IDEs are highly professional and would give you immediate and great ideas on errors that occur in a program.

Related

Half String every second char

I an coding beginner.I have started practicing SPOJ basic problems.This was the one I was trying to solve , But the code is incorrect.
Please help me where I have coded this question wrong as I am unable to figure out:
public class Print2ndChar {
public static void main(String[] args) throws java.lang.Exception {
Print2ndChar mainObj = new Print2ndChar();
java.io.BufferedReader inputReader = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
String noOfTestCase;
if(((noOfTestCase = inputReader.readLine()) == null))
System.exit(0);
int noOfLines = 0;
try{
noOfLines = Integer.parseInt(noOfTestCase);
}catch(Exception e){
System.exit(0);
}
if(noOfLines<0 || noOfLines>100)
System.exit(0);
String [] randomWords = new String[noOfLines];
for(int i=0;i<noOfLines;i++){
randomWords[i] = inputReader.readLine();
if(randomWords[i] == null || randomWords[i].length()<2 || randomWords[i].length()%2!=0 || (randomWords[i].length()/2)>100)
System.exit(0);
}
for (String word : randomWords){
mainObj.letsBegin(word.substring(0, word.length() / 2));
System.out.println();
}
}
private void letsBegin(String data) {
if (data.length() <= 0) {
return;
} else {
System.out.print(data.charAt(0));
if (data.length() >= 3)
letsBegin(data.substring(2, data.length()));
}
}
}
EDIT :
I/P : 4
your
progress
is
noticeable
O/P
y
po
i
ntc
OK! So after a lot of hit and trials, I know what is wrong with your code. The code that you have written fails because of the condition randomWords[i].length()%2!=0 inside your if. There is nothing wrong with you putting this condition to check the input, but if you will select sample test case, inside the highlighted blue area you will notice an extra space after every string. Like this :
You can see that other than the last input all other input strings have a space character at the end. So, when you read the string from stdin the length of the string is 2*k + 1 (because of the space), and your program will exit without any output. Hence you get a wrong answer.
This problem exists with other test cases as well probably. And how do I know this? After spoj shows you wrong answer, if you click on the wrong answer, it will show you 2 failed test cases, something like this:
It shows your program's output is empty because your code exited because of the extra space at the end of strings.
So, I believe the person who wrote the test cases should be given a WT Error (Wrong Test Cases) :P :D
So, the possible correction is you remove the mentioned condition from the if and you will get AC. Because now you will be dividing 2*k + 1 by 2, which will not be an integer and which will get rounded to the nearest smallest integer, which will be same as dividing 2*k by 2 and the program will give the correct result.
A few things that you should take care while solving questions on spoj, you do not have to verify that every input lies within the range specified in the question, or if it is a valid data type. The range is given to tell you that Spoj will only test your program with cases which lie between those ranges and will not exceed them. So, even if you remove all the code where you check for exceptions and ranges of input data, you will get an AC. Moreover, writing such code only adds to the burden.
Hope this helps. :)

storing "inputdialog" data in an array

I have written a Java menu console which asks users to select an option. I have successfully compiled the menu system which takes a users input and directs them to a menu page. The first of these pages asks 2 questions using "InputDialog" boxes.
Here is the code for the "InputDialog", when I run the java console i can access and enter information into these boxes fine.
private void enterInfor()
{
String carInfo;
int carHours;
int i = 0;
double fee = Double.parseDouble("7.50");
double sum = 0;
{
carInfo = JOptionPane.showInputDialog("Please enter the license plate of the car");
carHours = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of hours the car was parked (1-12):"));
System.out.printf("\n");
System.out.printf("Details for car 1 entered:\n");
System.out.printf("License plate Hours Fee:\n");
System.out.printf(""+carInfo+" "+carHours+" $");
if (carHours == 1)
System.out.printf("%3.2f",fee*(carHours));
else if (carHours == 2)
System.out.printf("%3.2f",fee+4.50);
else if (carHours >= 3)
System.out.printf("%3.2f",3+(carHours*4.50));
System.out.printf("\n\n");
}
}
I have the "String" and "int" information to store the information that is input by the user, however I need the program to store at least 20 different inputs which can be accessed later in the console.
I have successfully made a console repeat information and then output the combined answers using a for loop =
"for(int Num=1; Num <= 6; Num++)"
and this allowed me to repeat a set of questions and then compile the information into statistics afterwards but for this console I need the "InputDialog" to only take in one set of answers at a time and then return the user to the initial console menu.
I'm sorry again if this is all pretty vague of information or formats, just need some kind of help on how/where to put the correct code.

Asking the user to think of, and write down, a number between 1 and 1,000,000 in java

Hi guys so I'm working on writing a program that's asking a user to think of and write down a number between 1 and 1,000,000.
then it asks questions like "Is it greater than 500000?", and the user answers "Yes" or "yes" or "no or "NO", or "Got It!" now this where I'm stuck at. I don't know how to get it to ask that questions
this is the code i got so far :
import javax.swing.JOptionPane;
public class Questions {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, Questions");
String S = JOptionPane.showInputDialog("Enter a number between 1 and 1,000,000");
int i = 1000000;
if (i>500000){
}
}
how do i use JOptionPane.showInputDialog to ask questions and get answers ?
Any help is appreciated.
First of all, I strongly recommend debugging in the console until your logic is complete, then work on the GUI.
You are basically trying to implement a binary search, where the computer should get the answer right in log(N) guesses.
Here is some code to get you started. The GUI should be fairly straightforward. Read the appropriate Javadocs.
try (Scanner k = new Scanner(System.in);) {
String input;
int lo = 0;
int hi = 1000000;
int mid;
while (true) {
mid = (lo + hi) / 2;
System.out.printf("Is it equal to %d?\n", mid);
if (!input.equalsIgnoreCase("Got it!")) {
break;
} else {
System.out.printf("Is it greater than %d?\n", mid);
input = k.nextLine();
if (input.equalsIgnoreCase("yes")) {
lo = mid;
} else {
hi = mid;
}
}
}
} catch (IOException e) {
System.err.println(e.getMessage());
}
You can use showConfirmDialog() to ask a yes or no question...Here is an example you would need to change the values as these are hard coded but you should be able to figure out how to put this in a loop and change values dynamically based upon user entry:
int answer = JOptionPane.showConfirmDialog(null, "Is 500,000 your number?", "Question", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if(answer == 1)
{
answer = JOptionPane.showConfirmDialog(null, "Is 500,000 less than your number?", "Question", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
}
This way the user doesn't have to type "yes" or "no" or "got it" which will eliminate human error...
Yes - will return 0
No - will return 1
The second question will tell u whether there number is lower or higher than the proposed number depending on whether they answer yes or no...
First you should change S to an integer because you're asking the user to enter an integer. Second, assuming the program is supposed to try to guess the number, you would start with 500,000 and keep guessing in halves until you get the entered number (it looks like you got this part). So here is an outline (I'm not quite sure what the exact syntax is for JOptipnPane but you can find commands for input and output):
String YesOrNo = JOptionPane.ShowInputDialog ("is the number higher than 500,000? ")
If YesOrNo.equalsIgnoreCase ("yes") then guess 750,00 next if no guess 250,000 next
This is an outline see if you can get the rest if not comment for further help
First you should change S to int because you are asking the user to enter an integer. Second, assuming the program is supposed to try to guess the number, you would start with 500,000 and keep guessing in halves until you get the entered number (it looks like you got this part). So here is an outline (I am not quite sure what the exact syntax is for JOptipnPane is but you can find commands for input and output):
String yesOrNo = JOptionPane.ShowInputDialog("is the number higher than 500,000? ")
If yesOrNo.equalsIgnoreCase("yes") then guess 750,00 next if no guess 250,000 next
This is an outline see if you can get the rest. If not comment for further help.

How to fix: "the type java.lang.CharSequence cannot be resolved. It is indirectly referenced from required .class files" message? [duplicate]

This question already has answers here:
The type java.lang.CharSequence cannot be resolved in package declaration
(5 answers)
Closed 4 years ago.
I'm trying to use this string
amountStr = amountStr.replace("$", "").replace(" ", "").replace(",", "");
but I get an error message which I know I'm getting because that string I just posted is outdated. So I was wondering what would be a good updated version of that string? here is how my whole code looks like.
import java.util.Scanner;
public class QuarterMachine{
/**
* Convert the input to cents.
*/
public static void main(String[] args){
// PART I INPUT SECTION (COMPLETE)
// DO NOT CHANGE THESE LINES
Scanner cin = new Scanner(System.in);
System.out.print("Part I-Enter the amount input ($ 1,572.52): ");
String amountStr = cin.nextLine();
// PLACE YOUR CODE ONLY BELOW THIS LINE
// PLACE YOUR OUTPUT IN THESE VARIABLES
// ---------- YOUR CHANGES HERE ----------------------
double amount = 0;
int quarters = 0;
//My problem is in line below
amountStr = amountStr.replace("$", "").replace(" ", "").replace(",", "");
amount = Double.parseDouble(amountStr);
quarters = (int) (amount * 100) / 25;
// PLACE YOUR CODE ONLY ABOVE THIS LINE
// PART I OUTPUT SECTION COMPLETE
System.out.printf("Amount received($%,.0f), quarters returned(%,d)%n%n",amount, quarters);
// PART II INPUT SECTION (COMPLETE)
System.out.print("Part II-Enter seconds, minutes and hours as integers: ");
int seconds = cin.nextInt();
int minutes = cin.nextInt();
int hours = cin.nextInt();
// PLACE YOUR CODE ONLY BELOW THIS LINE
// PLACE YOUR OUTPUT IN THIS VARIABLE
String result = String.format("%02d:%02d:%02d", hours, minutes, seconds);
// YOUR CODE MUST GO ABOVE THIS LINE
// PART II - OUTPUT SECTION COMPLETE
System.out.println("Result: " + result);
}
}
I think this is some kind of a bug in Eclipse. You can fix this by trying each solution written below. If one doesn't work try the next one.
Clean the project
Delete the project and import it once again (You might need to clean the project again)
If above doesn't work try this link http://dev-answers.blogspot.de/2009/06/eclipse-build-errors-javalangobject.html. You basically remove JRE Library from project and add it again to the project.
Hope this helps.
Probably you will face this error after upgrading to JDK 8 as some old interfaces now have new default methods in 1.8.
So first verify that Your eclipse supports jdk 1.8, eclipse should be greater than or equal to 4.3.2(Eclipse Kepler SR2).
Eclipse complains this error if source level of your project is lower than 1.8, so set source level to 1.8 then complier will not through any exception.
Third option is, rollback to JDK 7 to use old interfaces.
Hope this will helps

receiving ArrayIndexOutOfBoundsException but cannot figure out why

this is a university assignment (sample academic report), I thought I was done and going to submit but when I started testing... I keep receiving ArrayIndexOutOfBoundsException on line 60 in main and I cannot see why. I am new to Java but really put a lot of hours into this program. Any help/advice is much appreciated.
line 60 = "int credits = Integer.parseInt(input[1]);" //im thinking error is something to due with data types??? im lost.
Course / Grade / Report classes pass data to the main java2pgm1
When you call split it returns you the an array. Here you are splitting using (":")
You need to check the length of variable input before accessing it.
String[] input = course.split(":");
int credits = Integer.parseInt(input[1]);
The input array may not contain more than 1 value so it fails
The exception will occur when the input from a user does not correspond to the expected format course_number:number_of_credits:grade_received:term_taken. In your case for what input value are you running into this exception? Does it contain a :?
Suggest that you test the length of the input array before referencing index[n]
String[] input = course.split(":");
int credits = Integer.parseInt(input[1]);
Integer term = Integer.parseInt(input[3]);
Course cObject = new Course(input[0],credits,input[2],input[3]);
The above snippet in your main always assumes that the course String has abc:def:ghi:jkl atleast 3 ":" in it. It is always good practice to handle the error case, when the string doesn't have 3 ":". Modify your code to something like below
String[] input = course.split(":");
if(input.length == 4)
{
int credits = Integer.parseInt(input[1]);
Integer term = Integer.parseInt(input[3]);
Course cObject = new Course(input[0],credits,input[2],input[3]);
}
else
{
//show some error message to user
}
here size of input array may be 0 or 1, you can check it by input.length.
If size of array is less or equal the element you want to get from array then runtime exception ArrayIndexOutOfBoundsException is thrown.

Categories

Resources