receiving ArrayIndexOutOfBoundsException but cannot figure out why - java

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.

Related

ArrayList for java

So, this is my question that I have to answer:
In the Payroll class, add a method with the header private int
computePay(Programmer p). The method should return the programmer’s
grade multiplied by the number of hours they worked. For example, if
the programmer’s grade is 2, and the total hours they worked is 6, the
method should return 12.
But my question for this forum is, how do I get a txt. file which contains Firstname Secondname,paygrade(Out of 3),hours,hours,hours,hours,hours,hours
(txt. example;
Sean Dyke,3,34,54,67,78,34,12
Fred Flintsone,1,65,78,89,89,34,23
Scooby Doo,2,54,56,67,87,89,65
)
To make the grade part separate to the hours they work, so I can then use
private int computePay(Programmer p){
return p.grade*p.hours;
}
I may have confused myself in this one, or thinking backwards, but any sort of guidelines would help.
I think the grade is after the name so you can split the array and take the values.
String[] temp = array1.split(",");
temp[0] gives name
temp[1] gives grade
temp[2...] gives hours worked
Well there are 2 ways of storing data in a .txt file:
You can put your object into an object stream and simply write that into a textfile.
FileOutputStream out = new FileOutputStream("test.txt");
ObjectOutputStream oout = new ObjectOutputStream(out);
// write something in the file
oout.writeObject(s);
// close the stream
oout.close();
Sadly the formating would be really bad and you could not read data on your own. Also that method is really inconsistent. You would need your class to implement Serializable. Furthmore, any change in your java code would stop making it possible to read that file.
So I would go for an attampt where you just store the name, followed by those hours. Then, read it line by line:
String s = "Sean Dyke,3,34,54,67,78,34,12"
String[] entries = s.split(",");
String name = entries[0];
Integer[] hours = new Integer[entries.length -1];
for(int i = 0; i < hours; i++){
hours[i] = Integer.parseInt(entries[i + 1]);
}
This could would parse one line. Do it for every line in your code txt file and you should be fine.

Why is there no output from the While loop in my code, despite everything else working?

I made this program in java, on the BlueJ IDE. It is meant to take a number in the decimal base and convert it into a base of the users choice, up till base 9. It does this by taking the modulus between two numbers and inserting it into a string. The code works till the input stage, after which there is no output. I am sure my maths is right, but the syntax may have a problem.
My code is as follows:
import java.util.*;
public class Octal
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int danum = 0;
int base = 0;
System.out.println("Please enter the base you want the number in (till decimal). Enter as a whole number");
base=in.nextInt(); //This is the base the user wants the number converted in//
System.out.println("Enter the number you want converted (enter in decimal)");
danum=in.nextInt(); //This is the number the user wants converted//
while ( danum/base >= base-1 && base < danum) {
int rem = danum/base; //The number by the base//
int modu = danum % base;//the modulus//
String summat = Integer.toString(modu);//this is to convert the integer to the string//
String strConverted = new String();//Making a new string??//
StringBuffer buff = new StringBuffer(strConverted);//StringBuffer command//
buff.insert(0, summat); //inserting the modulus into the first position (0 index)//
danum = rem;
if ( rem <= base-1 || base>danum) {//does the || work guys?//
System.out.println(rem + strConverted);
}
else {
System.out.println(strConverted);
}
}
}
}
I am very new to Java, so I am not fully aware of the syntax. I have done my best to research so that I don't waste your time. Please give me suggestions on how to improve my code and my skill as a programmer. Thanks.
Edit (previous answer what obviously a too quick response...)
String summat = Integer.toString(modu);
String strConverted = new String();
StringBuffer buff = new StringBuffer(strConverted);
buff.insert(0, summat);
...
System.out.println(strConverted);
Actually, strConverted is still an empty string, maybe you would rather than display buff.toString()
But I don't really understand why making all of this to just display the value of modu. You could just right System.out.println(modu).
I assume that you want to "save" your value and display your whole number in one time and not each digit a time by line.
So you need to store your number outside of while loop else your string would be init at each call of the loop. (and print outside)
So, init your StringBuffer outside of the loop. you don't need to convert your int to String since StringBuffer accept int
http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html#insert-int-int-
(You could even use StringBuilder instead of StringBuffer. It work the same except StringBuffer work synchronized
https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html)
Your if inside the loop is a specific case (number lower than base) is prevent before the loop since it's the opposite condition of your loop. (BTW : rem <= base-1 and base>danum are actually only one test since rem == danum at this place)
so :
StringBuffer buff = new StringBuffer();
if(base > danum) {
buff.append(danum);
} else {
while (danum / base >= base - 1 && base < danum) {
int rem = danum / base;
int modu = danum % base;
buff.insert(0, modu);
danum = rem;
}
if(danum > 0) {
buff.insert(0, danum);
}
}
System.out.println(buff.toString());
I would also strongly recommand to test your input before running your code. (No Zero for base, no letters etc...)
2 Things
do a lot more error checking after getting user input. It avoids weird 'errors' down the path
Your conversion from int to String inside the loop is wrong. Whats the whole deal summat and buff.... :: modifying the buffer doesnt affect the strConverted (so thats always empty which is what you see)
try to get rid of this. :)
error is logic related
error is java related
Your code has the following problems:
Firstly, you have declared and initialized your strConverted variable (in which you store your result) inside your while loop. Hence whenever the loop repeats, it creates a new string strConverted with a value "". Hence your answer will never be correct.
Secondly, the StringBuffer buff never changes the string strConverted. You have to change your string by actually calling it.
You print your result inside your while loop which prints your step-by-step result after every repetition. You must change the value of strConverted within the loop, nut the end result has to be printed outside it.

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. :)

