У меня есть задание, над которым я работаю, и мне нужно в основном создать систему, которая проверяет, существует ли уже введенная строка в ArrayList. В случае, если он не существует, он создаст новое целое число с именем точного введенного текста и присвоит значение 1. Если строка уже существует (это означает, что кто-то другой уже ввел этот вариант), тогда он добавит один к уже существующему целому числу. Я просто пытаюсь присвоить целое число со значением строки.
Я попытался напрямую взять ввод и присвоить его строке, для которой я затем пытаюсь использовать строковое значение для создания нового целого числа. Это пока безуспешно.
static int totalSubmissions = 0; // tracks # of custom submissions (used to navigate Array List)
static ArrayList<String> userInputs = new ArrayList<String>(); // contains strings (not listed ice creams) from user input
private static JLabel pollOtherLabel = new JLabel("Unlisted Flavors: ");
private static JTextField customInput = new JTextField();
private static JButton submitInput = new JButton("Submit");
// Above is the totalSubmmissions (used to navigate ArrayList, the list itself, and my label, submit button, and the neccesary code to record what was entered.
@Override
public void actionPerformed(ActionEvent e) {
// checks vote chocolate and contains output
if (e.getSource() == voteChocolate){
chocolateVotes++;
pollOption1Label.setText("Chocolate Votes: " + chocolateVotes);
} else if (e.getSource() == voteVanilla){ // checks vote vanilla and contains output
vanillaVotes++;
pollOption2Label.setText("Vanilla Votes: " + vanillaVotes);
} else if (e.getSource() == voteStrawberry){ // checks vote strawberry and contains output
strawberryVotes++;
pollOption3Label.setText("Strawberry Votes: " + strawberryVotes);
} else if (e.getSource() == submitInput){ // checks custom input and contains output
String currentString = customInput.getText(); // << ISSUE IS HERE
if (userInputs.contains(currentString)){ // want to assign the text field input
int currentString = 1; // to a new integer, that will track
} else { // the number of times that exact string is entered
int customInput.getText() = 1;
}
userInputs.add(customInput.getText());
customInput.setText("");
pollOtherLabel.setText("Unlisted Flavors: " + userInputs.get(totalSubmissions));
totalSubmissions++;
}
}
Я предполагаю, что у этого задания есть несколько предопределенных вкусов (шоколад, ваниль и т. д.), и у них есть специальная кнопка для голосования. Кроме того, он позволяет добавлять в коллекцию свои собственные вкусы и учитывается при голосовании.
Вы не можете инициализировать переменную во время выполнения. Это потому, что вы пишете код, чтобы компьютер запускал его за вас. Вы не можете написать код, поэтому программа сама напишет новый код. (по крайней мере, это не является целью данного задания)
В этом случае я бы предложил вам сохранить вкусы и проголосовать за единую структуру данных. Я вижу, вы храните предопределенные вкусы в strawberryVotes
, chocolateVotes
. Вы можете создать карту для хранения всей необходимой информации, предопределенной или пользовательской. Вам нужно хранить 2 информации. 1) название аромата 2) голосование. Мы можем использовать Карту. Его концепция аналогична таблице.
static int totalSubmissions = 0; // tracks # of custom submissions (used to navigate Array List)
private Map<String, Integer> flavorVotes = new HashMap<String, Integer>();
// contains flavor and vote (not listed ice creams) from user input
private static JLabel pollOtherLabel = new JLabel("Unlisted Flavors: ");
private static JTextField customInput = new JTextField();
private static JButton submitInput = new JButton("Submit");
// define constant for predefined flavor
private static final String FLAVOR_CHOCOLATE = "Chocolate";
private static final String FLAVOR_VANILLA_ = "Vanilla";
private static final String FLAVOR_STRAWBERRY_ = "Strawberry";
// Above is the totalSubmmissions (used to navigate ArrayList, the list itself,
// and my label, submit button, and the neccesary code to record what was
// entered.
@Override
public void actionPerformed(ActionEvent e) {
String flavor;
// checks vote chocolate and contains output
if (e.getSource() == voteChocolate) {
flavor = FLAVOR_CHOCOLATE;
addVote(flavor);
pollOption1Label.setText("Chocolate Votes: " + flavorVotes.get(flavor));
} else if (e.getSource() == voteVanilla) { // checks vote vanilla and contains output
flavor = FLAVOR_VANILLA_;
addVote(flavor);
pollOption2Label.setText("Vanilla Votes: " + flavorVotes.get(flavor));
} else if (e.getSource() == voteStrawberry) { // checks vote strawberry and contains output
flavor = FLAVOR_STRAWBERRY_;
addVote(flavor);
pollOption3Label.setText("Strawberry Votes: " + flavorVotes.get(flavor));
} else if (e.getSource() == submitInput) { // checks custom input and contains output
flavor = customInput.getText();
addVote(flavor);
customInput.setText("");
pollOtherLabel.setText("Unlisted Flavors: " + flavor);
totalSubmissions++;
}
}
private void addVote(String flavor) {
if (flavorVotes.containsKey(flavor)) {
// flavor exists, increment by 1
flavorVotes.put(flavor, flavorVotes.get(flavor) + 1);
} else {
// new flavor, set its vote to 1
flavorVotes.put(flavor, 1);
}
}
p.s. Я думаю, что некоторые атрибуты не должны объявляться как статические. Но это другая тема.
ты не можешь. Что вы можете сделать, так это либо иметь составной объект, ключ String (ваш ввод) и значение (int), либо вы можете создать карту, где ваша строка является ключом, а значение (int) является вводом