variable may have not been initialized? - java

so in the while loop i print some elements of the ArrayList Store. but afterwards when i call it, it says array may have not been initialized.
any thoughts? i'm trying to read a file of lines. each line has at least 8 elements, and i'm sure the array is not empty because i printed from it in the while loop.
?
public class ReaderFile {
public static Scanner input;
public static Scanner input2;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int count=0;
ArrayList<Team> store;
ArrayList<Robot> store2;
//Robot robot;
String fileLocation = "Tourney2Teams.csv";
String fileLocation2 = "Tourney1robots.csv";
try{
input = new Scanner(new File(fileLocation)).useDelimiter(",");
}
catch (IOException ioException)
{
System.out.print("PROBLEM");
}
try {
input2 = new Scanner(new File (fileLocation2)).useDelimiter(",");
}
catch (IOException ioException)
{
System.out.print("problem with robot");
}
try{
input.nextLine();
System.out.print("PLEAse\n");
int countt = 0;
while(input.hasNext())
{
//int countt = 0;
int ID = input.nextInt();
String teamName = input.next();
String coachFirst = input.next();
String coachLast = input.next();
String mentorFirst = input.next();
String mentorLast = input.next();
String teamFs = input.next();
String teamSS = input.next();
input.nextLine();
store = new ArrayList<>();
Team team = new Team (teamName, ID, coachFirst, coachLast,mentorFirst,mentorLast,teamFs,teamSS);
store.add(team);
System.out.print("Team Numer"+store.get(0).teamNumber+"\n");
countt = countt+1;
System.out.print("\n"+countt);
}
}
catch (NoSuchElementException statExcemtion)
{
System.out.print("\nAnkosh");
}
String x = store.get(2).teamName;
}
}

store = new ArrayList<>();
This line reinitializes the store at every pass in the while. You probably want to initialize it before the while to accumulate while looping.
It says it was not initialized because for some reason it never executed the while loop (empty input).

It can be uninitialized in two cases:
A NoSuchElementException exception is thrown in your try block, in which case your catch block is executed, and the store is not initialized. I would suggest to either return from the catch block, or move your String x = line inside the try block.
Your loop does zero iterations. In this case the store is also uninitialized. It also looks like a logic error, you probably want your store to be instantiated before the while loop.
I would also suggest to check that the store has at least three elements before accessing element 2.

Related

Not able to print out the Array Elements

This code is to get the firstName, LastName, and StudentID by reading it from a file and displaying the information in the main file. When I run my program, instead of printing the information of the students, it prints out a chain of characters and numbers.
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Student[] students = new Student[10];
getStudentData(students);
for (int i = 0; i < students.length; i++){
System.out.println(students[i]);
}
}
public static void getStudentData(Student[] students){
String infileName = "studentlist.txt";
Scanner reader = null;
try {
reader = new Scanner (new File(infileName));
int index = 0;
while(reader.hasNext()){
String oneLine = reader.nextLine();
String[] parts = oneLine.split(" ");
long studentID = Long.parseLong(parts[2]);
students[index] = new Student(parts[0],parts[1],studentID);
index++;
}
} catch (FileNotFoundException err) {
System.out.println(err);
} finally {
if (reader != null)
reader.close();
}
}
}
Have you defined a toString() method on your Student class?
You need to do this otherwise the default toString() implementation of the superclass for all classes (class Object) will be used which returns the name of the class concatenated with # and the hashcode of the class in hexadecimal format.
Add this method to your Student class and return a meaningful String containing the attribute values of a Student object instead of my descriptive String.
#Override
public String toString() {
return "return a string here that represents the student and his/ her attribute values";
}
FYI: Many IDEs can generate an arbitrary toString() method for you.
See the this thread for more details on Object::toString().

Array *not throwing out of bounds exception