if statement with integers [duplicate]

This question already has answers here:
Why does my if condition not accept an integer in java?
(7 answers)
Closed 3 years ago.
I'm new at Java. I'm looking for some help with homework. I wont post the full code I was doing that originally but I dont think it will help me learn it.
I have a program working with classes. I have a class that will validate a selection and a class that has my setters and getters and a class that the professor coded with the IO for the program (it's an addres book)
I have a statement in my main like this that says
//create new scanner
Scanner ip = new Scanner(System.in);
System.out.println();
int menuNumber = Validator.getInt(ip, "Enter menu number: ", 1, 3);
if (menuNumber = 1)
{
//print address book
}
else if (menuNumber = 2)
{
// get input from user
}
else
{
Exit
}
If you look at my if statement if (menuNumber = 1) I get a red line that tells me I cannot convert an int to boolean. I thought the answer was if (menuNumber.equals(1)) but that also gave me a similar error.
I'm not 100% on what I can do to fix it so I wanted to ask for help. Do I need to convert my entry to a string? Right now my validator looks something like:
if (int < 1)
print "Error entry must be 1, 2 or 3)
else if (int > 3)
print "error entry must 1, 2, or 3)
else
print "invalid entry"
If I convert my main to a string instead of an int wont I have to change this all up as well?
Thanks again for helping me I haven't been diong that great and I want to get a good chunk of the assignment knocked out.
if (menuNumber = 1)
should be
if (menuNumber == 1)
The former assigns the value 1 to menuNumber, the latter tests if menuNumber is equal to 1.
The reason you get cannot convert an int to boolean is that Java expects a boolean in the if(...) construct - but menuNumber is an int. The expression menuNumber == 1 returns a boolean, which is what is needed.
It's a common mix-up in various languages. I think you can set the Java compiler to warn you of other likely cases of this error.
A trick used in some languages is to do the comparison the other way round: (1 == menuNumber) so that if you accidentally type = you will get a compiler error rather than a silent bug.
This is known as a Yoda Condition.
In Java, a similar trick can be used if you are comparing objects using the .equals() method (not ==), and one of them could be null:
if(myString.equals("abc"))
may produce a NullPointerException if myString is null. But:
if("abc".equals(myString))
will cope, and will just return false if myString is null.
I get a red line that tells me I cannot convert an int to boolean.
Thats because = is an assignment operator. What you need to use is == operator.
A single equal sign is assignment: you assign value to a variable this way. use two equal signs (==) for comparison:
if ($menuNumber = 1) {
Update: forgot dollar sign: $menuNumber

beginner java, help me fix my program?

I am trying to make a calculator for college gpa's. I cut out all like 20 if statements that just say what each letter grade is. I fixed my first program for anybody looking at this again. The program now works, but regardless of the letters i type in the gpa it returns is a 2.0 . If anybody sees anything wrong it would be very much appreciated...again. Thanks
import java.util.Scanner;
public class universityGPA {
public static void main(String args[]){
int classes = 4;
int units[] = {3, 2, 4, 4};
double[] grade = new double[4];
double[] value= new double[4];
int counter = 0;
double total = 0;
double gpa;
String letter;
while(classes > counter){
Scanner gradeObject = new Scanner(System.in);
letter = gradeObject.next();
if(letter.equalsIgnoreCase("A+") || letter.equalsIgnoreCase("A")){
grade[counter] = 4;
}
if(letter.equalsIgnoreCase("F")){
grade[counter] = 0;
}
value[counter] = grade[counter] * units[counter];
counter++;
}
for(int i = 0; i < classes; i++ ){
total += value[i];
}
gpa = total/classes;
System.out.println("You gpa is " +gpa);
}
}
You forgot to initialize grade. The NullPointerException is telling you that grade is null. The exception is thrown the first time you try to use grade, in the statment grade[counter] = 4;. Allocate as much space as you need with new.
Initialization of grade can be done statically as well dynamically:
double []grade = new double[4];
or
double []grade = new double[classes];
Do the same for value as well.
Here are a few pointers for cleaning up your code:
Try to be more consistent with your formatting. Make sure everything is properly indented and that you don't have lingering spaces at the beginnings or endings of lines (line 18).
You should declare variables as close to the first spot you use them as possible. This, along with making your code much more readable, minimizes the scope. For instance, on line 18, you initialize letter, but it is never used outside the scope of the while statement. You should declare the variable right there, along with the initializer (String letter = gradeObject.next()).
Declaring arrays in the type name[] form is discouraged. It is recommended to use the type[] name form instead.
Try to separate your program into distinguished sections. For instance, for this program, you can clearly see a few steps are involved. Namely, you first must grab some input, then parse it, then calculate the return value. These sections can be factored out into separate methods to clean up the code and promote reuse. While it may not seem to yield many benefits for such a simple program, once you start working on larger problems this organization will be absolutely mandatory.
NullPointerException means you are trying to access something that does not exist.
Since your grade[] is null, accessing it on line 21 by grade[counter] actually means you are accessing something that has yet to be created.
You need to initialize the array, so it actually has an instance.

Categories

Resources