Java FXML TextArea.setText() Stops Working - java

I am trying to update a TextArea in my Java FXML program and am encountering a weird problem. I am able to update the instructions 2 times but on the third instance of the same update call the text field will not update. I am using the same method call for all updates and have gotten what should be displayed to print in the console, so I know the problem is with the TextArea update. Here is the code causing the problem:
private void freedomCheck(){ // method for starting out a composition, choosing "mode"
decisionIndex = 0;
this.addChord("I"); //initialize first chord to "I"
prompt[0] = "Please enter your degree of freedom: 1, 2, 3, or 4."; //display prompt
prompt[1] = "1: Composes and plays for you";
prompt[2] = "2: Fill in just notes with chords given to you";
prompt[3] = "3: Fill in chords and notes, with software giving you options for both";
prompt[4] = "4: Fill in chords and notes with full independence";
prompt(); // get user input (can be changed to button press, etc.
}
private void prompt(){
String displayString = "";
for(int i=0;i<5;i++){
displayString += prompt[i] + "\n";
}
setInstructions(displayString);
System.out.println(displayString);
}
public void setInstructions(String newString){
instruction_text.setText(newString);
}
The prompt[] array is used to quickly separate lines of text. This section of the code works and prints correctly on the display, but later when I try to update it with the same prompt() call:
public void promptNotes(){
decisionIndex = 4;
int index;
if (composition.noteLength() == 0)
index = composition.getSize() - 1;
else index = composition.noteLength();
prompt[0] = "The current chord is " + composition.getChord(index).getName() + "; please pick a note:";//prompt
Chord temp = composition.getChord(composition.getSize()-1);
ArrayList<Note> candidates = temp.getOfferedNotes();
int notesLen = candidates.size(); //length of notes list for current chord
for(int i = 1; i < 5; i++){
tempNotes[i] = candidates.get(notesLen - i);
prompt[i] = (i+1) + ": " + tempNotes[i].getName();
}
prompt();
}
The correct output is printed to the console, but the textArea does not update.

Related

How do I stop this array from only printing/remembering the latest thing put into the array?

I don't know if the array itself is broken or if the code to print the array is broken
/*This is the main class that prints out everything */.
//Start the problems loop
for (int i = 0; i < session.getNumProb(); i++) {
//Set random values for factors
cards.setFactors();
//Create problems
cards.setProb(session);
//Determine correct/incorrect answer, update running score
cards.setResponse(session);
//Add the problem to the history array
session.setHistory(cards);
}
//Set score percentage
session.setScorePct();
//Print out summary
session.prtSummary();
//Print out history array and outro
session.prtHistoryAndOutro();
______________________________________________________________________________
/* This sets the history based on questions asked */
//setHistory
public void setHistory(Cards c) {
for (int i = 0; i < numProb; i++) {
history[i] = c.getA() + oper + c.getB() + " = " + c.getResponse() + ", " + c.getCorInc() + ", correct answer is " + c.getC();
System.out.println();
}
}
____________________________________________________________________________
/* This prints out the history array */
//prtHistoryAndOutro
public void prtHistoryAndOutro() {
System.out.println("Problems");
for (int i = 0; i < numProb; i++) {
System.out.println(history[i]);
}
System.out.println();
System.out.println();
System.out.println("Thank you for using the 3312 FlashCard System, " + name + ".");
System.out.println("Come back and play again real soon!");
}
I don't know where something is going wrong but it should be within these three pieces of code. Also the bottom two pieces are within the same class

Setting up a highscore by using arrays

So our teacher told us to create a JApplet with a highscore.
He wanted us to use an Arraylist which contains 10 integer values. If u press a JButton these values are getting displayed in a JLabel. And you can enter a number and where it is placed in the Array. Like if I enter 10 and in the other text field 0, the number 10 is the first number which gets displayed when I press the button. But the other 10 integer values are supposed to move one digit up in the array.
e.g I enter nothing I get displayed
1,2,3,4,5,6,7,8,9,10
and when I enter 10 and 0 it should display
10,1,2,3,4,5,6,7,8,9,10.
My problem is that I don't get how to move the numbers like I can only get this thing if I enter 10 and 0:
10,2,3,4,5,6,7,8,9,10
Here is my Code:
public void neueListe (int Stelle,int Zahl, int[] highscore){
highscore[Stelle] = Zahl;
}
public void jButton1_ActionPerformed(ActionEvent evt) {
int Stelle = Integer.parseInt(jTextField2.getText());
int Zahl = Integer.parseInt(jTextField1.getText());
int[] highscore = new int [10];
highscore[0]=1;
highscore[1]=2;
highscore[2]=3;
highscore[3]=4;
highscore[4]=5;
highscore[5]=6;
highscore[6]=7;
highscore[7]=8;
highscore[8]=9;
highscore[9]=10;
neueListe(Stelle,Zahl, highscore);
jLabel1.setText(""+ highscore[0]+", " + highscore[1]+", " + highscore[2]+", "+ highscore[3] + highscore[4] + highscore[5] + highscore[6] + highscore[7] + highscore[8] + highscore[9]);
}
Convert your int[] into ArrayList and then simply add any element at any position using add method.
ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(highscore));
arr.add(Zahl, Stelle); // arr.add(position, value)
System.out.println(arr);
if you want to print all no.s as string then use this.
String labelshow = "";
for(Integer item: arr){
labelshow += "," + item;
}
jLabel1.setText(labelshow);
Or you can simply put your no. in required position and shift rest of the elements towards right using a for loop.(size would be increased keep this in mind.)
int newarray[] = new int[highscore.length+1];
for(int i=0, j=0; i<highscore.length+1; i++){
if(i == Zahl){
newarray[i] = Stelle;
}
else{
newarray[i] = highscore[j++];
}
}
newarray contains your resultant array. You can print it or show it in JLabel.

