package statescapitalquizz;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
*
* #author Steve
*/
public class Statescapitalquizz {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String fileName = "Capitals.txt";
boolean found = false;
Scanner kb = new Scanner(System.in);
String target;
int n = 50;
String[] states = new String[n];
String[] capitals = new String[n];
try (Scanner inputStream = new Scanner(new FileInputStream(fileName))) {
for (int i = 0; i < n; i++) {
states[i] = inputStream.nextLine();
capitals[i] = inputStream.nextLine();
}
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
System.out.println("Please enter the name of a state: ");
target = kb.nextLine();
// the loop coninues to the end of the array if the city is not found
for (n=0; (!found) && (n < states.length) ; n++) {
if (states[n].matches(target)) {
//print found message and set found to true
System.out.println("The capital of " + target + " is"); //Where I need help
found = true;
} // end if
} // for loop
// after the loop – if not(found) print not found message
if (!found)
System.out.println(target + "is not a state in the United States");
}
}
Okay so the part I need help is how to retrieve the matching 'capital' to the 'state' that was entered by the user. My output statement is basically
//print found message and set found to true
System.out.println("The capital of " + target + " is" + ); //Where I need help
found = true;
} // end if
} // for loop
And I don't know what code to put in the output statement so it cross references my second array and puts the matching Capital from the State the user entered.
System.out.println("The capital of " + target + " is " + capitals[n]);
As mentioned in the comments to my question, is the answer.
Related
I'm using an arraylist to append inputs and send the arraylist elements to file. However, everytime I exit the program and run it again, the contents in the written in the file becomes empty.
ArrayList<String> memory = new ArrayList<String>();
public void fileHandling() {
try {
FileWriter fWriter = new FileWriter("notes.data");
for (int x = 0; x <= memory.size() - 1; x++) {
fWriter.write(memory.get(x) + '\n');
}
fWriter.close();
} catch (IOException e) {
System.out.println(e);
}
}
public void createNote() {
Scanner insertNote = new Scanner(System.in);
LocalDate todayDate = LocalDate.now();
LocalTime nowTime = LocalTime.now();
String timeFormat = nowTime.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM));
String dateTime = todayDate.toString() + " at " + timeFormat;
while (true) {
System.out.println();
System.out.println("Enter a note");
System.out.print("> ");
String note = insertNote.nextLine();
if (note == null) {
System.out.println("Invalid input! Try again");
break;
} else {
memory.add(note + " /" + dateTime);
fileHandling();
System.out.println("Note is saved!\n");
break;
}
}
I expect the program to save the contents of every input. Then if I exit and run the program again, the contents will go back to the array
Your code currently does the following:
You enter something (X) for the first time:
It gets added to the ArrayList
The ArrayList gets written into the file
Your file now contains: X
You enter something second (Y):
It gets added to the ArrayList (Which now contains: X, Y)
The ArrayList gets written into the file
Your file now contains: X + newline + Y
Your Problem is, that everytime you create a new FileWrite it overwrites your file.
This can be avoided by using the constructor like this:
FileWriter writer = new FileWriter("notes.data", true);
This sets it into the append mode and therefore keeps previous data in the file
You don't need to create a separate Scanner, in method createNote(), in order to get a "note" from the user.
It is usually better to write your code using the interface rather than the specific implementation because then you usually need to change less code if you decide to change the implementation. Hence the type for member variable memory should probably be List rather than ArrayList.
Note that ArrayList may waste memory if the list of "note"s is large. I suggest using LinkedList instead. Alternatively, use an array (rather than a List) and handle expanding the array when adding a "note" as well as reducing the array when removing a "note".
Having an infinite loop, i.e. while (true), which contains a single if-else where both the if block and the else block contain break statements, means that the loop will perform exactly one iteration. May as well remove the while loop – which means also removing the break statements.
Rather than writing the code that generates a timestamp repeatedly, you should adopt the DRY principle and extract that code into a separate method.
The file name should be a constant so as to minimize the amount of code changes you will need to do if you decide to change the file name.
By convention, text files have a filename extension of .txt whereas binary files have the .data extension.
Although you don't need to, I personally prefer to initialize class member variables in the constructor.
The below code is a SSCCE, hence I added a main method. More notes appear after the code.
package Methods;
import java.util.*;
import java.time.format.*;
import java.time.*;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class FileSys {
private static final String FILENAME = "notes.txt";
private static final String CREATE = "C";
private static final String DELETE = "D";
private static final String FIND = "F";
private static final String QUIT = "Q";
private static final String SHOW = "S";
private static final String UPDATE = "U";
Scanner reader;
List<String> memory;
public FileSys() throws IOException {
reader = new Scanner(System.in);
memory = new LinkedList<String>();
loadFile();
}
public void fileHandling() {
Path path = Paths.get(FILENAME);
try (BufferedWriter bw = Files.newBufferedWriter(path,
StandardOpenOption.CREATE,
StandardOpenOption.WRITE);
PrintWriter pw = new PrintWriter(bw)) {
for (String write : memory) {
pw.println(write);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
public void createNote() {
String dateTime = getTimestamp();
System.out.println();
System.out.println("Enter a note");
System.out.print("> ");
String note = reader.nextLine();
memory.add(note + " / " + dateTime);
fileHandling();
System.out.println("Note is saved!");
}
public void searchNote() {
System.out.print("\nEnter note number: ");
try {
int search = reader.nextInt();
reader.nextLine();
System.out.println("\nSearch result:");
int index = memory.indexOf(memory.get(search - 1));
if (index != -1) {
System.out.println("[" + (index + 1) + "]" + " " + memory.get(search - 1));
}
else {
System.out.println("Note number-" + search + " is not found in the collection!");
}
}
catch (IndexOutOfBoundsException e) {
System.out.println("The note number you have entered is invalid!");
}
}
public void updateNote() {
String dateTime = getTimestamp(); // ZonedDateTime.now(ZoneId.systemDefault()).format(dateTimeObj);
System.out.print("\nEnter note number to change: ");
try {
int search = reader.nextInt();
int index = memory.indexOf(memory.get(search - 1));
String updateLine;
if (index != -1) {
System.out.println("\nCurrent note: ");
System.out.println("[" + (index + 1) + "]" + " " + memory.get(search - 1));
System.out.println("\nThe updated note will be: ");
System.out.print("> ");
reader.nextLine();
updateLine = reader.nextLine();
memory.set(index, updateLine + " /" + dateTime);
System.out.print("Note has been updated successfully!\n");
}
else {
System.out.println(search + " is not found in the collection!");
}
}
catch (IndexOutOfBoundsException e) {
System.out.println("The note number you have entered is invalid!");
}
fileHandling();
}
public void deleteNote() {
System.out.print("\nEnter note number to delete: ");
try {
int search = reader.nextInt();
reader.nextLine();
int index = memory.indexOf(memory.get(search - 1));
System.out.println();
if (index != -1) {
System.out.println("[" + (index + 1) + "]" + " " + memory.get(search - 1));
System.out.print("\nDo you want to delete this note? \n[y] or [n]: ");
char delDecision = reader.nextLine().charAt(0);
if (delDecision == 'y' || delDecision == 'Y') {
memory.remove(index);
System.out.println("Note has been deleted successfully!");
System.out.println();
}
else if (delDecision == 'n' || delDecision == 'N') {
System.out.println("Note was not deleted!");
}
else {
System.out.println("Invalid input!");
}
}
else {
System.out.println(search + " is not found in the collection!");
}
}
catch (IndexOutOfBoundsException e) {
System.out.println("The note number you have entered is invalid!");
}
fileHandling();
}
public void displayNote() {
if (memory.size() > 0) {
int counter = 0;
for (String note : memory) {
System.out.printf("%d. %s%n", ++counter, note);
}
}
else {
System.out.println("There are no notes.");
}
}
private String getTimestamp() {
LocalDate todayDate = LocalDate.now();
LocalTime nowTime = LocalTime.now();
String timeFormat = nowTime.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM));
String dateTime = todayDate.toString() + " at " + timeFormat;// ZonedDateTime.now(ZoneId.systemDefault()).format(dateTimeObj);
return dateTime;
}
private void loadFile() throws IOException {
Path path = Paths.get(FILENAME);
if (Files.isRegularFile(path)) {
memory.addAll(Files.readAllLines(path, Charset.defaultCharset()));
}
}
private void showMenu() {
String choice = "";
while (!QUIT.equalsIgnoreCase(choice)) {
System.out.println(CREATE + " - Create note");
System.out.println(DELETE + " - Delete note");
System.out.println(FIND + " - Search notes");
System.out.println(SHOW + " - Show notes");
System.out.println(UPDATE + " - Update note");
System.out.println(QUIT + " - Quit");
System.out.println();
System.out.print("Your choice: ");
choice = reader.nextLine();
if (!choice.isEmpty()) {
choice = choice.substring(0, 1);
choice = choice.toUpperCase();
switch (choice) {
case CREATE -> createNote();
case DELETE -> deleteNote();
case FIND -> searchNote();
case SHOW -> displayNote();
case UPDATE -> updateNote();
case QUIT -> System.out.println("Good bye.");
default -> System.out.println("Invalid: " + choice);
}
}
else {
System.out.println("No selection entered. Retry.");
}
}
}
public static void main(String[] args) {
try {
FileSys fs = new FileSys();
fs.showMenu();
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
Your code does not initially load memory with contents of file notes.txt so I added that in the constructor. Consequently you don't need to append to the file since you simply overwrite it with contents of memory.
The file handling is done using NIO.2 including try-with-resources – which was added in Java 7. There are more NIO.2 examples in the JDK documentation.
Whenever the code throws an unexpected exception, it is nearly always a good idea to print the stack trace.
I dont want it to say attempts remaining -1, i want it saying the 2 attempts after the 1st attempt is done, and it repeats the prompt of the user input.
I already tried looking on how to correctly do the 3 attempt thing, but for some reason, my program is not successfully doing it.
import java.util.*;
import java.util.Collections;
public class Anagrams extends ShuffleWord{
static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
int score1 = 0;
int score2 = 0;
int score3 = 0;
int attempts = 3;
Random r = new Random();
System.out.println("Your face looks familiar, what is your name?");
String name = input.nextLine();
System.out.println("Welcome " + name + " to Anagrams, a game where the word is shuffled and you have to unscramble the word correctly!");
System.out.println(" Please select a difficulty " + name + ", 1 being easy, 2 being normal, and 3 being hard.");
int difficulty = input.nextInt();
switch (difficulty) {
case 1:
// 6 letter words
final String[] wordlist1 = {"string", "switch", "system" , "static" , "public" , "python" , "method" };
String word1 = wordlist1[r.nextInt(wordlist1.length)];
System.out.println("Your scrambled word is:" + shuffle(word1));
System.out.println("Please type the word");
String thisisjustsoitworks1 = input.nextLine();
String userword1 = "";
final List<String> wordy1 = Arrays.asList(wordlist1);
while (attempts -- > 0 && !wordy1.contains(userword1));
{
userword1 = input.nextLine();
if (wordy1.contains(userword1))
{
score1 += 50;
System.out.println(name + ", Your current score is:" + score1);
}
else
{
System.out.println("Incorrect. Number of attempts remaining:" + attempts);
}
}
break;
case 2:
// 15-16 letterwords
final String[] wordlist2 = {"computerscience" , "primitivedatatype" , "booleandatatype" ,};
String word2 = wordlist2[r.nextInt(wordlist2.length)];
System.out.println("Your scrambled word is:" + shuffle(word2));
System.out.println("Please type the word");
String thisisjustsoitworks2= input.nextLine();
String userword2 = input.nextLine();
List<String> wordy2 = Arrays.asList(wordlist2);
if (wordy2.contains(userword2))
{
score2 += 150;
System.out.println(name +", Your current score is:" + score2);
}
else
{
System.out.println("game over");
}
break;
case 3:
final String[] wordlist3 = {"objectorientatedprogramming" , "primitivedatatype" , "booleandatatype" ,};
String word3 = wordlist3[r.nextInt(wordlist3.length)];
System.out.println("Your scrambled word is:" + shuffle(word3));
System.out.println("Please type the word");
String thisisjustsoitworks3 = input.nextLine();
String userword3 = input.nextLine();
List<String> wordy3 = Arrays.asList(wordlist3);
if (wordy3.contains(userword3))
{
score3 += 300;
System.out.println (name + ", you gained" + score3 + "points, your total score is;" + score3);
}
else
{
System.out.println("game over");
}
break;
default:
System.out.println("Invalid Difficulty");
}
}
}
Suffle method code
import java.util.concurrent.ThreadLocalRandom;
/* Java program to shuffle a word randomly5
*/
public class ShuffleWord {
//public static void main(String[] args) {
// ShuffleWord sw = new ShuffleWord();
//
// String word = "Hello";
//
// String shuffled = sw.shuffle(word);
//
// System.out.println("Original word:"+word);
//
// System.out.println("Shuffled word:"+shuffled);
/*
* Shuffles a given word. Randomly swaps characters 10 times.
* #param word
* #return
*/
public static String shuffle(String word) {
String shuffledWord = word; // start with original
int wordSize = word.length();
int shuffleCount = 10; // let us randomly shuffle letters 10 times
for(int i=0;i<shuffleCount;i++) {
//swap letters in two indexes
int position1 = ThreadLocalRandom.current().nextInt(0, wordSize);
int position2 = ThreadLocalRandom.current().nextInt(0, wordSize);
shuffledWord = swapCharacters(shuffledWord,position1,position2);
}
return shuffledWord;
}
/**
* Swaps characters in a string using the given character positions
* #param shuffledWord
* #param position1
* #param position2
* #return
*/
private static String swapCharacters(String shuffledWord, int position1, int position2) {
char[] charArray = shuffledWord.toCharArray();
// Replace with a "swap" function, if desired:
char temp = charArray[position1];
charArray[position1] = charArray[position2];
charArray[position2] = temp;
return new String(charArray);
}
}
Output
Your face looks familiar, what is your name?
thomas
Welcome thomas to Anagrams, a game where the word is shuffled and you have to unscramble the word correctly!
Please select a difficulty thomas, 1 being easy, 2 being normal, and 3 being hard.
1
Your scrambled word is:static
Please type the word
a
Incorrect. Number of attempts remaining:-1
attempts remaining -1 is getting printed because of ; at the end of while loop(case 1:) in your code.
while (attempts -- > 0 && !wordy1.contains(userword1));
Due to this, attempts is getting decremented to -1, and after that program is taking user input.
I have a simple code that asks a user to input items and stores them into an array. I would like to make it so the program stops running when the last entry is the same as the first.
so for example this would stop the program because Cookie it both the first item in the array and the last. But it's also ok to have duplicates with in the array like "Sugar" in this example:
Enter the item: Cookie
Enter the item: Sugar
Enter the item: Milk
Enter the item: Sugar
Enter the item: Salt
Enter the item: Cookie
Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
//Decide the number of items
int numOfItems = 20;
//Create a string array to store the names of your items
String arrayOfNames[] = new String[numOfItems];
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("Enter Item " + (i+1) + " : ");
arrayOfNames[i] = scan.nextLine();
}
//Now show your items's name one by one
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("Item # " + (i+1) + " : ");
System.out.print(arrayOfNames[i] + "\n");
}
}
}
Thanks for your help
You can do this by adding a simple if-condition with equals() method. you need do add following if-condition.
if(Temp.equals(arrayOfNames[0])) // readed Temp equals to first element.
Try this code:-
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
//Decide the number of items
int numOfItems = 20,maxItems=0; // total items may vary
//Create a string array to store the names of your items
String arrayOfNames[] = new String[numOfItems];
String Temp=""; // for temporary storage
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("Enter Item " + (i+1) + " : ");
Temp= scan.nextLine();
if(Temp.equals(arrayOfNames[0])){
maxItems=i;
break;
}
else{
arrayOfNames[i]=Temp;
}
}
//Now show your items's name one by one
for (int i = 0; i < maxItems; i++) {
System.out.print("Item # " + (i+1) + " : ");
System.out.print(arrayOfNames[i] + "\n");
}
}
}
Output :-
Enter Item 1 : Cookie
Enter Item 2 : Sugar
Enter Item 3 : milk
Enter Item 4 : Sugar
Enter Item 5 : Salt
Enter Item 6 : Cookie
Item # 1 : Cookie
Item # 2 : Sugar
Item # 3 : milk
Item # 4 : Sugar
Item # 5 : Salt
If you don't know the number of items will be entered by the user then this code will be helpful,
import java.util.*;
public class MyClass {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
Scanner sc = new Scanner(System.in);
while(true)
{
System.out.print("Enter name:");
String temp = sc.next();
if(al.isEmpty() != true)
{
if(temp.equals(al.get(0)))
break;
}
al.add(temp);
}
for(int i = 0;i<al.size();i++)
{
System.out.println(al.get(i));
}
}
}
More sophisticated OO Program Example:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Grocery {
List<String> basket; // list of items in the basket
//constructor of Grocery with number of items provided
public Grocery(int numberOfItems) {
basket = new ArrayList<>(numberOfItems); // initialize basket
}
/**
* Add item to basket only if it is not similar to the first item
* return true if succeeded otherwise return false if it's duplicate
* #param item
* #return
*/
public boolean addItem(String item) {
if(basket.size()==0) return basket.add(item);
if(!basket.get(0).equals(item)) {
return basket.add(item);
}
return false;
}
/**
* Remove specific item in the basket
* or all items by name if "all" is true
* #param item
*/
public void removeItem(String item, boolean all) {
if(all) {
for(String i : basket) {
if(i.equals(item)) {
basket.remove(i);
}
}
}else {
basket.remove(item);
}
}
// method to empty the basket
public void emptyBasket() {
basket.clear();
}
/**
* Override toString() to provide your own
* textual representation of the basket
*/
#Override
public String toString() {
String s = "";
for(int i=0; i<basket.size(); i++) {
s += "Item #" + (i+1) + " : " + basket.get(i) + "\n";
}
return s;
}
// TEST
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//Decide the number of items
int numOfItems=0;
System.out.print("Enter How Many Items: ");
try {
numOfItems = Integer.parseInt(scan.nextLine().trim());
}catch(NumberFormatException e) {
System.out.print("Number of items you entered is invalid!");
System.exit(0);
}
Grocery grocery = new Grocery(numOfItems);
for (int i = 0; i < numOfItems; i++) {
System.out.print("Enter Item " + (i+1) + " : ");
if(!grocery.addItem(scan.nextLine())) {
System.out.println("First Item Duplicate Detected!");
//break;
System.exit(0);
};
}
scan.close();
System.out.println(grocery.toString());
}
}
Test
Sounds to me like you should be able to do a if statement in here to find out if array[0] = array[i]
if (i > 0 && (arrayOfNames[0] == arrayOfNames[i])) {
// do something
}
Simply add a condition that if the current element matches first element, then break out of the for loop.
String first=null;
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("Enter Item " + (i+1) + " : ");
arrayOfNames[i] = scan.nextLine();
if (i==0){
first=arrayOfNames[i];
}else{
if(first==arrayOfNames[i]){break;}
}
}
Just change your for loop condition to:
for (int i = 0; i == 0 || arrayOfNames[i] != arrayOfNames[0]; i++)
I am getting this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at JavaProject.main(JavaProject.java:70)
Here is the code:
try
{
PrintWriter writer = new PrintWriter("Gamer Report Data.txt");
writer.println("Player: " + gamerName);
writer.println();
writer.println("-------------------------------");
String[] report = gamerReport.split(gamerReport, ':');
writer.println("Game:" + ", score=" + report[1] + ", minutes played=" + report[2] + report[3]);
writer.close();
} catch (IOException e)
{
System.err.println("File does not exist!");
}
I believed it to be something related to my for loop, but I have had no luck changing it around.
import java.util.Scanner;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.io.PrintWriter;
public class JavaProject {
private static char[] input;
#SuppressWarnings("null")
public static void main(String[] args) {
for (int b = 1; b < 100; b++) {
// this is making the code loop 100 times
int hrs, mins;
int[] gameCount;
int[] minutesPlayed = new int[100];
String gamerName, gamerReport;
// Main data storage arrays
String[] gameNames = new String[100];
int[] highScores = new int[100];
Scanner Scan = new Scanner(System.in);
// formatting for output and input
System.out.println("////// Game Score Report Generator \\\\\\\\\\\\");
System.out.println(" ");
// user enters name and then moves to next line
System.out.println("Enter Your Name");
gamerName = Scan.nextLine();
// user is given an example of input format
System.out.println("Input Gamer Information " + "Using Format --> Game : Achievement Score : Minutes Played");
System.out.println(" ");
System.out.println("Game : Achievement Score : Minutes Played");
gamerReport = Scan.nextLine();
String[] splitUpReport; // an array of string
splitUpReport = gamerReport.split(":"); // split the text up on the colon
int i = 0;
// copy data from split text into main data storage arrays
gameNames[i] = splitUpReport[0];
highScores[i] = Integer.parseInt(splitUpReport[1].trim());
minutesPlayed[i] = Integer.parseInt(splitUpReport[2].trim());
// output to file
try
{
PrintWriter writer = new PrintWriter("Gamer Report Data.txt");
writer.println("Player: " + gamerName);
writer.println();
writer.println("-------------------------------");
String[] report = gamerReport.split(gamerReport, ':');
writer.println("Game:" + ", score=" + report[1] + ", minutes played=" + report[2] + report[3]);
writer.close();
} catch (IOException e)
{
System.err.println("File does not exist!");
}
}
}
public static char[] getInput() {
return input;
}
public static void setInput(char[] input) {
JavaProject.input = input;
}
}
There are two problems with your code:
1)
String[] report = gamerReport.split(gamerReport, ':');
should be
String[] report = gamerReport.split(":");
as you did with splitUpReport (not sure why you're splitting again actually).
2) Arrays are zero-indexed, so the print statement should look like this:
writer.println("Game:" + ", score=" +report[0] +", minutes played="+ report[1] + report[2]);
The error in your code is being caused by this code in the try block:
String[] report = gamerReport.split(gamerReport, ':');
You are actually trying to split the gamerReport string using itself as a regex, with a limit of 58, which is the numerical value of the colon.
The result of this split is 2 empty String elements, which correspond to the match happening before and after the regex, which is the string itself.
The ArrayIndexOutOfBounds exception is happening when you try to access the third element from this array:
To fix your problem, just define the report array as follows:
String[] report = gamerReport.split(':');
As #shmosel pointed out, you might also want to change your array indices here as well:
writer.println("Game:" + ", score=" + report[0] +", minutes played="+ report[1] + report[2]);
i'll get straight to the chase. If a user wants to read another file they must type r in the menu, then they are thrown with a return readFile(); method which takes them to the top of the program and asks them the same question it did at the beggining when they first ran this program. Only issue is when you type R or Default it throws an OutOFBoundsException. BTW It is Reading a CSV file
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1000
at studentrecs.StudentRecs.in(StudentRecs.java:71)
at studentrecs.StudentRecs.readFile(StudentRecs.java:55)
at studentrecs.StudentRecs.menu(StudentRecs.java:97)
at studentrecs.StudentRecs.main(StudentRecs.java:33)
Java Result: 1
/
public static Boolean readFile(String filename) throws IOException { //Constructor for filename
try {
Scanner userInput = new Scanner(System.in);
System.out.println("Type R To Read a File or Type Default for the default file");
user = userInput.nextLine();
if (user.equalsIgnoreCase("r")) {
user = userInput.nextLine();
}
filename = user;
if (user.equalsIgnoreCase("default")) {
filename = "newreg2.csv";
}
Scanner input = new Scanner(new FileReader(filename));
while (input.hasNext()) {
in(input.nextLine());
numstu++;
}
input.close();
return true;
} catch (IOException e) {
System.err.println(e.getMessage());
}
return false;
}
public static void in(String reader) {
String splitter[];
splitter = reader.split(",");
stu[numstu] = new StuRec();
stu[numstu].studentID = splitter[0];
stu[numstu].lastName = splitter[1];
stu[numstu].firstName = splitter[2];
stu[numstu].phoneNumber = splitter[3];
stu[numstu].courseCode = splitter[4];
stu[numstu].periodNumber = Integer.parseInt(splitter[5]); // parseInt turns a string of digits into an integer
stu[numstu].mark = Integer.parseInt(splitter[6]);
}
public static boolean menu() throws IOException {
String choice;
Scanner userInput = new Scanner(System.in);
System.out.println("=============================================");
System.out.println("Type R To Read Another File");
System.out.println("Type L To Print all File Records");
System.out.println("Type AA To Print The Average Of All The Marks");
System.out.println("Type X To Exit The Program");
choice = userInput.nextLine();
double average = 0.0; // declare average
if (choice.equalsIgnoreCase("L")) {
for (int i = 0; i < numstu; i++) {
System.out.println(stu[i].lastName + ", " + stu[i].firstName + ", " + stu[i].studentID + ", " + stu[i].phoneNumber + ", " + stu[i].courseCode + ", " + stu[i].periodNumber + ", " + stu[i].mark);
}
}else if (choice.equalsIgnoreCase("R")){
return readFile(filename);
} else if (choice.equalsIgnoreCase("AA")) {
for (int i = 0; i < numstu; i++) {
average += stu[i].mark; // keep adding to average
}
}else if (choice.equalsIgnoreCase("X")) {
for (int i = 0; i < numstu; i++) {
System.exit(i);
}
}else if (choice.equalsIgnoreCase("AC")) {
} else {System.err.println("Unknown Key Try Again...");
}
// divide by zero protection
if ( choice.equalsIgnoreCase("AA") && numstu > 0 ) {
average = average/numstu; // compute the average. Always use the size in terms of a variable whenever possible.
System.out.println(average); // as noted below, if this is an integer value, < #of students computations will eval to 0.
}
else if (!choice.equalsIgnoreCase("AA") && numstu < 0) {
System.out.println("Oops! No Marks To Calculate! :(");
}
return menu();
}
}
It looks like EITHER you have initialised numstu to start at 1, OR you have more than 1000 lines in your file.
The effect of either of these errors would be that you eventually attempt to write data to entry 1000 of stu. But since you've initialised stu with 1000 entries, numbered from 0 to 999, this gives your error.
You should make sure that numstu is initially 0, not 1.
And next time you post a question, post ALL of your code, not just the parts where you think the error might be. It's very difficult for most people to find bugs in code that they can't see.