I'm trying to learn about exception handling. I can't seem to get
String[] a = names(scnr); To throw an out of bounds exception when it goes beyond 3 elements. I know, most people hate the out of bounds error and I'm trying to make it happen and for the life of me I cannot figure out what I'm doing wrong. Been at it all day and googled all kinds of stuff. But I cannot seem to find exactly what I'm looking for. So I could use some help and perspective.
So I'm inputting a full string that I'm delimiting (trim and splitting) based on commas and spaces and then the pieces are being stored into an array (String []name), then passed to main to be output with String[] a. So it's not erroring when I go beyond 3 elements no matter how I do it. I can just not display anything beyond a[4]. But that's not really what I'm trying to do. Its my first java class so be gentle haha.
Any suggestions?
import java.util.*;
public class ReturnArrayExample1
{
public static void main(String args[])
{
Scanner scnr = new Scanner(System.in);
String[] a = names(scnr);
for (int i = 0; i < 3; i++)
{
System.out.println(a[i] + " in index[" + i + "].");
}
scnr.close();
}
public static String[] names(Scanner scnr)
{
String[] name = new String[3]; // initializing
boolean run = true;
do
{
try
{
System.out.println("Enter 3 names separated by commas ',':(Example: keith, mark, mike)");
String rawData = scnr.nextLine();
if(rawData.isEmpty())
{
System.err.println("Nothing was entered!");
throw new Exception();
}
else
{
name = rawData.trim().split("[\\s,]+");
run = false;
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.err.println("Input is out of bounds!\nUnsuccessful!");
}
catch(Exception e)
{
System.err.println("Invalid entry!\nUnsuccessful!");
}
}
while(run == true);
System.out.println("Successful!");
scnr.close();
return name;
}
}
If I understand you correctly, you want to throw an ArrayOutOfBoundsException if the names array does not contain exactly 3 elements. The following code is the same as the one you wrote with an if-statement to do just that.
import java.util.*;
public class ReturnArrayExample1
{
public static void main(String args[])
{
Scanner scnr = new Scanner(System.in);
String[] a = names(scnr);
for (int i = 0; i < 3; i++)
{
System.out.println(a[i] + " in index[" + i + "].");
}
scnr.close();
}
public static String[] names(Scanner scnr)
{
String[] name = new String[3]; // initializing
boolean run = true;
do
{
try
{
System.out.println("Enter 3 names separated by commas ',':(Example: keith, mark, mike)");
String rawData = scnr.nextLine();
if(rawData.isEmpty())
{
System.err.println("Nothing was entered!");
throw new Exception();
}
else
{
name = rawData.trim().split("[\\s,]+");
if (name.length != 3) {
throw new ArrayIndexOutOfBoundsException();
}
run = false;
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.err.println("Input is out of bounds!\nUnsuccessful!");
}
catch(Exception e)
{
System.err.println("Invalid entry!\nUnsuccessful!");
}
}
while(run == true);
System.out.println("Successful!");
scnr.close();
return name;
}
}
If you want java to throw an ArrayIndexOutOfBoundException you have to preserve the created names instance and let java copy the array into your names array:
String[] names=new String[3];
String[] rawElements=rawData.trim().split("[\\s,]+");
System.arraycopy(rawElements, 0, names, 0, rawElements.length);
output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
at java.lang.System.arraycopy(Native Method)
at stackoverflow.OutOfBound.main(OutOfBound.java:8)
As far as I understand, you are expecting an exception (ArrayIndexOutOfBoundsException) to the thrown at line
name = rawData.trim().split("[\\s,]+");
with an argument that the size of array (name) is fixed to 3, and when if the input is beyond 3 then the exception must be thrown; which is not the case.
The reason is in the way assignment happens in java. When you declare String[] name = new String[3];, then an object is created in java heap and its reference is assigned to variable name which is in stack memory.
And when this line name = rawData.trim().split("[\\s,]+"); gets executed then a new array object is created in heap and the variable name starts pointing to the newly created array object on heap. Note: the old object will get available for garbage collection after some time.
This eventually changes the length of the array variable (name) and you do not get any ArrayIndexOutOfBoundsException.
You can understand this more clearly by printing the object on console, like System.out.println(name); after its initialisation and post its assignment.
I will also suggest you to refer this link (https://books.trinket.io/thinkjava2/chapter7.html#elements) to understand how array are created, initialised and copied etc..
Code with system.out commands (for understanding)
import java.util.Scanner;
public class ReturnArrayExample1 {
public static void main(String args[]) {
Scanner scnr = new Scanner(System.in);
String[] a = names(scnr);
System.out.println("Variable (a) is referring to > " + a);
for (int i = 0; i < 3; i++) {
System.out.println(a[i] + " in index[" + i + "].");
}
scnr.close();
}
public static String[] names(Scanner scnr) {
String[] name = new String[3]; // initializing
System.out.println("Variable (name) is referring to > " + name);
boolean run = true;
do {
try {
System.out.println("Enter 3 names separated by commas ',':(Example: keith, mark, mike)");
String rawData = scnr.nextLine();
if (rawData.isEmpty()) {
System.err.println("Nothing was entered!");
throw new Exception();
} else {
name = rawData.trim().split("[\\s,]+");
System.out.println("Now Variable (name) is referring to > " + name);
run = false;
}
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Input is out of bounds!\nUnsuccessful!");
} catch (Exception e) {
System.err.println("Invalid entry!\nUnsuccessful!");
}
} while (run == true);
System.out.println("Successful!");
scnr.close();
return name;
}
}
I you want to throw exception when input is more than 3 then there are many ways to do it. One suggestion from #mohamedmoselhy.com is also decent.

Creating array from reading a file

I have a file with the following:
5
212:Float On:Modest Mouse
259:Cherub Rock:Smashing Pumpkins
512:Won't Get Fooled Again:The Who
417:Teen Age Riot:Sonic Youth
299:PDA:Interpol
I need to create a array but I need to take into account the integer it starts with, then read the rest as strings taking into account the initial line containing only an integer. I've made the method to read the file and print, just don't know how to split it up.
An example of how to do it:
String s = "212:Float On:Modest Mouse"; // your input - a line from the file
String[] arr = s.split(":");
System.out.println(arr[0]); // your int
// The rest of the array elements will be the remaining text.
// You can concatenate them back into one string if necessary.
you can read file using Scanner
readlines = new Scanner(filename);
while(readlines.hasNextLine())
{
String line = readlines.nextLine();
String[] values = line.split(":");
int firstColumn = -1;
if (values.length > 0) {
try {
firstColumn = Integer.parseInt(values[0]);
} catch (NumberFormatException ex) {
// the value in the first column is not an integer
}
}
}
I've grown a habit of reading the entire file into a List, then handling the List in memory. Doing this is not the only option.
Once I have the file read in, I look at the first line to know how many tracks to expect in the remaining file. I then would loop through the remaining List to either get the number of tracks from the first line or until I reach the end of the list, in the event that the number of tracks (from the first line) exceeds the actual amount of tracks that are in the file.
As I go through the tracks I would use substring to break the line apart, and convert just the first part.
Update
Base on your comment, I've updated to use split instead of substring. Then some basic alignment formatting for output
public static void main(String[] args) throws Exception {
String yourFile = "path to your file.txt";
List<String> yourFileLines = new ArrayList<>(Files.readAllLines(Paths.get(yourFile)));
// You know the first line is suppose to be the number of tracks so convert it to a number
int numberOfTracks = Integer.valueOf(yourFileLines.get(0));
// Either go to the number of tracks or till the end of file
List<Track> tracks = new ArrayList<>();
for (int i = 1; (i <= numberOfTracks && i < yourFileLines.size()); i++) {
String currentFileLine = yourFileLines.get(i);
String[] currentFileLinePieces = currentFileLine.split(":");
Track currentTrack = new Track();
currentTrack.TrackTime = Integer.valueOf(currentFileLinePieces[0]);
currentTrack.TrackTitle = currentFileLinePieces[1];
currentTrack.TrackArtist = currentFileLinePieces[2];
tracks.add(currentTrack);
}
System.out.println(String.format("%-20s\t\t%-20s\t\t%-20s", "TITLE", "ARTIST", "TIME"));
System.out.println(String.format("%-20s\t\t%-20s\t\t%-20s", "-----", "------", "----"));
for (Track currentTrack : tracks) {
System.out.println(currentTrack);
}
}
public static class Track {
public int TrackTime;
public String TrackTitle;
public String TrackArtist;
#Override
public String toString() {
return String.format("%-20s\t\t%-20s\t\t%-20d", TrackTitle, TrackArtist, TrackTime);
}
}
Results:
Here's an example using a Scanner, and breaking everything into methods. You should be able to use List and ArrayList. Results are the same.
public static void main(String[] args) throws Exception {
String yourFile = "data.txt";
List<String> yourFileLines = readFile(yourFile);
if (yourFileLines.size() > 0) {
// You know the first line is suppose to be the number of tracks so convert it to a number
int numberOfTracks = Integer.valueOf(yourFileLines.get(0));
List<Track> tracks = getTracks(numberOfTracks, yourFileLines);
printTracks(tracks);
}
}
public static List<String> readFile(String pathToYourFile) {
List<String> yourFileLines = new ArrayList();
try {
File yourFile = new File(pathToYourFile);
Scanner inputFile = new Scanner(yourFile);
while(inputFile.hasNext()) {
yourFileLines.add(inputFile.nextLine().trim());
}
} catch (Exception e) {
System.out.println(e);
}
return yourFileLines;
}
public static List<Track> getTracks(int numberOfTracks, List<String> yourFileLines) {
List<Track> tracks = new ArrayList();
// Either go to the number of tracks or till the end of file
for (int i = 1; (i <= numberOfTracks && i < yourFileLines.size()); i++) {
String currentFileLine = yourFileLines.get(i);
String[] currentFileLinePieces = currentFileLine.split(":");
Track currentTrack = new Track();
currentTrack.TrackTime = Integer.valueOf(currentFileLinePieces[0]);
currentTrack.TrackTitle = currentFileLinePieces[1];
currentTrack.TrackArtist = currentFileLinePieces[2];
tracks.add(currentTrack);
}
return tracks;
}
public static void printTracks(List<Track> tracks) {
System.out.println(String.format("%-20s\t\t%-20s\t\t%-20s", "TITLE", "ARTIST", "TIME"));
System.out.println(String.format("%-20s\t\t%-20s\t\t%-20s", "-----", "------", "----"));
for (Track currentTrack : tracks) {
System.out.println(currentTrack);
}
}
public static class Track {
public int TrackTime;
public String TrackTitle;
public String TrackArtist;
#Override
public String toString() {
return String.format("%-20s\t\t%-20s\t\t%-20d", TrackTitle, TrackArtist, TrackTime);
}
}

How do I have a program create its own variables with Java?

I would like to start off by saying that if this is common knowledge, please forgive me and have patience. I am somewhat new to Java.
I am trying to write a program that will store many values of variables in a sort of buffer. I was wondering if there was a way to have the program "create" its own variables, and assign them to values.
Here is an Example of what I am trying to avoid:
package test;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
int inputCacheNumber = 0;
//Text File:
String userInputCache1 = null;
String userInputCache2 = null;
String userInputCache3 = null;
String userInputCache4 = null;
//Program
while (true) {
Scanner scan = new Scanner(System.in);
System.out.println("User Input: ");
String userInput;
userInput = scan.nextLine();
// This would be in the text file
if (inputCacheNumber == 0) {
userInputCache1 = userInput;
inputCacheNumber++;
System.out.println(userInputCache1);
} else if (inputCacheNumber == 1) {
userInputCache2 = userInput;
inputCacheNumber++;
} else if (inputCacheNumber == 2) {
userInputCache3 = userInput;
inputCacheNumber++;
} else if (inputCacheNumber == 3) {
userInputCache4 = userInput;
inputCacheNumber++;
}
// And so on
}
}
}
So just to try to summarize, I would like to know if there is a way for a program to set an unlimited number of user input values to String values. I am wondering if there is a way I can avoid predefining all the variables it may need.
Thanks for reading, and your patience and help!
~Rane
You can use Array List data structure.
The ArrayList class extends AbstractList and implements the List
interface. ArrayList supports dynamic arrays that can grow as needed.
For example:
List<String> userInputCache = new ArrayList<>();
and when you want to add each input into your array like
if (inputCacheNumber == 0) {
userInputCache.add(userInput); // <----- here
inputCacheNumber++;
}
If you want to traverse your array list you can do as follows:
for (int i = 0; i < userInputCache.size(); i++) {
System.out.println(" your user input is " + userInputCache.get(i));
}
or you can use enhanced for loop
for(String st : userInputCache) {
System.out.println("Your user input is " + st);
}
Note: it is better to put your Scanner in your try catch block with resource so you will not be worried if it is close or not at the end.
For example:
try(Scanner input = new Scanner(System.in)) {
/*
**whatever code you have you put here**
Good point for MadProgrammer:
Just beware of it, that's all. A lot of people have multiple stages in their
programs which may require them to create a new Scanner AFTER the try-block
*/
} catch(Exception e) {
}
For more info on ArrayList
http://www.tutorialspoint.com/java/java_arraylist_class.htm

Changing a String into an int

I have an array of string objects that was read from a file. Some of these strings I need to use as ints. I wrote a method to read the file but now I just don't know how to get the numbers from the file, here is the file
29,,
Chute,1,0
Chute,2,0
Chute,3,0
Chute,4,0
Chute,5,0
Chute,6,0
Chute,7,0
Chute,8,0
Chute,9,0
Chute,0,1
Chute,0,2
Chute,0,3
Chute,9,1
Chute,9,2
Chute,9,3
Ladder,0,5
Ladder,1,5
Ladder,2,5
Ladder,3,5
Ladder,4,5
Ladder,5,5
Ladder,6,5
Ladder,7,5
Ladder,8,5
Ladder,9,5
Ladder,9,6
here is my method
public void readBoard(String file)throws FileNotFoundException
{
File clboard = new File ("myBoard.csv");
Scanner x = new Scanner(clboard);
while(x.hasNext())
{
String c = x.nextLine();
String [] myboard =c.split(",");
}
}
Try
int numOne = Integer.parseInt(myboard[1]);
int numTwo = Integer.parseInt(myboard[2]);
immediately after your split line.
String [] myboard = c.split(",");
if (myboard.length < 3) {
// error message
} else {
int i1 = Integer.parseInt(myboard[1]);
int i2 = Integer.parseInt(myboard[2]);
}
You might also want to add a try/catch to handle NumberFormatException (which occurs when you try to convert something that isn't a number).
public void readBoard(String file)throws FileNotFoundException
{
File clboard = new File ("myBoard.csv");
Scanner x = new Scanner(clboard);
while(x.hasNext()) {
List<Integer> number = new ArrayList<Integer>();
String c = x.nextLine();
String [] myboard =c.split(",");
for (String candid8 : myboard) {
try {
number.add(Integer.parseInt(candid8));
} catch (NumberFormatException e) {
}
}
}
}
Your numbers will now be in the number object, which is a List. If it's a more complex grammar, look into jflex, as that seems to be the recommendation of Google.

Categories