why do my simple arrays not work?

This program should ask how many of an animal are left in the wild 5 times. Then it should use a second method to output the same information. But i cant figure this out; every time i change anything based on previous questions here i just add to the number of errors.
import java.util.Scanner;
class animals {
public static void main(String[] args) {
int[] q1 = question();
output(q1);
System.exit(0);
} // exit main
public static int[] question() {
String[] wild = { "Komodo Dragon", "Mantee", "Kakapo", "Florida Panther", "White Rhino" };
int number = 0;
int[] record = {};
for (int i = 1; i <= 5; i++) {
System.out.println(wild[number] + ":");
Scanner scanner = new Scanner(System.in);
System.out.println("How many are left in the wild?");
int howMany = scanner.nextInt();
record = new int[] {howMany};
number++;
}//end for loop
return record;
}// end method question
public static void output(int[] q1){
System.out.println("There are " + q1[0] + " Komodo Dragons in the wild");
System.out.println("There are " + q1[1] + " Mantees in the wild");
System.out.println("There are " + q1[2] + " Kakapos in the wild");
System.out.println("There are " + q1[3] + " Florida Panthers in the wild");
System.out.println("There are " + q1[4] + " White Rhinos in the wild");
}//end method output
} // end class animals
So this compiles alright, then when i've added 5 numbers in terminal after each loop i get
There are 3 Komodo Dragons in the wild
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at animals.output(animals.java:39)
at animals.main(animals.java:13)
Other than the fact that im getting the text, the monodo dragon number being provided is the last number i input not the first
This doesn't make sense
int[number] record = {};
most like what you meant was
int[] record = new int[wild.length];
and instead of
for (int i = 1; i <= 5; i++) {
you need
for (int i = 0; i < wild.length; i++) {
instead of the following which creates an array of 1 value [0]
record = new int[] {howMany};
which will produce the following when you try to access [1]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
you need
record[i] = howMany;
As you write each line of code in your IDE (or your editor) you should see if that compiles and if it doesn't adding more lines is unlikely to help. I suggest you try to compile and test as often as possible so you know where the source of your errors are and when you get a bug, you can step through the code in your debugger to see why the program is not doing what you expect.
This is what you need:
int number = 0;
int[] record = new int[5];
and another modification which you need to make:
int howMany = scanner.nextInt();
record[number] = howMany;
Remove comment from last line.
Now your program should work fine.
Learn some basic stuff about arrays.

How to display all scores at the end without a loop?

I am trying to display my score at the end of a questionnaire however my way of doing it only displays the last score.
It would work if I were to put it in a loop, the JOptionPane.showMessageDialog however I only want it to display this once, at the end.
Here is my code.
//Main method
JOptionPane.showMessageDialog(null, printPlayerScore(playerName, playerAge, playerScore, playerCount));
//printPlayerScore method
public static String printPlayerScore(String playerName[], int playerAge[], int playerScore[], int playerCount) {
String displayResult = "";
for(int i = 0; i < playerCount; i++) {
displayResult += "\nName: " + playerName[i] + "\nAge: " + playerAge[i] + "\nScore: " + playerScore[i] + "\n";
}
return displayResult;
}
Example run:
Player1: 12
Player2: 12
When it should be
Player1: 10
Player2: 12
I know I need to change the method to something else, but how else could I do it?
Full code: http://pastebin.com/NME8Dh7N
This is a screaming example of the benefits of Object-Oriented Programming. OOP will make this chunk of code easier to debug, read, and write. I'll write some quick code to explain this better (by no means is it perfect). Notice how we can easily create a nice output string using the properties of a Player. Create an array of Player objects, and pass it into your print method.
public class Player
{
public String name;
public int age;
public int score;
public String toString()
{
return String.format("\nName : %s\nAge: %d\nScore: %s\n", name, age, score);
}
}
public static String printPlayerScore(Player[] players)
{
String displayResult = "";
for(Player player : players)
{
displayResult += player.toString();
}
return displayResult;
}
I personally would not code this problem the way you did as it's not OOP and just very confusing. However, here is something you can use so as to not totally break your code but fix your problem.
The main question you are trying to answer is why is the last score showing up. As others have stated, you are using one array for player scores. Here is hack to change your code to get it working:
List<int[]> playerScoresList = new ArrayList<int[]>();
for (int i = 0; i < playerCount; i++)
{
int playerScore[] = new int[1];
JOptionPane.showMessageDialog(null, "It is " + playerName[i] + "'s turn now!");
checkQuestion(question, questionAnswer, userAnswer);
System.out.println("Name: " + playerName[i] + " || Age: " + playerAge[i] + "\n\n ~~~~ Results ~~~~");
System.out.println(printQuestionnaireResults(question, userAnswer) + " ~~~~ End of Results ~~~~\n");
playerScore = calculatePlayerScore(userAnswer, playerScore, playerCount);
// double playerScorePercentage = ((double)playerScore[i] / (double)question.length) * 100;
double playerScorePercentage = ((double)playerScore[0] / (double)question.length) * 100;
System.out.println(playerName[i] + " got " + playerScore[0] + " questions correct out of " + question.length + "! (" +
playerScorePercentage + "%)\n");
playerScoresList.add(playerScore);
}
JOptionPane.showMessageDialog(null, printPlayerScore(playerName, playerAge, playerScoresList, playerCount));
Other methods that need to be changed:
public static int[] calculatePlayerScore(boolean userAnswer[], int playerScore[], int playerCount) {
for (int i = 0; i < 1; i++) {
playerScore[i] = 0;
for (int ii = 0; ii < userAnswer.length; ii++) {
if (userAnswer[ii]) {
playerScore[i] += 1;
}
}
}
return playerScore;
}
And:
public static String printPlayerScore(String playerName[], int playerAge[], List<int[]> playerScore, int playerCount) {
String displayResult = ""; // Maybe use StringBuilder
for(int i = 0; i < playerCount; i++)
{
int[] score = playerScore.get(i);
displayResult += "\nName: " + playerName[i] + "\nAge: " + playerAge[i] + "\nScore: " + score[0] + "\n";
}
return displayResult;
}
Now, you will create a new array with one element each time for each user.
Please keep in mind this hack is provided such that there should be minimal change in your current code. You should seriously consider re-writing the entire program IMO. I've also commented out some other code as well just to get it working.
According to your pastebin, you only have 1 array for storing question answers. Meaning the n+1 player is overwriting n player's answers.
You could either do a matrix (Array of Arrays), or the easier to read alternative, make a class for players and have that class manage player data, with the program having only a list of players. It will reduce the number of parameters in the function calls and allow for easy individualization of answers.
public class Player {
private String name;
private List<boolean> answers;
private int playerId;
}
The matrix would work like this:
boolean answers[][] = new boolean[playerCount][questionCount];
That way, each player has a separate list of answers that independ from each other.
Then, all you need would be to get send each player as a parameter to the functions and read those as necessary.

Looping String arrays : cannot find symbol error

I'm new to java and I'm banging my head against a wall with a task. I need to get this to work. Can anyone tell me where I went wrong? I need to write an application for Carl’s Carpentry that shows a user a list of available items: table, desk, dresser, or entertainment center. Allow the user to enter a string that corresponds to one of the options, and display the price as $250, $325, $420, or $600, accordingly. Display an error message if the user enters an invalid item. The program MUST contain parallel arrays.
import javax.swing.*;
public class CarpentryChoice
{
public static void main(String[] args)
{
String entry;
String [] item = {"table","desk","dresser","entertainment center"};
int [] price = {250, 325, 420, 600};
String strPiece;
int x, fi = 99;
String prompt = "Please select an item\n" +
"Our furniture is:\n" + "Table\n" +
"Desk\n" +
"Dresser\n" +
"Entertainment center\n" +
"Enter an item letter";
entry = JOptionPane.showInputDialog(null, prompt);
entry = strPiece.ToString();
for(x = 0; x < item.length; ++x)
if(strPiece == item[x])
fi = x;
if(fi == 99)
JOptionPane.showMessageDialog(null,
"Invalid item code entered");
else
{
if (fi > 2)
fi = fi - 3;
JOptionPane.showMessageDialog(null, "Furniture item " +
strPiece + " is priced at $" +
price[fi]);
}
System.exit(0);
}
}
Any help is MUCH appreciated!!
Thanks!
It is toString instead of ToString.
Why are you assigning entry twice? The second assignment will override what the user input via the prompt dialog. You don't need the variable strPiece in this case. You can just use entry:
entry = JOptionPane.showInputDialog(null, prompt);
for(x = 0; x < item.length; ++x)
To compare Strings, use the equals instead of the == operator:
if(entry.equals(item[x]))
And in the part that displays the result dialog, use entry again instead of strPiece (simply remove strPiece from the entire code):
JOptionPane.showMessageDialog(null, "Furniture item " +
entry + " is priced at $" +
price[fi]);

Categories

Resources