I'm trying to generate random questions into a quiz. Currently everything is fine but the questions are repeating, how would you keep them from repeating? I've read several articles but I just don't quite understand how to implement the code.
public class CplusQuiz extends AppCompatActivity {
Button answer1, answer2, answer3, answer4;
TextView score, question;
private Questions mQuestions = new Questions();
private String mAnswer;
private int mScore = 0;
private int mQuestionLength = mQuestions.mQuestions.length;
Random r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cplus_quiz);
r = new Random();
answer1 = (Button) findViewById(R.id.answer1);
answer2 = (Button) findViewById(R.id.answer2);
answer3 = (Button) findViewById(R.id.answer3);
answer4 = (Button) findViewById(R.id.answer4);
score = (TextView) findViewById(R.id.score);
question = (TextView) findViewById(R.id.question);
score.setText("Nerd Level: " + mScore);
updateQuestion(r.nextInt(mQuestionLength));
answer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(answer1.getText() == mAnswer) {
mScore++;
score.setText("Score: "+ mScore);
updateQuestion(r.nextInt(mQuestionLength));
}
else {
gameOver();
}
}
});
answer2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(answer2.getText() == mAnswer) {
mScore++;
score.setText("Score: "+ mScore);
updateQuestion(r.nextInt(mQuestionLength));
}
else {
gameOver();
}
}
});
answer3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(answer3.getText() == mAnswer) {
mScore++;
score.setText("Score: "+ mScore);
updateQuestion(r.nextInt(mQuestionLength));
}
else {
gameOver();
}
}
});
answer4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(answer4.getText() == mAnswer) {
mScore++;
score.setText("Score: "+ mScore);
updateQuestion(r.nextInt(mQuestionLength));
}
else {
gameOver();
}
}
});
}
private void updateQuestion(int num) {
question.setText(mQuestions.getQuestion(num));
answer1.setText(mQuestions.getChoice1(num));
answer2.setText(mQuestions.getChoice2(num));
answer3.setText(mQuestions.getChoice3(num));
answer4.setText(mQuestions.getChoice4(num));
mAnswer = mQuestions.getCorrectAnswer(num);
}
private void gameOver() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(CplusQuiz.this);
alertDialogBuilder
.setMessage("Epic Fail... Your nerd level is " + mScore + " ")
.setCancelable(false)
.setPositiveButton("Start Over",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
startActivity(new Intent(getApplicationContext(), CplusQuiz.class));
finish();
}
})
.setNegativeButton("EXIT TO MAIN",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
Questions.java file
package com.example.max.quiz;
/**
* Created by max on 4/24/2017.
*/
public class Questions {
public String mQuestions[] = {
"WHO IS THE FASTEST OF THESE VIDEO GAME CHARACTERS?",
"IN THE GAME HALO, WHAT IS THE NAME OF MASTER CHIEF'S AI SIDEKICK?",
"WHICH BAD GUY WAS INTRODUCED IN SUPER MARIO BROTHERS 2?",
"WHAT VIDEO GAME CONSOLE HAS THE HIGHEST NUMBER OF VIDEO GAME CONSOLE SALES OF ALL TIME?",
"WHICH OF THESE DO YOU NOT DO IN WE LOVE KATAMARI, THE SEQUEL TO KATAMARI DAMACY?",
"WHICH OF THESE BANDS IS NOT FEATURED IN GUITAR HERO III: LEGENDS OF ROCK?",
"HOW MANY UNLOCKABLE CHARACTERS CAN BE FOUND IN SUPER SMASH BROTHERS?",
"WHAT WAS NINTENDOS FIRST TRY AT AN ARCADE GAME?",
"WHICH DOES NOT HAVE WIFI?",
"WHAT VIDEO GAME CONSOLE HAS THE HIGHEST NUMBER OF VIDEO GAME CONSOLE SALES OF ALL TIME?",
};
private String mChoices[][] = {
{"Mario", "Sonic", "Donkey Kong", "The Paperboy"},
{"Cortana", "Arbiter", "343 Guilty Spark", "HAL"},
{"Koopa troopa", "Lakitu", "Shy Guy", "Goomba"},
{"Xbox 360", "Nintendo 64", "Wii", "PlayStation 2"},
{"roll around under water", "roll around while on fire", "roll around on the moon", "roll around a sumo wrestler"},
{"Metallica", "Weezer", "Iron Maiden", "Lynyrd Skynyrd"},
{"1", "2", "3", "4"},
{"Super Mario Brothers", "Donkey Kong Jr.", "Donkey Kong", "Final Fantasy"},
{"Mario Kart DS", "Diddy Kong Racing DS", "Tony Hawk's American Sk8land", "Super Mario 64 DS"},
{"Xbox 360", "Nintendo 64", "Wii", "PlayStation 2"},
};
private String mCorrectAnswers[] = {"Sonic", "Cortana", "Shy Guy", "PlayStation 2","roll around on the moon", "Iron Maiden", "4", "Donkey Kong", "Super Mario 64 DS", "PlayStation 2" };
public String getQuestion(int a) {
String question = mQuestions[a];
return question;
}
public String getChoice1(int a) {
String choice = mChoices[a][0];
return choice;
}
public String getChoice2(int a) {
String choice = mChoices[a][1];
return choice;
}
public String getChoice3(int a) {
String choice = mChoices[a][2];
return choice;
}
public String getChoice4(int a) {
String choice = mChoices[a][3];
return choice;
}
public String getCorrectAnswer (int a) {
String answer = mCorrectAnswers [a];
return answer;
}
}
Here's a solution in JavaScript - you can follow the logic and the hopefully apply the concepts to your Java project. There's a running demo in this Plunkr https://plnkr.co/edit/KcHh63ou25LZDaZ79iwI?p=preview
Basically what we're doing is creating an initial array of all the possible questions, and an empty array of questions we're going to include on the quiz. We decide how many questions to include, in this example 5, and then loop that number of times.
On each iteration, we get the current length of the array holding all the possible questions, and pick a random number between 0 and the number of questions left in the array, then we push the question at that index value onto our array of quiz questions, and slice that question out of our array of possible questions so it's not there to get picked a second time.
Then we iterate again, now the source question array is one shorter, we get it's new length, pick a new random number and grab that question, add it to our quiz array, slice it out of our source questions array.
Lather, rinse, repeat.
questionsSource = [{
"question": "What is your favourite colour?",
"answer": "blue",
}, {
"question": "What is the average airspeed of a coconut laden swallow?",
"answer": "African or European Swallow?",
}, {
"question": "Question 3?",
"answer": "Answer 3",
}, {
"question": "Question 4?",
"answer": "Answer 4",
}, {
"question": "Question 5?",
"answer": "Answer 5",
}, {
"question": "Question 6?",
"answer": "Answer 6",
}, {
"question": "Question 7?",
"answer": "Answer 7",
}, {
"question": "Question 8?",
"answer": "Answer 8",
}]
questionsLeft = questionsSource;
questionsPicked = [];
questionsInQuiz = 5; // how many questions you want to look up
for (i = 0; i < questionsInQuiz; i++) {
questionsLeftInArray = this.questionsLeft.length;
randNumber = Math.floor(Math.random() * questionsLeftInArray);
// pick a random number between 0 and the number of questions left in the array.
this.questionsPicked.push(questionsLeft[randNumber]);
// add the randomly selected question to the questionsPicked array.
this.questionsLeft.splice(randNumber, 1);
// remove that question from the remaining questions so it can't be picked again.
}
console.log("QuestionsSource", questionsSource);
console.log("questionsPicked", questionsPicked);
output = JSON.stringify(questionsPicked, null, 4)
document.write(output);
Related
I am developing an application to collect data in the field on Android devices using speech recognition. There are five "target words", as well as several numbers (zero, one, ten, one-hundred, etc) that are recognized.
I have improved accuracy of the target words by adding homonyms (homophones) as well as vernacular synonyms. Target words are Chinook, sockeye, coho, pink, and chum. This is the relevant code,
public void parseWords() {
List<String> szlNumbers = Arrays.asList(new String[]{"ONE", "TEN", "ONE HUNDRED", "ONE THOUSAND", "TEN THOUSAND"});
//species with phonemes and vernacular names
List<String> szlChinook = Arrays.asList("CHINOOK", "CHINOOK SALMON", "KING", "KINGS", "KING SALMON", "KING SALMAN");
List<String> szlSockeye = Arrays.asList("SOCKEYE", "SOCCER", "SOCKEYE SALMON", "SOCK ICE", "SOCCER ICE", "SOCK I SAID", "SOCCER IS", "OKAY SALMON", "RED SALMON", "READ SALMON", "RED", "REDS");
List<String> szlCoho = Arrays.asList("COHO", "COHO SALMON", "COVER SALMON", "SILVER SALMON", "SILVER", "SILVERS", "CO", "KOBO", "GO HOME", "COMO", "COVER", "GO");
List<String> szlPink = Arrays.asList("PINK", "A PINK", "PINKS", "PINK SALMON", "HANK SALMON", "EXAMINE", "HUMPY", "HOBBY", "HUMPIES", "HUM BE", "HUM P", "BE", "HUMPTY", "HOBBIES", "HUMVEE", "THE HUMVEES", "POMPEY");
List<String> szlChum = Arrays.asList("CHUM", "JOHN", "JUMP", "SHARMA", "CHARM", "COME", "CHARM SALMON", "COME SALMON", "CHUM SALMON", "JUMP SALMON", "TRUMP SALMON", "KETA SALMON", "KETA", "DOG", "DOGS", "DOG SALMON", "GATOR", "GATORS", "CALICO", "A CALICO");
//Collections.sort(szlChinook); //what is this?
szVoskOutput=szVoskOutput.toUpperCase();
if (szVoskOutput.compareTo("")==0){
//do nothing, this is a blank string
return;
}
if(szVoskOutput==null){//...and this is a null string
return;
}
//pink
if (szlPink.contains(szVoskOutput)) {
szSpecies = "Pink";
populateSpecies();
return;
}
//chum
if (szlChum.contains(szVoskOutput)) {
szSpecies = "Chum";
populateSpecies();
return;
}
//sockeye
if (szlSockeye.contains(szVoskOutput)) {
szSpecies = "Sockeye";
populateSpecies();
return;
}
//coho
if (szlCoho.contains(szVoskOutput)) {
szSpecies = "Coho";
populateSpecies();
return;
}
//Chinook
if (szlChinook.contains(szVoskOutput)) {
szSpecies = "Chinook";
populateSpecies();
return;
}
if(szlNumbers.contains(szVoskOutput)) {//then this is a number, put in count txt box
tvCount.setText(szVoskOutput);
return;
}else{
Toast.makeText(this, "Please repeat clearly. Captured string is:" + szVoskOutput, Toast.LENGTH_SHORT).show();
}
}//end parseWords()
I have a streamlined version of the application with source code on GitHub: https://github.com/portsample/salmonTalkerLite
as well as the latest full version on Google Play: https://play.google.com/store/apps/details?id=net.blepsias.salmontalker
Using the target word and homonyms, I can get hits in four to five seconds. I would like to make this faster. What can I do to further tune for speed?
This helped out significantly. Recognition time is now consistently about 1.5 seconds.
private void recognizeMicrophone() {
if (speechService != null) {
setUiState(iSTATE_DONE);
speechService.stop();
speechService = null;
} else {
setUiState(iSTATE_MIC);
try {
Recognizer rec = new Recognizer(model, 16000.f, "[\"sockeye pink coho chum chinook atlantic salmon\","[unk]"]");
speechService = new SpeechService(rec, 16000.0f);
speechService.startListening(this);
} catch (IOException e) {
setErrorState(e.getMessage());
}
}
}
This clears out the upstream extraineous Vosk output leaving only specified target words. This will eliminate the need for the elaborate homonym sorting conditionals shown in the original post. Thanks to Nickolay Shmyrev for this.
I am still looking for other methods to speed recognition up, or otherwise improve this process.
Updates and improvements will be reflected in source code on GitHub: https://github.com/portsample/salmonTalkerLite
private void createRooms()
{
myNeighbor = new HashMap <String, Room> ();
crumbs = new Item("Crumbs", "small crumbs of some kind of food", 100);
eggs = new Item("Raw Eggs", "a couple of raw eggs still contained within their egg shells", 1100);
cellPhone = new Item("Cell Phone", "Mike's cell phone he must have forgotten here...", 0);
textBooks = new Item("Textbooks", "Jay's textbooks, because he can't use his bedroom to store his stuff", 0);
poptarts = new Item("Pop Tarts", "an un-opened box of chocolate pop tarts that someone must have left behind...", 1500);
pizzaRolls = new Item("Pizza Rolls", "cooked steaming pizza rolls piled high", 2000);
clothes = new Item("Clothes", "clothes, a lot of clothes all over the floor and all over the room, who knows if they're clean or not...", 0);
// miningTools = new Item("Mining Tools", "pickaxes, drills, and everything else you need to extract rocks and minerals from the earth's crust", 100);
chips = new Item("Chips", "chip bag hidden away that is only half full now", 400);
hallway = new Room("in a dark hallway with crumbs scattered over the ground", crumbs);
kitchen = new Room("in a kitchen with raw eggs lying on the counter tops", eggs);
bathroom = new Room("in a bathroom with a stand up shower, a washer, a drier, and Mike's cell phone left behind laying on the counter", cellPhone);
livingRoom = new Room("in a living room with Jay's textbooks all over the room", textBooks);
upstairsLobby = new Room("in a lobby at the top of the stairs with a box of pop tarts on the ground", poptarts);
blakesRoom = new Room("in a dark room with towers of pizza rolls covering the desk and scattered across the bed", pizzaRolls);
jaysRoom = new Room("in a cluttered room with clothes covering every inch of the floor and nothing hanging on the walls", clothes);
mikesRoom = new Room("in a bed room with mining tools and a bag of chips hidden underneath a pillow on the bed", chips);
hallway.addNeighbor("north", kitchen);
hallway.addNeighbor("west", upstairsLobby);
hallway.addNeighbor("east", livingRoom);
kitchen.addNeighbor("west", bathroom);
kitchen.addNeighbor("south", hallway);
bathroom.addNeighbor("east", kitchen);
livingRoom.addNeighbor("west", hallway);
upstairsLobby.addNeighbor("north", jaysRoom);
upstairsLobby.addNeighbor("west", blakesRoom);
upstairsLobby.addNeighbor("east", mikesRoom);
upstairsLobby.addNeighbor("south", hallway);
blakesRoom.addNeighbor("east", upstairsLobby);
jaysRoom.addNeighbor("south", upstairsLobby);
mikesRoom.addNeighbor("west", upstairsLobby);
}
Room class
import java.util.HashMap;
/**
* Write a description of class Room here.
*
* #author (Christopher a date)
*/
public class Room
{
private String description;
private Item item;
private HashMap <String, Room> myNeighbor;
public Room (String pDescription)
{
description = pDescription;
item = null;
HashMap <String, Room> myNeighbor = new HashMap <String, Room> ();
}
public Room (String pDescription, Item pItem)
{
description = pDescription;
item = pItem;
}
public String getDescription()
{
return description;
}
public Item getItem()
{
return item;
}
public void addItem(Item i)
{
item = i;
}
public boolean hasItem()
{
if (item != null)
return true;
else
return false;
}
public void addNeighbor(String pDirection, Room r)
{
myNeighbor = new HashMap <String, Room> ();
myNeighbor.put(pDirection, r);
}
public Room getNeighbor(String pDirection)
{
Room next = myNeighbor.get(pDirection);
if(next != null){
return next;
}
else{
return null;
}
}
public Item removeItem()
{
Item temp;
temp = item;
item = null;
return temp;
}
public String getLongDescription()
{
String part1 = "You are " + description;
String part2 = "You see ";
if(item != null){
return part1 + "" + part2 + "" + item.getDescription() + "" + item.getCalories();
}
return part1;
}
}
Long story short, the point of this is to add Rooms and be able to naviage them and pick up items and drop them. It has just been brought to my attention as I try to run the program that I can't have multiple north/south/east/west keys. How can I get around this so I can make this work?
It wont allow me to comment so...
I am not sure what your ROOM class looks like but I am guessing it is intialized with a hasmap in the constuctor, and ahs a method called addNeighbor to actuallymodify this hash map?
----EDIT-----
Seeing your AddNeighbor method shows that you create a new hasmap every time you add a neighbor to the hashmap. There is no need and you alraedy craeted MyNeighbor in the constuctor, now you can just "put" they new key, value combination in the hash map
Just remove the line to create a new hasmap every time.
Assuming that you want to be able to write:
Room targetRoom = currentRoom.neighbour("north");
then you need to change your design.
The neighbours need to be member (ivars) of a room, like this for example:
class Room;
typedef HashMap<string, Room*> NeighbouringRooms;
public class Room {
...
public NeighbouringRooms const& neighbour() const {
return _neighbours;
}
private NeighbouringRooms neighbours;
}
(I've omitted some details inside the class, like adding a neighbour to a room.)
Now, since there are only 4 possible directions (N, S, E, W), an array of neighbours for each room would do the trick as well.
public class Room {
public Room neighbours[4];
...
}
Room room;
room.neighbour[north] = ... ;
I have created code which adds,deletes and modify objects added to the arraylist.when i select the remove method it shows the above error.how do i solve it.This code is where i am running everything.It has an instance of the member class which has all methods neccessary
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MedicalAid
{
class MedicalTest
{
//instance of MedicalTest class
public static MedicalTest medicalMember = new MedicalTest();
//array list to hold member objects
static List<Member> customer = new List<Member>();
//instance of Member class
static Member member = new Member();
//some important booleans
private bool isSubscribed;
private bool isDeducted;
private bool isToBeRemoved;
private bool isToBeAdded = true;
//add passed memebers to arraylist
public void addMembersToArrayList()
{
customer.Add(member1);
customer.Add(member2);
isToBeAdded = false;
}
//method to add member
public void AddMember(Member name)
{
customer.Add(name);
}
//method to remove a member
public void RemoveMember(String removeName) {
foreach (Member i in customer) {
if (isToBeRemoved)
{
if (i.GetName() == removeName)
{
Console.WriteLine("Found and Removed");
customer.Remove(i);
}
else{Console.WriteLine("Not Found");}
}
if(isSubscribed)
{
if (i.GetName() == removeName)
{
//if delete member is true,delete member
Console.WriteLine("Found and Transaction Made");
i.makeSubscription();
i.showMember();
}//closes isToBeDeleted
else { Console.WriteLine("Not Found"); }
}
if(isDeducted){
if (i.GetName() == removeName)
{
//if delete member is true,delete member
Console.WriteLine("Found and Transaction Made");
i.makeSubscription();
i.showMember();
}//closes isToBeDeleted
else
{
Console.WriteLine("Not Found");
}
}//closes deducted if
}
}
//method to iterate through customer and remove a member
public void ViewMembers()
{
//iterate throus the customer list and print details of any member availabe
if(customer.Capacity == 0){
Console.WriteLine("Medical Aid List is Empty");
}else{
foreach(Member i in customer){
i.showMember();
}
}
}
//create two objects with details
Member member1 = new Member("male",
"Z.N.A",
" 272 Area 3 D/Mvura Mutare",
"Premium",
"JAMES",
500.00,
"Dr Bvirakure",
"xx-xxxxx y XX",
//spouse
"xx/xx/1987",
"JOSEPHINE MANYORE",
"XX-XXXXX-XX",
//family doctor
"DANGAMVURA SHOPPING MALL",
"0773 0733 0734",
//dependent
"male",
"ANDREW BLESSING MANYORE",
"75-426820 Y 50",
//bank details
"ZABG",
"Herbet Chitepo",
"xxxxxxxxxxxxx",
"xxxxxxxxxxxxx",
"Mutare");
Member member2 = new Member("female",
"MINISTRY OF EDUCATION",
" 272 Area 3 D/Mvura Mutare",
"Premium",
"TAPIWA",
500.00,
"Dr Bvirakure",
"xx-xxxxx y XX",
//spouse
"xx/xx/1987",
"JAMES MANYORE",
"XX-XXXXX-XX",
//family doctor
"DANGAMVURA SHOPPING MALL",
"0773 0733 0734",
//dependent
"male",
"PORTIA TATENDA MANYORE",
"75-426820 Y 50",
//bank details
"ZB",
"Herbet Chitepo",
"xxxxxxxxxxxxx",
"xxxxxxxxxxxxx",
"Mutare");
//method to print saved members
static void Main(string[] args)
{
int option;
string options;
//add the members to the arraylist
if (medicalMember.isToBeAdded)
{
medicalMember.addMembersToArrayList();
}
do{
Console.Write("********Medical Aid*********\n"+
"1.To Add New Member\n"+
"2.To Edit Member Balance if he made a Subscription\n" +
"3.To Edit Member Balance if he received a Service\n" +
"4.To Delete Old Member\n" +
"5.To View Members\n"+
"6.To Exit\n");
options = Console.ReadLine();
option = Convert.ToInt32(options);
switch(option){
case 1: member.GetMember();
medicalMember.AddMember(member);
break;
case 2 : medicalMember.isSubscribed = true;
medicalMember.isDeducted = false;
medicalMember.isToBeRemoved = false;
Console.WriteLine("Enter Member Name who made a Subscription\n");
String memberToGetSer = Console.ReadLine();
medicalMember.RemoveMember(memberToGetSer);
break;
case 3 :medicalMember.isSubscribed = false;
medicalMember.isDeducted = true;
medicalMember.isToBeRemoved = false;
Console.WriteLine("Enter Member Name who received a Service\n");
String memberToGetSub = Console.ReadLine();
medicalMember.RemoveMember(memberToGetSub);
break;
case 4: medicalMember.isSubscribed = false;
medicalMember.isDeducted = false;
medicalMember.isToBeRemoved = true;
Console.WriteLine("Enter Member Name to remove");
String memberToRemove = Console.ReadLine();
medicalMember.RemoveMember(memberToRemove);
break;
case 5: medicalMember.ViewMembers();
break;
case 6: Console.WriteLine("******EXITING********");
Environment.Exit(0);
break;
}//closes switch
}while(option<=5);//closes while
}//closes main
}//closes class
}
You can't call Remove() while inside foreach loop (as long as it concerns the collection you are looping through)
use a for loop:
for (int i=0;i<customer.Count;i++)
{
......
}
From MSDN:
The foreach statement is used to iterate through the collection to get the information that you want,
but can not be used to add or remove items from the source collection to avoid unpredictable side effects.
If you need to add or remove items from the source collection, use a for loop.
See this for more details
just change this in remove Member:
public void RemoveMember(String removeName) {
for (int i=customer.Count - 1;i>=0;i--) {
if (isToBeRemoved)
{
if (customer[i].GetName() == removeName)
{
Console.WriteLine("Found and Removed");
customer.RemoveAt(i);
}
else{Console.WriteLine("Not Found");
}
}
}
You can't remove elements if you're reading forward through a collection as the enumerator would be invalidated. Try using the RemoveAll method, it will do what you want and simplify your code:
if (isToBeRemoved) // No need for a for loop.
{
customer.RemoveAll(elem => elem.GetName() == removeName);
}
I found a problem when i use the pivot control in the Windows Phone 8 SDK.
The pivot binds to a list named Students and set a button when click it,Will new a new student object and set it to Students[2] as new value. This has lead to the overlapping problem shown in the screenshot below. Has anyone else had this problem in the WP8 SDK?
Here is the code
public MainPage()
{
InitializeComponent();
this.DataContext = this;
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
InitiList();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
int index = 2;
Students[index] = new Student();
Students[index].Name = "tian";
Students[index].College = "shida";
}
private ObservableCollection<Student> _students;
public ObservableCollection<Student> Students
{
get { return _students; }
set
{
_students = value;
RaisePropertyChanged("Students");
}
}
private void InitiList()
{
Students = new ObservableCollection<Student>();
Students.Add(new Student { Name="a",College="aa"});
Students.Add(new Student { Name = "b", College = "aa" });
Students.Add(new Student { Name = "c", College = "aa" });
Students.Add(new Student { Name = "d", College = "aa" });
Students.Add(new Student { Name = "e", College = "aa" });
}
Ckeck this o/p image:
You're modifying Students but RaisePropertyChanged isn't getting fired because accessing Students doesn't fire Set, which calls RaisePropertyChanged. This could be the problem, I can't test it right now.
I experience the same issue, and I fixed it by adding the items to the ObservableCollection in the constructor instead of using the Add method. It appears to be a bug with the ObservableCollection class. Try changing your code to:
private void InitiList()
{
Students = new ObservableCollection<Student>(new [] {
new Student { Name="a",College="aa"}),
new Student { Name = "b", College = "aa" }),
new Student { Name = "c", College = "aa" }),
new Student { Name = "d", College = "aa" }),
new Student { Name = "e", College = "aa" })
});
}
So, I made a class that takes arrays and calculates a value from them. I then decided (unknowingly) to incorporate it into a GUI interface. All went well until I noticed this strange error; one of the jtextfields (prarie) would not store text while the other (yard) does.
I looked around and found my problem similiar to mine on this site;
Updating text in a JTextField
But he had one that doesn't work at all, where I have one that works and one that doesn't.
The Code is here (it's a bit long, but most of it is GUI), so hold your breath!:
import java.awt.GridLayout;
import javax.swing.Box;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Window {
/**
* #param args
*/
private static int numb;
private static double micro, centi;
private static JTextField[] yard,prarie;
private static double[] charges,distances;
public static void main(String[] args)
{
//create a small dialog window to take in number of charged objects
JPanel startup = new JPanel();
JTextField many = new JTextField(5);
startup.add(many);
int result = JOptionPane.showConfirmDialog(null,startup , "Please Enter How Many Charged Objects are Being Evaluated", JOptionPane.OK_CANCEL_OPTION);
many.requestFocusInWindow();
//once ok is clicked, then the number input will be stored under 'numb'
//then proceed to inputFields
if (result == JOptionPane.OK_OPTION)
{
numb = Integer.parseInt(many.getText());
inputFields();
}
}
//this window opens the various JTextFields for input
public static void inputFields()
{
//top JTextFields
yard = new JTextField[numb];
JPanel chargePanel = new JPanel();
for(int x=0;x<numb;x++)
{
yard[x] =new JTextField(5);
chargePanel.add(new JLabel("Charge "+ Integer.toString(x+1)+":"));
chargePanel.add(yard[x]);
chargePanel.add(Box.createVerticalStrut(15)); // a spacer
}
//bottom JTextFields
prarie = new JTextField[numb-1];
JPanel meterPanel = new JPanel();
for(int x=0;x<numb-1;x++)
{
prarie[x]=new JTextField(5);
meterPanel.add(new JLabel("Meters "+ Integer.toString(x+1)+":"));
meterPanel.add(new JTextField(5));
meterPanel.add(Box.createVerticalStrut(15)); // a spacer
}
//JCheckBoxes
JCheckBox isMicro = new JCheckBox("Charges are in terms of microCoulombs");
JCheckBox isCm = new JCheckBox("Distances are in terms of centiMeters");
JPanel chechBox = new JPanel();
chechBox.add(isMicro);
chechBox.add(Box.createVerticalStrut(20));
chechBox.add(isCm);
//Paste them all together into one window
GridLayout gufi = new GridLayout(3,1);
JPanel host = new JPanel(gufi);
host.add(chargePanel);
host.add(meterPanel);
host.add(chechBox);
int result1 = JOptionPane.showConfirmDialog(null, host, "Please Enter Charge and Distance Values", JOptionPane.OK_CANCEL_OPTION);
//if ok is clicked, then go to 'printArr()' to print the JTextFields
//then go to assign the values from the JTextFields to private double arrays 'yard' and 'prarie'
if (result1 == JOptionPane.OK_OPTION)
{
micro = (isMicro.isSelected())? Math.pow(10, -6): 1;
centi = (isCm.isSelected())? .01: 1;
printArr();
assign();
}
}
//a makeshift method to print the value from the JTextFields
//to fix the problem of why prarie wouldn't store numbers
public static void printArr()
{
System.out.println("Charges are:");
for(int x=0;x<numb;x++)
System.out.print(yard[x].getText() + " ");
System.out.println("Distances are:");
for(int x=0;x<numb-1;x++)
System.out.print(prarie[x].getText() + " ");
}
//assigns values from JTextFields to the private double arrays 'yard' and 'prarie'
public static void assign()
{
try {
charges = new double[numb];
for(int x=0;x<numb;x++)
charges[x]=micro*Double.parseDouble(yard[x].getText().trim());
distances = new double[numb-1];
for(int x=0;x<numb-1;x++)
distances[x]=centi*Double.parseDouble(prarie[x].getText().trim());
} catch (NumberFormatException e) {
e.printStackTrace();
//inputFields();
}
calculate();
}
public static void calculate()
{
JPanel sample = new JPanel();
JTextField whichOne = new JTextField(5);
sample.add(whichOne);
int result = JOptionPane.showConfirmDialog(null,sample , "Please Enter Which Charged Object thy Wishs For", JOptionPane.OK_CANCEL_OPTION);
whichOne.requestFocusInWindow();
if (result == JOptionPane.OK_OPTION)
{
int target = Integer.parseInt(whichOne.getText());
}
}
}
Anyone who runs the code and takes the time to enter dummy values will see that 'yard' stores values while 'prarie' does not. Why is this?
*I'm pretty sure I'm overlooking obvious (as always).
Change:
meterPanel.add(new JTextField(5));
to:
meterPanel.add(prarie[x]);
in the for loop for the prarie textfields