why I am getting ArrayIndexOutOfBoundsException? - java

Hi I am unable to know what I am doing wrong.
I have a string which is pass as an argument to a my class.
I have to split that string and assign the respective values to the member variable but it is not working properly.
Here is my class.
package virtusa;
public class pratice {
String getName;
Double getPrice;
int getQuantity;
String temp[] = null;
public pratice()
{
}
public pratice(String rawInput)
{
temp = rawInput.split("$$##",2);
getName = temp[0];
getPrice = Double.parseDouble(temp[1]);
getQuantity =Integer.parseInt( temp[2]);
}
public String getGetName() {
return getName;
}
public Double getGetPrice() {
return getPrice;
}
public int getGetQuantity() {
return getQuantity;
}
}
here is my main class
package virtusa;
import java.util.Scanner;
public class demo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String stub = in.nextLine();
pratice temp = new pratice(stub);
System.out.println(temp.getName);
System.out.println(temp.getQuantity);
System.out.println(temp.getPrice);
}
}
My Input = apple$$##12.5$$##9
error i am having -
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
at virtusa.pratice.<init>(pratice.java:17)
at virtusa.demo.main(demo.java:12)

String::split take regex as a parameter, so the $ has special meaning. You will need to escape it with a \

One of problems in your code in not escaping special characters as some comments are mentioning. In my opinion clearest solution is to use Patter quote
rawInput.split(Pattern.quote("$$##"), 3);
Other problem is that you clearly need to get there elements since you are trying to get temp[0], temp[1] and temp[2]
So the final code should look something like this
String getName;
Double getPrice;
int getQuantity;
String temp[] = null;
public Practice() {
}
public Practice(final String rawInput) {
temp = rawInput.split(Pattern.quote("$$##"), 3);
getName = temp[0];
getPrice = Double.parseDouble(temp[1]);
getQuantity = Integer.parseInt(temp[2]);
}
public String getGetName() {
return getName;
}
public Double getGetPrice() {
return getPrice;
}
public int getGetQuantity() {
return getQuantity;
}

Related

Arrays of Object test but not getting any output

