I'm trying to use i++ to store certain parts of an array in a loop. But instead of incrementing by 1, I really need it to increment by 2.
For example:
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.JOptionPane;
public class PeerTutoring
{
public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<String>();
int a = 0;
int b = 1;
String name, degree;
String line;
line = JOptionPane.showInputDialog("Inputs");
String[] userinput = line.split("\\s+");
for(int i = 0; i < userinput.length; i++)
{
name = userinput[a];
degree = userinput[b];
a+=2;
b+=2;
}
}
public static String sort(String name)
{
String tutors = "Tutor List";
ArrayList<String> names = new ArrayList<String> ();
names.add(userinput[0]);
names.add(userinput[2]);
names.add(userinput[4]);
names.add(userinput[6]);
names.add(userinput[8]);
names.add(userinput[10]);
names.add(userinput[12]);
names.add(userinput[14]);
names.add(userinput[16]);
names.add(userinput[18]);
}
}
I want a to start as 0 and b as 1, and then each time I would like it to increase by two. (Since the names are each one is seperated by a space) I think I'm going to have to incorporate something along the lines of userinput[a + 1]. But I just wanted to know if there was a simpler way.
for(i=0, i < linesize; i += 2)
As a side note, make sure to initialize your variables outside the loop if you are planning to use them after, or they will be lost.
int a = 0;
int b = 1;
String name, degree;
for(i=0, i < linesize; i += 2)
{
int linesize = line.size();
String line;
line = JOptionPane.showInputDialog("Please enter tutor name and
their highest earned degree.");
String[] userinput = line.split("\\s+");
name = userinput[a];
degree = userinput[b];
a++;
b++;
}
Your options are:
i++; i++; (Which you can't use in the for loop construct since you need a single statement.)
i += 2;
i = i + 2;
String line;
line = JOptionPane.showInputDialog("Please enter tutor name and
their highest earned degree.");
String[] userinput = line.split("\\s+");
for(int i=0, i < userinput.length; ){
String name = userinput[i++];
String degree = userinput[i++];
...
}
Related
I have a problem at the moment I have a college assignment and we need to list a file that contain books and should be sorted A to Z,
My sort algorithm is a bubble sort and at the moment is not sorting alphabetically but don't give errors, I cant see where I should change to make it work as the coding seems correct to me.
We are not allowed to use collections so that is the reason I am not using sort().
package Book;
public class AlphabeticalOrderTitle{
//Global variables
public static String input;
public static int bookId;
public static String bookTitle;
public static String authorName;
public static boolean isAvailable;
public static void main(String[] args)
{
ArrayList<Book> books = BubbleSort();
System.out.println(linearSearch(books));
}
public static ArrayList<Book> loadData() {
//Creating an array list;
ArrayList<Book> books = new ArrayList<>();
try {
//Here we start reading our file
BufferedReader br = new BufferedReader(new FileReader("Book.txt"));
//This header string will allow to skip the header so does not mismatch with getter and setters.
String header = br.readLine();
//This string will read the lines.
String contentLine = br.readLine();
//Giving our array name data;
String [] data;
//Here we loop to continue the reading of data for each array box.
while (contentLine != null) {
data = contentLine.split(",");
bookId = Integer.parseInt(data[0]);
bookTitle = data[1];
authorName = data[2];
isAvailable = Boolean.parseBoolean(data[3]);
books.add(new Book(bookId, bookTitle, authorName, isAvailable));
contentLine = br.readLine();
}
}catch (IOException ex) {
Logger.getLogger(SearchBookAuthor.class.getName()).log(Level.SEVERE, null,ex);
}
return books;
}
public static int linearSearch(ArrayList<Book> array){
//Variables for holding values
int n;
String temp;
// Going one by one the elements in the array
for(int g = 0; g < array.size(); g++){
//Getting the array size from the file and giving the array name a size
n = array.size();
String names[] = new String[n];
//Load all the names
for(int i = 0; i < n; i++) {
names[i] = array.get(g).getBookTitle();
}
//Bubble sort starts
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (names[i].compareTo(names[j]) > 0)
{
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
//Print sorted
System.out.println(names[n-1]);
}
return -1;
}
}
Outpout:
Captains
Romeo
Don
-1
and what I am aiming is Captains, Don, Romeo.
My book.txt contains is like this:
book
Any suggestion for me to fix it ? Thank you very much.
Bubble Sort Example
I linked a bubble sort example. You can click on Java to see a version in Java. And you can see there are differences between yours and theirs, even though they are very similar.
What I would do is do it manually. That is, grab some paper, write down what your array looks like then actually pretend you're the computer and see what you end up with. It will be a good exercise for you, and you'll probably figure out what you're doing wrong.
First of all, BubbleSort() is not an appropriate name for this method as all it does is reading the file and storing the content inside the list.
If this course is not an upper-level algorithms class, you could probably use java libraries to sort your list instead.
Something like this should work and produce the needed result:
Collections.sort(books);
Also, I usually just do the following:
List books = new ArrayList<>();
In case you have to implement bubble sort, please use the following link which shows how to use bubble sort to sort string arrays: https://www.geeksforgeeks.org/sorting-strings-using-bubble-sort-2/
For array A of 'n' elements A[n], then the first loop in bubble sort always ends with n-1.
The idea of bubble sort is to compare the adjacent elements and then swap if the are not in order (increasing / decreasing depending on the use case).
So, when i=n-1, as you mentioned in your first for loop=>j=n-1. We are basically comparing A[i=n-1] to A[j=n-1].
//Bubble sort starts
for (int i = 0; i < n-1; i++)
{
for (int j = i + 1; j < n; j++)
{
if (names[i].compareTo(names[j]) > 0)
{
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
you can try a quick dry-run whenever you are stuck in such problems by substituting with small numbers and writing the loop content on paper. Helps a lot to learn and to build logic. :)
So after a couple days working on it I have come with a working solution thanks to everyone.
public class Alphabetical_Order {
//Global variables
public static String input;
public static int bookId;
public static String bookTitle;
public static String authorName;
public static boolean isAvailable;
//Creating an array list;
public static ArrayList<Book> books = new ArrayList<>();
public static void main(String[] args)
{
loadData();
int n = 0;
String temp;
//Scanner s = new Scanner(System.in);
System.out.print("Enter number of names you want to enter:");
//get size of arraylist
for (int g = 0; g < books.size(); g ++) {
n = books.size();
}
String names[] = new String[n];
//Names to be get from user
Scanner s1 = new Scanner(System.in);
System.out.println("Enter all the names:");
for(int i = 0; i < n; i++)
{
names[i] = books.get(i).getAuthorName();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (names[i].compareTo(names[j])>0)
{
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
System.out.print("Names in Sorted Order:");
for (int i = 0; i < n - 1; i++)
{
System.out.print(names[i] + ",");
}
System.out.print(names[n - 1]);
}
public static void loadData() {
try {
//Here we start reading our file
BufferedReader br = new BufferedReader(new FileReader("Book.csv"));
//This header string will allow to store the header so does not mistach with getter and setters.
String header = br.readLine();
//This string will read the lines.
String contentLine = br.readLine();
//Giving our array name data;
String [] data;
//Here we loop to continue the reading of data for each array box.
while (contentLine != null) {
data = contentLine.split(",");
bookId = Integer.parseInt(data[0]);
bookTitle = data[1];
authorName = data[2];
isAvailable = Boolean.parseBoolean(data[3]);
books.add(new Book(bookId, bookTitle, authorName, isAvailable));
contentLine = br.readLine();
}
}catch (IOException ex) {
Logger.getLogger(SearchBookAuthor.class.getName()).log(Level.SEVERE, null,ex);
}
}}
I am creating a program in which a user enters a string of words (Ex: I love you), and the program returns an array of the words in the string spelled backwards (Ex: I evol ouy). However, I cannot get my code to properly compile, and tried debugging, but cannot see where the problem is.
I tried to look for similar problems here on Slack, but the problems are found were concerned with rearranging words from a string, (ex: you I love), and I cannot find a problem similar to mine, involving turning string into an Array and then manipulating the array.
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string to see it in reverse: ");
String userEntry = sc.nextLine();
char[] entryToChar = userEntry.toCharArray();
System.out.println(Arrays.toString(entryToChar));
String[] splitInput = userEntry.split(" ");
String reverseWord = "";
int temp;
String[] reverseString = new String[splitInput.length];
for (int i = 0; i < splitInput.length; i++)
{
String word = splitInput[i];
for (int j = word.length()-1; j >= 0; j--)
{
reverseWord = reverseWord + word.charAt(j);
}
for (int k = 0; k < splitInput.length; k++) {
temp = splitInput[i];
splitInput[i] = reverseWord[j];
reverseWord[j] = temp;
}
} System.out.println("Your sttring with words spelled backwards is " + reverseWord[j]);
I am avoiding using the 'StringBuilder' method as I have not yet studied it, and trying to see if I can get the new string using swapping, as in the code below:
temp = splitInput[i];
splitInput[i] = reverseWord[j];
reverseWord[j] = temp;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String word, reverseWord;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string to see it in reverse: ");
String userEntry = sc.nextLine();
userEntry: I love you
String[] splitInput = userEntry.split(" ");
splitInput: [I, love, you]
for (int i = 0; i < splitInput.length; i++)
{
word = splitInput[i];
reverseWord = "";
for (int j = word.length()-1; j >= 0; j--)
{
reverseWord = reverseWord + word.charAt(j);
}
splitInput[i] = reverseWord;
}
splitInput: [I, evol, uoy]
System.out.println("Your string with words spelled backwards is: " + String.join(" ", splitInput));
}
}
Your string with words spelled backwards is: I evol uoy
Your code is not getting compiled because tmp variable is declared as int while splitInput[i] is String.
The other problem is variable j is outside its block scope from where you are trying to access.
Make your logic clear before writing code to achieve correct result.
A good Java programmer should know which tools exist in the language and make use of them in her/his design appropriately. I would suggest to use the class StringBuilder, which has a method for reversing the string. Your program could look like this:
while in.hasNext() {
StringBuilder sb = in.next();
sb.reverse();
System.out.println(sb.toString());
}
If you want to write the reverse function yourself for practice then you can simply define a method that takes a string and returns a reversed string and call that method in place of sb.reverse().
Please know that String in Java is an immutable object. You cannot modify it directly. You can have modified copies returned.
StringBuilder on the other hand allows the programmer to modify the object directly as you can see in the code above.
You need to split original string into an array and then reverse each one and insert into the new array, here you can use StringBuilder as good practice.
class Testarray{
public static void main(String args[]){
String str = "I am Engineer";
String[] spArray = str.split(" ");
String farr[] = new String[spArray.length];
for(int i=0;i<spArray.length;i++){
String split = spArray[i];
farr[i]=reverseString(split);
}
for(int i=0;i<farr.length;i++){
System.out.println(farr[i]);
}
}
public static String reverseString(String str){
char ch[]=str.toCharArray();
String rev="";
for(int i=ch.length-1;i>=0;i--){
rev+=ch[i];
}
return rev;
}
}
There are a few things going on here, and I think in some places you're mixing up between strings and arrays.
Let's try to break this problem down into smaller problems.
First, we need to reverse a single word. Your first inner loop (the one that uses j) does that, so let's extract it into its own method:
public static String reverseWord(String word) {
String reverseWord = "";
for (int j = word.length()-1; j >= 0; j--) {
reverseWord = reverseWord + word.charAt(j);
}
return reverseWord;
}
Although, you should note that concatenating strings like that in a loop isn't great for performance, and using a StringBuilder would probably be faster (although with such a small application, it probably won't be noticeable):
public static String reverseWord(String word) {
StringBuilder reverseWord = new StringBuilder(word.length());
for (int j = word.length()-1; j >= 0; j--) {
reverseWord = reverseWord.append(word.charAt(j));
}
return reverseWord.toString();
}
Once you have that, you can split the input string (like you did), revere each word, and join them back together:
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string to see it in reverse: ");
String userEntry = sc.nextLine();
String[] splitInput = userEntry.split(" ");
for (int i = 0; i < splitInput.length; i++) {
splitInput[i] = reverseWord(splitInput[i]);
}
System.out.println("Your sttring with words spelled backwards is " +
String.join(" ", splitInput));
All you need is to split your original sentence into separate words and use StringBuilder.reverse() to get words in reverse:
public static void main(String... args) {
String str = getSentenceFromConsole();
System.out.println("Your string with words spelled backwards is '" + reversLettersInWords(str) + '\'');
}
private static String getSentenceFromConsole() {
try (Scanner scan = new Scanner(System.in)) {
System.out.print("Enter a string to see it in reverse: ");
return scan.nextLine();
}
}
private static String reversLettersInWords(String str) {
return Arrays.stream(str.split("\\s+"))
.map(word -> new StringBuilder(word).reverse().toString())
.collect(Collectors.joining(" "));
}
i try with your code
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string to see it in reverse: ");
String userEntry = sc.nextLine();
String[] splitInput = userEntry.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < splitInput.length; i++) {
String word = splitInput[i];
for (int j = word.length() - 1; j >= 0; j--) {
sb.append(word.charAt(j));
}
sb.append(" ");
}
System.out.println("Your sttring with words spelled backwards is " + sb.toString());
here i remove all access line of code....
String input = "i love you";
StringBuilder input1 = new StringBuilder();
input1.append(input);
input1 = input1.reverse();
System.out.println(input1);
You can use this implementation to try to reverse the string elements in the array.
For the code, it wakes a user input and splits it by witespaces then takes the individual words from the user input and checks to see if the singular word is in the text file( containing parallel arrays with one being a string array and the other an int array). For every time it finds the user inputted word it needs to add one but the problem is that I don't know how to implement either match, or compare or equalsTo to check to see if the word is in the String array.
public class MovieReviewSentimentAnalysis {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
// TODO: complete me
//make own arrays to pass by value
//movieReviewComments = the text
String[] movieReviewComments = new String[10000];
//movieReviewScores = numeric values, avoid lit. values
int[] movieReviewScores = new int[10000];
String userComment = "";
// String reviewFile = "";
// reviewFile = args[0];
String whiteComment = "";
MovieReviewReader.readMovieReviews("movie_reviews.txt", movieReviewComments, movieReviewScores); //string, string array, and int array
System.out.println("Please type one line of review and when you are done press either Ctr D or Ctr Z");
userComment = userInput.nextLine();
System.out.println(userComment);
String[] words2 = userComment.split("[\\W]");
double itemCount = 0;
double wordTotal = 0;
double totalSumOfUserCommentWords = 0;
String test = "";
// int itemCount = words.length;
for (int i = 0; i < words2.length; i++)
{
test = words2[i];
itemCount = wordCount(test, movieReviewComments, movieReviewScores);
wordTotal += itemCount;
totalSumOfUserCommentWords = wordTotal / userComment.length();
// System.out.println(totalSumOfUserCommentWords);
}
// System.out.println(reviewFile);
System.out.println("Incomplete assignment");
userInput.close();
}
public static double wordCount(String test, String[] movieReviewComments, int[] movieReviewScores)
{
double storeScore = 0;
double totalSumofReviewScores = 0;
double numOfTimesWordAppears = 0;
for (int i=0; i < (movieReviewComments.length); i++)
{
if (test.equals(movieReviewComments[i])) //////////////////////////////////////////////////////////SOMETHING'S OFF
{
storeScore = movieReviewScores[i];
totalSumofReviewScores += storeScore;
numOfTimesWordAppears++;
System.out.println("Found"); //QUQ when will you appear!?!?
}
else
System.out.println("You dun goofed"); //delete after fixing problem
}
double wordScoreAverage = totalSumofReviewScores / numOfTimesWordAppears;
return wordScoreAverage;
}
It is very simple. You can do it the following way:
if (movieReviewComments[i].toLowerCase().contains(test.toLowerCase())
And if you want to test an equal comparison and not containment, use following instead:
if (test.equalsIgnoreCase(movieReviewComments[i])
EDIT: right, I forgot to state the problem -- which is the fact that I get 0 as an output.
CONTEXT
My program aims to take a user-inputted number-word (1- 99) and output it as an integer (i.e. thirty-four = 34). I can't figure out where the error in my code is and need help:
Scanner scInput = new Scanner(System.in);
String word = scInput.nextLine(); //number in word-form (i.e. twenty six)
char[] charArray = word.toCharArray();//string to char array for word^
int divider = 0; //position of hyphen/space in charArray
All 2-word numbers are comprised of a tens value & a ones value. Assuming proper syntax [english], the word before the hyphen/space divider is the tens and the word following divider is the ones.
ARRAYS
//word values - components & syntax (1-99)
//ONES
public static final String[] wONES = {"one","two","three","four","five","six","seven","eight","nine"};
//TENS
public static final String[] wTENS = {null,"twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"};
//TEENS
public static final String[] wTEENS = {"ten", "eleven", "twelve", "thirteen","fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
I've organized all the word-components into 3 different arrays: ones, tens, and teens.
//equivalent integer-array of above String arrays
//ONES
public static final int[] nONES = {1,2,3,4,5,6,7,8,9};
//TENS
public static final int[] nTENS = {0,20,30,40,50,60,70,80,90};
//TEENS
public static final int[] nTEENS = {10,11,12,13,14,15,16,17,18,19};
I created 3 other arrays that are the same as the above three arrays, except they store the integer values.
CODE
Here I separate the user-inputted String into two sections: the tens and the ones. So if the number was 72: 70 = tens and 2 = ones.
int tensValue = 0; //number's tens value (i.e. 30)
int onesValue = 0; //ones value (i.e. 3)
char[] tensArray = null; //array storing tens section of word (before divider)
for (int u = 0; u < divider; u++){
tensArray[u] = charArray[u];
}
String tens = new String(tensArray); //convert char array to String
char[] onesArray = null; //array storing ones section of word (after divider)
for (int u = divider + 1; u > divider && u < charArray.length; u++){
onesArray[u] = charArray[u];
}
String ones = new String(onesArray);
//searches for matches in String array for tens
for(int u = 0; u < wTENS.length; u++){
if(tens.equals(wTENS[u])){
tensValue = nTENS[u];
total += tensValue;
}
}
//searches for matches in String array for ones
for(int u = 0; u < wONES.length; u++){
if(ones.equals(wONES[u])){
onesValue = nONES[u];
total += onesValue;
In your current code you are doing char[] tensArray = null; which should be something like char[] tensArray = new char[10]; or else you end up with NPE.
It might not be most efficient but here is a simple and better approach to your problem.
Read the line and split it on white space (assuming you are separating your words by a space).
Search each of the tokens you get after split in the above lists and add the corresponding number (same index) to your answer.
Print the answer.
Here is the code snippet:
class Main
{
public static final String[] wONES = {"one","two","three","four","five","six",
"seven","eight","nine"};
public static final String[] wTENS = {"ten","twenty","thirty","forty","fifty","sixty",
"seventy","eighty","ninety"};
public static final String[] wTEENS = {"eleven", "twelve", "thirteen","fourteen",
"fifteen", "sixteen", "seventeen", "eighteen",
"nineteen"};
public static final int[] nONES = {1,2,3,4,5,6,7,8,9};
public static final int[] nTENS = {10,20,30,40,50,60,70,80,90};
public static final int[] nTEENS = {11,12,13,14,15,16,17,18,19};
public static void main (String[] args) throws Exception
{
Scanner scInput = new Scanner(System.in);
String word = scInput.nextLine();
int answer = 0;
/* Assuming you are giving space between words */
for(String s : word.split(" ")) {
/* Scan wONES */
for(int i = 0; i < wONES.length; i++) {
if(wONES[i].equalsIgnoreCase(s)) {
answer += nONES[i];
continue;
}
}
/* Scan wTENS */
for(int i = 0; i < wTENS.length; i++) {
if(wTENS[i].equalsIgnoreCase(s)) {
answer += nTENS[i];
continue;
}
}
/* Scan wTEENS */
for(int i = 0; i < wTEENS.length; i++) {
if(wTEENS[i].equalsIgnoreCase(s)) {
answer += nTEENS[i];
continue;
}
}
}
System.out.println("Result: " + answer);
}
}
Input:
thirty four
Output:
34
You have an interesting approach to this problem. A couple of things to change:
I don't see where you set your divider index.
You seem to be doing a lot of work with character arrays, so I'm guessing you're coming from a different language. Sticking with Strings will work fine.
You don't address the "teens". This looks like a simple oversight.
I've added those fixes while attempting maintain the original approach:
public static void main(String [] args) {
Scanner scInput = new Scanner(System.in);
String word = scInput.nextLine();
int total = 0;
int tensValue = 0; //number's tens value (i.e. 30)
int onesValue = 0; //ones value (i.e. 3)
int divider = word.indexOf('-');
String tens = null;
String ones = null;
if (divider != -1) {
tens = word.substring(0, divider);
ones = word.substring(divider + 1);
} else {
ones = word;
}
//searches for matches in String array for tens
if (tens != null) {
for (int u = 0; u < wTENS.length; u++) {
if (tens.equals(wTENS[u])) {
tensValue = nTENS[u];
total += tensValue;
}
}
}
//searches for matches in String array for ones
for(int u = 0; u < wONES.length; u++) {
if (ones.equals(wONES[u])) {
onesValue = nONES[u];
total += onesValue;
}
}
// if a "teen" override what's in total
for(int u = 0; u < wTEENS.length; u++) {
if (ones.equals(wTEENS[u])) {
total = nTEENS[u];
}
}
System.out.println(total);
}
I am trying to use the setCharAt method in a StringBuilder but I am getting a null pointer exception. Is there a way I can add values to the StringBuilder array I have made so I wont get these error.
From research I have found the .append() method but I'm not even sure how it works.
import java.util.*; // Allows for the input of a scanner method.
import java.io.*; // Allows for the inputting and outputting of a data file.
import java.lang.*; // Allows for the use of String Methods.
//////////////////////////////////////////////////////////////////////////////////////
public class TESTY
{
static Scanner testanswers;
static PrintWriter testresults;
public static void main(String[] args) throws IOException
{
testanswers = new Scanner(new FileReader("TestInput.dat"));
testresults = new PrintWriter("TestOutput.dat");
String StudentID;
String answers;
// Reads first two lines first to know how many records there are.
String answerKey = testanswers.nextLine();
int count = Integer.parseInt(testanswers.nextLine());
// Allocate the array for the size needed.
String[][] answerArray = new String[count][];
for (int i = 0; i < count; i++)
{
String line = testanswers.nextLine();
answerArray[i] = line.split(" ", 2);
}
for(int row = 0; row < answerArray.length; row++)
{
for(int col = 0; col < answerArray[row].length; col++)
{
System.out.print(answerArray[row][col] + " ");
}
System.out.println();
}
gradeData(answerArray, answerKey);
testanswers.close();
testresults.close();
}
///////////////////////////////////////////////////////////
//Method: gradeData
//Description: This method will grade testanswers showing
//what was missed, skipped, letter grade, and percentage.
///////////////////////////////////////////////////////////
public static double gradeData(String[][] answerArray, String answerKey)
{
String key = answerKey;
double Points = 0;
StringBuilder[] wrongAnswers = new StringBuilder[5];
String studAnswers;
for(int rowIndex = 0; rowIndex < answerArray.length; rowIndex++) /// Counting rows
{
studAnswers = answerArray[rowIndex][1].replace(" ", "S"); ///Counts rows, Col stay static index 1
for(int charIndex = 0; charIndex < studAnswers.length(); charIndex++)
{
if(studAnswers.charAt(charIndex) == key.charAt(charIndex))
{
Points += 2;
}
else if(studAnswers.charAt(charIndex) == 'S')
{
Points --;
}
else if(studAnswers.charAt(charIndex) != key.charAt(charIndex))
{
for(int i = 0; i < wrongAnswers.length; i++)
{
wrongAnswers[i].setCharAt(charIndex, 'X');
}
Points -= 2;
}
}
System.out.println(Points);
}
return Points;
}
}
The error is occurring on line 91 :
wrongAnswers[i].setCharAt(charIndex, 'X');
You have declared an array of StringBuilders, but you haven't initialized any of the slots, so they're still null.
Initialize them:
StringBuilder[] wrongAnswers = new StringBuilder[5];
for (int i = 0; i < wrongAnswers.length; i++)
{
wrongAnswers[i] = new StringBuilder();
}
Additionally, using setCharAt won't work here, because initially, there is nothing in the StringBuilder. Depending on what you want here, you may need to just call append, or you may initially want a string full of spaces so that you can set a specific character to 'X'.
StringBuilder[] wrongAnswers = new StringBuilder[5];
does not create 5 empty StringBuilders but 5 null StringBuilders.
You need to call something like
wrongAnswers[i] = new StringBuilder()
in order to initialize your 5 array members.
Your problem is that
StringBuilder[] wrongAnswers = new StringBuilder[5];
does not create 5 StringBuilder objects. It only creates an array with 5 null StringBuilder references. You need to create each StringBuilder separately with a line such as
wrongAnswers[i] = new StringBuilder();
inside a loop over i.