|
I have an assignment where the main class output mentions Index 1 out of bounds for length 1 and im trying to read a csv file which has 4 rows and 4 columns below is my code and csv file. Please help the assignment is due tonight at midnight Eastern time :/ I am in my first year of computer science and the assignment is for my introduction of Object-oriented programing, I still consider myself beginner.
main class:
public static void main(String[]args) {
String relativePath = "data/technicians 2.numbers";
List<BaseTechnician> technicians = new ArrayList<>();
try {
List<String[]> data = CSVReader.readTechnicians(relativePath);
if(data != null) {
for(String[]technician : data) {
String position = technician[0];
String name = technician[1];
String technicianId = technician[2];
double salaryOrHourlyRate = Double.parseDouble(technician[3]);
BaseTechnician emp;
switch(position) {
case " Fulltime ":
emp = new FullTimeTechnician(name, technicianId,salaryOrHourlyRate);
break;
case " PartTime ":
emp = new PartTimeTechnician(name, technicianId, salaryOrHourlyRate);
break;
default:
System.out.println(" Wrong technician position ");
continue;
}
technicians.add(emp);
for(BaseTechnician tech : technicians ) {
tech.displayDetails();
System.out.println(" Calculated Salary : " + tech.calculateSalary());
System.out.println();
}
}
} else {
System.out.println("Error Failed to read data from the technician CSV file ");
}
} catch (Exception e) {
System.out.println(" Error occured " + e.getMessage() );
}
}
}
and csv file:
FullTime David Jonathan FT1001 50000
PartTime Keith Peters PTE 2001.00 24.5
FullTime Mary Aramal FTE1003 60000
PartTime Hassan Otosh PTE 2002.00 30.5
FullTime Bernard Becker FTE1004 40000
PartTime Roselyn Anne PTE 2003.00 24.5
FullTime James Lead FTE1005 80000
modified 24-Mar-24 12:35pm.
|
|
|
|
|
Simple: Java indexes run from 0 to N-1, where N is the number of elements in the collection.
So if you have an array with three elements, the only valid indexes are 0, 1, and 2 - any index that is 3 or higher or that is negative is invalid and you will get this error message.
In your specific case, the error is telling you that you are using an index of 1 to access a collection with a single element - so the only valid index will be zero. Read this: How to Write Code to Solve a Problem, A Beginner's Guide Part 2: Syntax Errors[^] to find out where the error occurs and than use the debugger to find out why the collection contains fewer elements than you thought, or why the index is bigger than it should be. (It's primarily about syntax errors, but the message format is generally similar for run time errors as well)
[edit]
But one thing I did notice while adding code blocks to your original post is that that isn't CSV data: CSV stands for "Comma Separated Values" and your data as shown contains no commas ... this may be relevant to your problem ... check the data you read with the debugger and you'll see what I mean.
[edit]
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
modified 24-Mar-24 12:38pm.
|
|
|
|
|
Hey! Thanks for the reply I ended up using the debugger and made some changes with the data index and my code runs! Appreciate it!
|
|
|
|
|
You're welcome!
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Olivia8 wrote: I ended up using the debugger
And from first post...
"I am in my first year of computer science"
Someone is doing something right. Either you or the teacher or both of you are doing a great job. Even if the teacher covered this in detail, you still get points for paying attention.
Not sure I have ever seen anyone before do the same.
|
|
|
|
|
Are you sure that line
FullTime David Jonathan FT1001 50000
gives FOUR Strings
or it gives FIVE Strings?
Depends on CSVReader.readTechnicians()
Can understand that name is David AND Jonathan
or it is just read name:David
and id :Jonathan(wrong)..
And in what line says exception occuring?
|
|
|
|
|
The SecurityManager is being removed from Java?
JEP 411: Deprecate the Security Manager for Removal[^]
For a certain class of problems I found that to be a solution. Without it there is no solution. Certainly in C# such a solution does not exist.
The class of problems is one where the business model allows, as a selling point, customers to create their own code for limited solutions.
For example (and from a real company) if one allows for Content Management creation then allowing for programmatic creation provides many possibilities. But running that in a shared application space means that the company will want to limit access. Not only things like operating system calls but even to make sure that the customer code doesn't spin up 100 threads.
The SecurityManager allows one to prevent that.
Alternatives are not as elegant as it requires spinning up a new process and limiting, some functionality, by the access that the user has.
It is this one feature that I found made Java better than C#.
|
|
|
|
|
How do you separate large numbers in Java? I want to use something like commas.
I think this works in C++, but it doesn't work in Java:
int onebillion = 1'000'000'000;
Anyone know?
Thanks.
|
|
|
|
|
From Java 7 onwards, you can use the underscore in numeric literals. For instance, 1 million would be represented as 1_000_000. Documentation for this feature can be found here[^].
|
|
|
|
|
|
I am tryint to validate a password that has the following rules: can't be the same as username, at least 8 characters, and must have a uppercase letter and special character. Any help you can offer would be AMAZING!
import java.util.Scanner;
public class Main {
static String userName = "johndoe";
static String password = "ABC_1234";
static boolean validPassword = false;
public static void main(String[] args) {
System.out.println("Please Change Your Password");
System.out.println("""
Please make sure it is 8 characters long,
Contains an uppercase letter,
Contains a special character,
Does not contain your username,
And is not the same as the previous password
""");
checkPassword();
}
public static void checkPassword() {
System.out.println();
System.out.print("What is your new password? ");
Scanner scanner = new Scanner(System.in);
String newPassword = scanner.next();
while (!validPassword) {
if (newPassword.equalsIgnoreCase(userName)) {
System.out.println("Your password can't be the same as your username");
System.out.print("What is your new password? ");
newPassword = scanner.next();
}
if (newPassword.length() < 8) {
System.out.println("You password must be at least 8 characters");
System.out.print("What is your new password? ");
newPassword = scanner.next();
}
for (int i = 0; i < newPassword.length(); i++) {
char ch = newPassword.charAt(i);
if (!Character.isUpperCase(ch) || (Character.isDigit(ch) && Character.isLetter(ch) && Character.isWhitespace(ch))) {
System.out.println("Please make sure your password has an uppercase and/or special character");
newPassword = scanner.next();
validPassword = true;
} else {
System.out.println("stop");
validPassword = false;
}
}
}
}
}
modified 14-Jan-24 10:51am.
|
|
|
|
|
if (!Character.isUpperCase(ch) || (Character.isDigit(ch) && Character.isLetter(ch) && Character.isWhitespace(ch))) {
This if clause (and the following statements) does not make much sense as you are testing for multiple conditions existing at the same time. You need to test each character in turn and keep a count of the valid types (upper case, digit, special). Then when all characters have been tested check that each count is greater than zero to signify a valid password.
|
|
|
|
|
Ok... I will try that, I thought you could check for multiple conditions in that way as I saw it done that way somewhere.
|
|
|
|
|
No, it could never be done that way; look at the test:
if (!Character.isUpperCase(ch)
||
(Character.isDigit(ch)
&&
Character.isLetter(ch)
&&
Character.isWhitespace(ch))
So when this test fails (as it mostly will) you request a new password, but then set validPassword = true; , without checking anything else.
|
|
|
|
|
You're not handling your "validPassword" flag in all cases (setting / resetting). And the while loop should be in Main ... calling the check routine (which returns a result) and reading the next try if necessary.
"Before entering on an understanding, I have meditated for a long time, and have foreseen what might happen. It is not genius which reveals to me suddenly, secretly, what I have to say or to do in a circumstance unexpected by other people; it is reflection, it is meditation." - Napoleon I
|
|
|
|
|
Gotcha. So based on what you are describing, this is the reason the loop is running only once and not continuing until the valid result is met? I will try that. Thank you.
|
|
|
|
|
I am in IntelliJ IDEA. I want to view the disassembly of this code to see if it does two comparisons:
if (-0.0 == 0.0) System.out.println("they're equal");
Based on searching, it sounds like IntelliJ can't do that. Anyone know of a Java IDE that can do this?
Thank you.
|
|
|
|
|
At the command prompt in your directory enter the following command:
javap -c your_program_name
where "your_program_name " is the name of the class containing the compiled code.
If you want more information on the Java development utilities you can find it at Home: Java Platform, Standard Edition (Java SE) 8 Release 8[^].
|
|
|
|
|
In addition redirecting that to a file is probably going to be a good idea. Even a small class is going to have a lot of output.
|
|
|
|
|
True, but even so I doubt it will make a lot of sense to the OP.
|
|
|
|
|
Just curious why/how you expect two comparisons?
|
|
|
|
|
For doubles, I believe there is a positive zero and a negative zero.
|
|
|
|
|
There is only ever a single comparison made for each comparison operator, so if your code only has a single '==' operator, the JIT'd code will only generate a single IL comparison.
-0.0 does occur when a negative floating-point value is so small that is cannot be represented. That does NOT mean it's a different 0 from positive 0.0. You can see this is you try to convert an extremely small value to a string and output it. You can get -0.0.
If your code, the compiler will evaluate the comparison and optimize it out, replacing the expression with just 'true'. The resulting code, and what you see in the disassembly, will be very close to:
if (true) System.out.println("they're equal");
or, depending on code around this, maybe even:
System.out.println("they're equal");
If you want to know how numbers are represented in Java, and most other languages, read The IEEE Standard for Floating-Point Arithmetic (IEEE 754)[^]
modified 12-Jan-24 18:49pm.
|
|
|
|
|
Hi everyone! I want to integrate ChatGPT into my Spring Boot app. How can I do this?
|
|
|
|
|
Go to the ChatGPT website and ask them.
|
|
|
|