I would like some guidance on this particular code that I am testing but currently it is not printing out anything and on top of that I feel as if it isn't reading the text file at all. It seems to finish right away with no errors and I only get prompted that "build is successful."
The assignment is to read from a data text file that list 20 lines of student information, each line is comprised of first name, last name, and their grade all seperated by spaces. I am put to it into an array and output their information, but for now I am testing to see if it will output the first name before I proceed.
public class studentClass {
private String studentFName, studentLName;
private int testScore;
private char grade;
//constructor
public studentClass(String stuFName, String stuLName, int stuTestScore){
studentFName = stuFName;
studentLName = stuLName;
testScore = stuTestScore;
}
public String getStudentFName(){
return studentFName;
}
public String getStudentLName(){
return studentLName;
}
public int getTestScore(){
return testScore;
}
public char getGrade(){
return grade;
}
public void setStudentFName(String f){
studentFName = f;
}
public void setStudentLName(String l){
studentLName = l;
}
public void setTestScore(int t){
if (t>=0 && t<=100){
testScore = t;
}
}
public void setGrade(char g){
grade = g;
}
}
public static void main(String[] args) throws IOException {
int numberOfLines = 20;
studentClass[] studentObject = new studentClass[numberOfLines];
for(int i = 0; i>studentObject.length; i++){
System.out.print(studentObject[i].getStudentFName());
}
}
public static studentClass[] readStudentData(studentClass[] studentObject)throws IOException{
//create FileReader and BufferedReader to read and store data
FileReader fr = new FileReader("/Volumes/PERS/Data.txt");
BufferedReader br = new BufferedReader (fr);
String lines = null;
int i = 0;
//create array to store data for firstname, lastname, and score
while ((lines = br.readLine()) != null){
String stuArray[] = lines.split(" ");
String stuFName = stuArray[0];
String stuLName = stuArray[1];
int score = Integer.parseInt(stuArray[2]);
studentObject[i] = new studentClass (stuFName, stuLName, score);
i++;
}
return studentObject;
}
You need to actually call the method to read in the data. Try the following (note I didn't handle the Exception. I leave that as an exercise to you)
public static void main(String[] args) throws IOException {
int numberOfLines = 20;
studentClass[] studentObject = new studentClass[numberOfLines];
readStudentData(studentObject);
//NOTE I CHANGED THE '>' TO '<'
for(int i = 0; i < studentObject.length; i++){
System.out.print(studentObject[i].getStudentFName());
}
}
//Note that I changed the return type to void
public static void readStudentData(studentClass[] studentObject)throws IOException{
//Your code here
You'll see I changed your readStudentData to return void since you're passing the array into the method you don't need to return it. You'll need to remove the return at the end of it.
You could also leave it as a method returning a studentClass[] and have no parameters. Instead, create the studentClass array inside readStudentData. I would recommend that approach because it removes the need to create and pass the array, which complicates your main method.

Java arrayList variables

I am doing a homework assignment for my Java class. My instructor has some very defined requirements about what method calls and variables to use. One of the requirements is to write a method called public void initalizeSymbols(String inputFileName) that reads from an input file each letter of the alphabet and their morse code equivalent. I am trying to insure the variables are being passed to the arraylist, which we have to use, but can't get my System.out.println(input.toString()); to output anything which leads me to believe my variables arent being saved into the arrayList. The arrayList will be storing a-z, 1-0, ? / and all of their equivalent Morse code symbols which are made up of ... and ---. So it will be storing both strings and integers. Any help would be appreciated. I apologize if this is not in the right format since it is the first time I've posted here. Here is what I have:
public class MorseCodeTranslator
{
private String sentence;
private String translation;
private ArrayList<MorseCodeSymbol> morseCodeSymbols;
Scanner scannerIn;
public void initializeSymbols(String inputFileName)
{
String inputLine = "";
String letter = "";
String symbol = "";
try
{
scannerIn = new Scanner(new File(inputFileName));
while (scannerIn.hasNext())
{
inputLine = scannerIn.nextLine();
letter = inputLine.substring(0, inputLine.indexOf(' '));
symbol = inputLine.substring(inputLine.indexOf(' ') + 1);
MorseCodeSymbol input = new MorseCodeSymbol(letter, symbol);
morseCodeSymbols.add(input);
System.out.println(input.toString()); //this doesnt work
//System.out.println(letter + symbol); //this works
}
//MorseCodeSymbol input = new MorseCodeSymbol(" "," ");
//morseCodeSymbols.add(input);
}
catch (Exception ex)
{
}
//displayMorse();
}
}
public class MorseCodeSymbol
{
private String letter;
private String symbol;
public MorseCodeSymbol()
{
setLetter("");
setSymbol("");
}
public MorseCodeSymbol(String letter, String symbol)
{
this.letter = letter;
this.symbol = symbol;
}
public String getLetter()
{
return letter;
}
public String getSymbol()
{
return symbol;
}
public void setLetter(String letter)
{
this.letter = letter;
}
public void setSymbol(String symbol)
{
this.symbol = symbol;
}
public String toString()
{
return String.format("Letter: %s Symbol: %s", letter, symbol);
}
}
Figured it out, I needed to initialize the arrayList under the method initialzeSymbols. I knew it was something super simple I was overlooking

Java Error; array required, but java.lang.String found

I am currently trying to complete this program and I'm having trouble with this error. I've done many things trying to fix it so I can compile it but it won't work. It seems that the "String alphabet" is getting the error. Can someone help me solve this please?
import java.util.Scanner;
public class Period
{
private static String phrase;
private static String alphabet;
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
String userInput;
int[] letter = new int [27];
int number = keyboard.nextInt();
System.out.println("Enter a sentence with a period at the end.");
userInput = keyboard.nextLine();
userInput.toLowerCase();
}
public void Sorter(String newPhrase)
{
phrase=newPhrase.substring(0,newPhrase.indexOf("."));
}
private int charToInt(char currentLetter)
{
int converted=(int)currentLetter-(int)'a';
return converted;
}
private void writeToArray()
{
char next;
for (int i=0;i<phrase.length();i++)
{
next=(char)phrase.charAt(i);
sort(next);
}
}
private String cutPhrase()
{
phrase=phrase.substring(0,phrase.indexOf("."));
return phrase;
}
private void sort(char toArray)
{
int placement=charToInt(toArray);
if (placement<0)
{
alphabet[26]=1;
}
else
{
// here is one spot that mainly the error pops up?
alphabet[placement]=alphabet[placement]+1;
}
}
public void entryPoint()
{
writeToArray();
displaySorted();
}
private void displaySorted()
{
for (int q=0; q<26;q++)
{
System.out.println("Number of " + (char)('a'+q) +"'s: "+alphabet[q]);
}
}
}
Your sort method is treating alphabet (the String) as an array. String is not a char[] but you can call String.toCharArray() like
private void sort(char toArray)
{
char[] alpha = alphabet.toLowerCase().toCharArray();
int placement=charToInt(toArray);
if (placement<0)
{
alpha[26]=1;
}
else
{
alpha[placement]=alpha[placement]+1;
}
alphabet = new String(alpha, "UTF-8");
}
But modifying a String is not possible, because they are immutable. For the same reason your raw call alphabet.toLowerCase() doesn't modify the alphabet in your other method.
The variable alphabet is defined as a String data type, but you need to define it as an array if you want to reference it using the bracket notation [] you have in your code. The error message is pretty clear in this case.
String[] example = new String[3];
example[0] = "Hello";
example[1] = "ETC...";

Error in my Word program in Java

This is my code and it compiles fine but when I try to create a string it says
Error: cannot find symbol - variable racer
public class Word {
private String original;
public Word(String s) {
original = s;
}
public String reverse () {
String reverse= "";
int x = 1;
int length = original.length();
while (length - x >= 0) {
reverse = reverse + original.substring(length -x);
x++;
}
return reverse;
}
public boolean isPalindrome() {
if(original.equals(reverse()))
return true;
else
return false;
}
}
The stated problem is not in the code posted - my guess is irrelephant's comment is correct, ie change new Word(racer) --> new Word("racer").
But I offer this to eliminate any chance of any errors in your code by basically eliminating your code:
public class Word {
private String original;
public Word(String s) {
original = s;
}
public boolean isPalindrome()
return new StringBuilder(original).reverse().toString().equals(original);
}
}
or if you must expose a reverse() method:
public class Word {
private String original;
public Word(String s) {
original = s;
}
public String reverse () {
return new StringBuilder(original).reverse().toString();
}
public boolean isPalindrome()
return reverse().equals(original);
}
}
I don't see the variable racer anywhere, but since you're using reverse inside a method, I'd recommend making it
Most likely, racer was never defined
Either that or the method was called w/o quotes
isPalindrome(racer)//note the lack of quotes
change reverse() to this
private() String reverse () {
String reverse= "";
int x = 1;
int length = original.length();
while (length - x >= 0) {
reverse = reverse + original.substring(length -x);
x++;
}
return reverse;

How to return multiple numbers in an array, in a single print statement

public class Main {
public static void main(String[] args) {
java.util.ArrayList<StudentDataArray> info = new java.util.ArrayList<StudentDataArray>();
int amountOfPeople = KeyboardInput.promptForInt("Enter how many people you plan to enter into the list.");
for(int a=0;a<amountOfPeople;a++) {
try {
double[] grade = new double[5];
grade[0]=KeyboardInput.promptForDouble("Enter the First grade");
grade[1]=KeyboardInput.promptForDouble("Enter the Second grade");
grade[2]=KeyboardInput.promptForDouble("Enter the Third grade");
grade[3]=KeyboardInput.promptForDouble("Enter the Fourth grade");
grade[4]=KeyboardInput.promptForDouble("Enter the Fifth grade");
info.add(new StudentDataArray(KeyboardInput.promptForString("Enter the First Name"),KeyboardInput.promptForString("Enter the Last Name"),grade,KeyboardInput.promptForChar("Enter the Final Grade")));
}catch(IllegalArgumentException e){
System.out.println("Hello World :)");
}
}
for(int b=0;b<amountOfPeople;b++) {
System.out.printf("%-10s %-10s %-3f %-3s",info.get(b).getFN(),info.get(b).getLN(),info.get(b).getTS(),info.get(b).getFG());
}
}
}
public class StudentDataArray {
private String firstName;
private String lastName;
private double[] testScore;
private char finalGrade;
public StudentDataArray(String FN, String LN, double[] TS, char FG) {
firstName = FN;
lastName = LN;
testScore = TS;
finalGrade = FG;
}
public void setFN(String FN) {firstName = FN;};
public void setLN(String LN) {lastName = LN;}
public void setTS(double[] TS) {testScore = TS;}
public void setFG(char FG) {finalGrade = FG;}
public String getFN() {return firstName;};
public String getLN() {return lastName;}
public String getTS() {
for(int a=0;a<testScore.length;a++) {
return testScore[a]+" ";
}
return null;
}
public char getFG() {return finalGrade;}
}
Hey guys, this is my code for all to look at. What im trying to do is to return multiple doubles into one spot in the code. what it will look like is...
Ethan Michael 10 20 30 40 50 A
where this is all displayed in one statement
[10 20 30 40 50]
Since I am using a double[] i wasnt sure how to go about this.
Thanks guys!
you can use a for statement to concatenate all the info into one variable and then print it.
Here's how you do it in one neat line:
String s = Arrays.toString(testScores).replaceAll("[\\[\\],]", "");
You can use this expession (ie everything to the right of the equals dign) in-line wherever you need the string.
The key points of this are to use [Arrays.toString()][1], which produces a string like "[10, 20, 30, 40, 50]", then calling String.replaceAll() to strip out all the punctuation.
Lots of answers but none use a StringBuilder, which is recommended instead of concatenation in loops. It doesn't create a new String object in each iteration, so it is a lot easier on resources. As such:
public String getTS() {
StringBuilder sb = new StringBuilder();
for(int a=0;a<testScore.length;a++) {
sb.append(testScore[a]+" ");
}
return sb.toString();
}
It seems you would need something like this:
public String getTS() {
returnString := "";
for(int a=0;a<testScore.length;a++) {
returnString += testScore[a]+" ";
}
return returnString;
}
public String getTS() {
yourString:= "";
for(int a=0;a<testScore.length;a++) {
yourString+= testScore[a]+" ";
}
return ts;
}
I think the simplest thing would be to convert GetTS() to something like this:
public String getTS() {
String ts = "";
for(int a=0;a<testScore.length;a++) {
ts += testScore[a]+" ";
}
return ts;
}
Note that your format string in Main.java should then change to "%-10s %-10s %-3s %-3s".

Categories