I have an array with 5 elements. If a user inputs a name or a title, it should output that person's or job title's corresponding job title and person. Here's what I got, I'm not sure what I could be doing wrong. Since it's an applet, I don't need a main method right? Did I get stuff mixed up? What could I be doing wrong? Even if I input data that is stored in the array, it always gives me "input did not match any records" I would appreciate any help. Thanks in advance!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Assignment extends JApplet implements ActionListener
{
String[] empName = {"John Jacobs" , "Will Watts","Kevin Krust", "Allan Ayers", "Sam Smith"};
String[] empTitle = {"Software Engineer" , "Database Administrator", "Network Administrator" , "Head Programmer" ,"Department Manager"};
final int ARRAY_SIZE = 5;
boolean validName = false;
boolean validTitle = false;
String nameOfEmployee;
String titleOfEmployee;
JLabel enterInfo = new JLabel("Enter an Employee Name or Job Title");
JTextField userInput = new JTextField(20);
JButton empButton = new JButton ("Press if you entered a name");
JButton titleButton = new JButton ("Press if you entered a title");
JLabel inputDisplay = new JLabel("");
Container con = getContentPane();
public void init()
{
con.add(enterInfo);
con.add(userInput);
con.add(empButton);
con.add(titleButton);
con.setLayout(new FlowLayout());
userInput.addActionListener(this);
empButton.addActionListener(this);
titleButton.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{
Object source = event.getSource();
if (source == empButton)
{
String nameEmp = userInput.getText();
con.remove(enterInfo);
con.remove(userInput);
con.remove(empButton);
con.remove(titleButton);
for (int x = 0; x < ARRAY_SIZE; ++x)
{
if (nameEmp == empName[x])
{
validName = true;
titleOfEmployee = empTitle[x];
}
}
if(validName)
inputDisplay.setText(nameEmp + "is a" + titleOfEmployee);
else
inputDisplay.setText("The title you input did not match any records.");
con.add(inputDisplay);
con.setBackground(Color.YELLOW);
}
else
{
String nameJob = userInput.getText();
con.remove(enterInfo);
con.remove(userInput);
con.remove(empButton);
con.remove(titleButton);
for (int x = 0; x < ARRAY_SIZE; ++x)
{
if (nameJob == empTitle[x])
{
validTitle = true;
nameOfEmployee = empName[x];
}
}
if(validName)
inputDisplay.setText(nameOfEmployee + "is a" + nameJob);
else
inputDisplay.setText("The name you input did not match any records.");
con.add(inputDisplay);
con.setBackground(Color.YELLOW);
}
con.invalidate();
con.validate();
}
}
This
nameEmp == empName[x]
compares object references. What you want is comparison of contents, so you should check
nameEmp.equals(empName[x])
When comparing the value input by the user to the values in your arrays, you need to use the equals function and not ==.
Read why here.
Related
Tried writing a sort method where input was given like a string of comma-delimited years and year ranges String input = '2017, 2018,2020-2023,1800-1700,2020,20a9,19z5-1990,2025,20261,2013';
Expectation is to get a string of comma-delimited years and year ranges,and remove all duplicates and invalid inputs.
Below is class written which is not giving me correct output
public class sortYearAndYearRangesString {
public static List<String> sortSpecialString(String input) {
system.debug(input);
List<String> inputList = input.split('');
system.debug(inputList);
Map<Integer,String> stringMap = new Map<Integer,String>();
system.debug(stringMap);
List<String> output = new List<String>();
for (Integer i=0; i<inputList.size(); i++) {
String charac = inputList[i];
if(!charac.isAlphaNumeric()) {
system.debug(charac);
stringMap.put(i,charac);
}else {
output.add(charac);
system.debug(output);
}
}
String finalString = String.join(output,'');
system.debug(finalString);
List<String> resultList = finalString.reverse().split('');
for( Integer I : stringMap.keySet() ){
system.debug(I);
resultList.add(I,stringMap.get(I));
system.debug(resultList);
}
return resultList;
}
Tried validating the solution in Anonymous Apex but no success
public static void validateSolution() {
String input = '2017, 2018,2020-2023,1800-1700,2020,20a9,19z5-1990,2025,20261,2013';
List<Integer> expected = new List<Integer> {2013,2017,2018,2020,2021,2022,2023,2025};
List<Integer> actual = sortYearAndYearRangesString(input);
System.assertEquals(expected, actual, 'Invalid Results');
}
}
Your help is appreciated
Regards
Carolyn
According to your test case, you should also define at least a constant for a maximum value, in order to exclude 20261. Probably you need a minimum too.
I used 1700 as min and 4000 as max because these are the limits for a Date or Datatime field: docs
Moreover the method must return a List<Integer> instead of a List<String>.
You don't need a Map, just a Set would work.
public class SortYearAndYearRangesString {
private static final Integer MAX_YEAR = 4000;
private static final Integer MIN_YEAR = 1700;
public static List<Integer> sortSpecialString(String input) {
Set<Integer> output = new Set<Integer>();
List<String> yearsList = input.split(',');
for (String yearString : yearsList) {
yearString = yearString.trim();
if (yearString.isNumeric()) {
try {
Integer year = Integer.valueOf(yearString);
if (year >= MIN_YEAR && year <= MAX_YEAR) {
output.add(year);
}
} catch (TypeException e) {
System.debug(e.getMessage());
}
} else {
List<String> range = yearString.split('-');
if (range.size() == 2 && range[0].isNumeric() && range[1].isNumeric()) {
try {
// Modify the following two lines once you know how to handle range like 1300-1500 or 3950-4150
Integer firstYear = Math.max(Integer.valueOf(range[0]), MIN_YEAR);
Integer lastYear = Math.min(Integer.valueOf(range[1]), MAX_YEAR);
while (firstYear <= lastYear) {
output.add(firstYear++);
}
} catch (TypeException e) {
System.debug(e.getMessage());
}
}
}
}
List<Integer> sortedYears = new List<Integer>(output);
sortedYears.sort();
return sortedYears;
}
}
If a range that exceed the boundaries (like 1300-1500 or 3950-4150) should be treated as invalid and skipped, please change these lines
Integer firstYear = Math.max(Integer.valueOf(range[0]), MIN_YEAR);
Integer lastYear = Math.min(Integer.valueOf(range[1]), MAX_YEAR);
while (firstYear <= lastYear) {
output.add(firstYear++);
}
as follow:
Integer firstYear = Integer.valueOf(range[0]);
Integer lastYear = Integer.valueOf(range[1]);
if (firstYear >= MIN_YEAR && lastYear <= MAX_YEAR) {
while (firstYear <= lastYear) {
output.add(firstYear++);
}
}
I tested it in anonymous console with the following code:
String input = '2017, 2018,2020-2023,1800-1700,2020,20a9,19z5-1990,2025,20261,2013';
List<Integer> expected = new List<Integer> {2013,2017,2018,2020,2021,2022,2023,2025};
List<Integer> actual = SortYearAndYearRangesString.sortSpecialString(input);
System.debug(actual);
System.assertEquals(expected, actual, 'Invalid Results');
input = '1500,2017, 2018,2020-2023,1800-1700,2020,20a9,19z5-1990,2025,20261,2013,3998-4002';
expected = new List<Integer> {2013,2017,2018,2020,2021,2022,2023,2025,3998,3999,4000};
actual = SortYearAndYearRangesString.sortSpecialString(input);
System.assertEquals(expected, actual, 'Invalid Results');
I made some changes to the class.
It does increment all ranges - and doesn't check if they're years that would make sense. You'll need to add that logic in there (e.g. 1500-1600 would return all years between 1500-1600. Prob best to cap at 1900 or something)
public class SortYearAndYearRangesString{
public static List<Integer> sortSpecialString(String input){
List<String> inputList = input.split(',');
Set<Integer> output = new Set<Integer>();
system.debug('input ' + input);
system.debug('inputList ' + inputList);
for (String s : inputList){
Set<Integer> tempSet = new Set<Integer>();
s.remove(' ');
if (s.contains('-')){
//// break the ranges and fill in years
List<String> tempSet2 = s.split('-');
for (String s2 : tempSet2){
try{
///capture valid integers
Integer tempInt = Integer.valueOf(s2);
tempSet.add(tempInt);
} catch (Exception e){
tempSet.clear();
break;
}
}
System.debug('set ' + tempSet);
if (tempSet.size() > 1){
List<Integer> tempList = new List<Integer>(tempSet);
tempList.sort ();
Integer r = tempList.size() - 1;
// iterate through the years
for (Integer i = tempList.get(0); i < tempList.get(r); i++){
tempSet.add(i) ;
}
}
} else{
try{
///capture valid integers
Integer tempInt = Integer.valueOf(s);
tempSet.add(tempInt);
} catch (Exception e){
continue;
}
}
output.addAll(tempSet);
}
// output is currently set of ints, need to convert to list of integer
List<Integer> finalOutput = new List<Integer>(output);
finalOutput.sort ();
System.debug('finalOutput :' + finalOutput);
return finalOutput;
}}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class JavaClass {
public static void main(String[] args) {
// Things start here
int[][] multi = new int[5][10];
for(int p = 1; p < 5; p++)
{
for(int h = 1;h < 10;h++)
{
System.out.println("Enter the score for Player " + String.valueOf(p) + ", Hole " + String.valueOf(h) + " :");
String v = stringReader();
multi[p][h] = Integer.parseInt(v);
System.out.println(String.valueOf(v));
}
}
}
public static String stringReader()
{
String value;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
try {
value = bufferedReader.readLine();
} catch (IOException e) {
value = "0";
}
return value;
}
Hello! I am currently working on a project for my Grade 12 Computer Science course where i am asked to make a "Golf Score Tracker" the description of the project is (add to the code below code that calculates and displays each golfers individual score)
I've tried working with while loops however whatever I do it does not seem to display. My teacher is also stuck lol he is actually the reason I am here asking for help on this project
I am implementing drop-drown feature in my app. Its implemented using container with list of elements in it.
Suppose the drop down list has following items aa1, aa2, aa3, aa4 aa5 and so on. And if i search as 'aa' it displays items starting from 'aa', if I select aa5 from list, it takes aa1 and displays that. But whereas if I scroll the items and select its working fine. This problem occurring only on iOS device working perfectly fine on simulator.
the first picture depicts how drop down looks like, in second picture if I search 'ee', it gives list of items starting with 'ee'. If I select 'ee5', it sets to ee1 as shown in picture 3. Problem only on device. Any workaround for this?
So, please let me know whats the issue with this.
Thanks
[![enter image description here][1]][1]
private CustomList itemList;
class CustomList extends List {
int startYPos = -1;
long lastDiff = 0;
Timer t = null;
int draggingState = 0;
public CustomList() {
this.setTensileDragEnabled(false);
}
}
private class ButtonListener implements ActionListener {
public void actionPerformed(final ActionEvent evt) {
final Runnable rn = new Runnable() {
public void run() {
// Create and show a dialog to allow users to make a selection.
final UiBuilder uib = dm.UiBuilder();
dialog = (Dialog) uib.createContainer(DESIGNER_NAME_DIALOG_COMBOBOX_CONTAINER);
GenericSpinner itemSpinner = (GenericSpinner) uib.findByName(DESIGNER_NAME_DIALOG_COMBOBOX_GENERIC_SPINNER, dialog);
itemSpinner.setPreferredW(Display.getInstance().getDisplayWidth() * 4 / 5);
//remove from parent and replace with a linear list
Container parent = itemSpinner.getParent();
parent.removeComponent(itemSpinner);
// Add the searchable text field box
final TextField tf = (TextField)uib.findByName("Search", dialog);
tf.addDataChangedListener(new DataChangedListener() {
#Override
public void dataChanged(int type, int index) {
Object[] items = model.getFilteredItems(tf.getText());
itemList.setModel(new DefaultListModel(items));
}
});
itemList = new CustomList();
itemList.getAllStyles().setBgTransparency(0);
itemList.setItemGap(0);
parent.addComponent(BorderLayout.CENTER, itemList);
final String[] items = model.getItems();
itemList.setModel(new DefaultListModel(items));
itemList.getStyle().setMargin(10, 10, 10, 10);
itemList.setFireOnClick(true);
itemList.setLongPointerPressActionEnabled(false);
ActionListener list = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (model.isUserEditable() && model.getItemCount() > 0) {
int i = itemList.getSelectedIndex();
if (i > items.length - 1) {
return;
}
itemList.getModel().setSelectedIndex(i);
model.onUserDataEntered((String) itemList.getModel().getItemAt(i));
String textToDisplay = (String) itemList.getModel().getItemAt(i);
button.setText(textToDisplay);
}
dialog.dispose();
}
};
itemList.addActionListener(list);
CommonTransitions tran = CommonTransitions.createEmpty();
dialog.setTransitionInAnimator(tran);
dialog.setTransitionOutAnimator(tran);
itemList.setRenderer(new ListRenderer());
//related to dialog to show list of items
//how much space do we really need???
if (cellHeight == 0) {
int dip = Display.getInstance().convertToPixels(1);
int siz = 2;
if (Display.getInstance().isTablet()) {
siz = 4;
}
siz *= 2;
cellHeight = siz * dip;
}
int heightRequired = cellHeight * (items.length + 8);
//is this too much for the screen - we will use 3/4 of the screen height max
int availableHeight = Display.getInstance().getDisplayHeight() * 3;
availableHeight /= 4;
if (heightRequired > availableHeight) {
int topPos = Display.getInstance().getDisplayHeight() / 8;
int bottomPos = topPos + availableHeight;
dialog.show(topPos, topPos, 40, 40);
}
else {
int topPos = (Display.getInstance().getDisplayHeight() - heightRequired) / 2;
int bottomPos = topPos + heightRequired;
dialog.show(topPos, topPos, 40, 40);
}
}
};
}
}
//new code using Multibutton implementation
final String[] listItems = model.getItems();
Display.getInstance().callSerially(() ->{
multiButton= new MultiButton();
multiButton.setTextLine1(s);
dialog.add(multiButton);
multiButton.addActionListener(e -> Log.p("you picked " + multiButton.getSelectCommandText(), Log.ERROR));
}
dialog.revalidate();
});
I would recommend using a Container and simple layout search as demonstrated by code such as this. The code below was taken from the Toolbar javadoc:
Image duke = null;
try {
duke = Image.createImage("/duke.png");
} catch(IOException err) {
Log.e(err);
}
int fiveMM = Display.getInstance().convertToPixels(5);
final Image finalDuke = duke.scaledWidth(fiveMM);
Toolbar.setGlobalToolbar(true);
Form hi = new Form("Search", BoxLayout.y());
hi.add(new InfiniteProgress());
Display.getInstance().scheduleBackgroundTask(()-> {
// this will take a while...
Contact[] cnts = Display.getInstance().getAllContacts(true, true, true, true, false, false);
Display.getInstance().callSerially(() -> {
hi.removeAll();
for(Contact c : cnts) {
MultiButton m = new MultiButton();
m.setTextLine1(c.getDisplayName());
m.setTextLine2(c.getPrimaryPhoneNumber());
Image pic = c.getPhoto();
if(pic != null) {
m.setIcon(fill(pic, finalDuke.getWidth(), finalDuke.getHeight()));
} else {
m.setIcon(finalDuke);
}
hi.add(m);
}
hi.revalidate();
});
});
hi.getToolbar().addSearchCommand(e -> {
String text = (String)e.getSource();
if(text == null || text.length() == 0) {
// clear search
for(Component cmp : hi.getContentPane()) {
cmp.setHidden(false);
cmp.setVisible(true);
}
hi.getContentPane().animateLayout(150);
} else {
text = text.toLowerCase();
for(Component cmp : hi.getContentPane()) {
MultiButton mb = (MultiButton)cmp;
String line1 = mb.getTextLine1();
String line2 = mb.getTextLine2();
boolean show = line1 != null && line1.toLowerCase().indexOf(text) > -1 ||
line2 != null && line2.toLowerCase().indexOf(text) > -1;
mb.setHidden(!show);
mb.setVisible(show);
}
hi.getContentPane().animateLayout(150);
}
}, 4);
hi.show();
I'm making my first app in Unity to learn English words and I got stuck.
I created and array like that:
public string[] words = {
"apple",
"banana",
"big",
"blue",
"book",
"one",
"two"
};
I'm using PlayerPrefs to save which array element I'm learning at the moment.
The problem is that I can't add or remove elements from this array. Whatever I do it always shows these 7 elements.
Can you please tell me why?
The thing is I don't want to add elements dynamically or within the script. I just want to expand my array manually by adding more elements, like this:
public string[] words = {
"apple",
"banana",
"big",
"blue",
"book",
"one",
"two",
"colours",
"green",
"orange",
"pencil",
"yellow",
"four",
"five",
"six",
"small",
};
The thing is that after changing array from my first post to this one, change takes no effect. Program still sees only 7 elements.
I tried to delete some elements and the result is the same. It looks like the program holds my array in memory or something....
Here is my complete code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour {
public static GameManager instance;
public bool isLearnOn;
public bool isFrontMenuActive;
public GameObject frontMenuEmpty;
Animator frontMenu;
Animator finishPanel;
//Tasks Elements
Image taskImage;
GameObject taskImageEmpty;
GameObject taskAllElementsEmpty;
GameObject taskTextEmpty;
Text taskText;
InputField taskInputField;
AudioSource taskAudio;
int randomWord;
int wordCount;
int allWordsCount;
int collectPoint;
Text pointsBoard;
Text hint;
public bool isHintShown;
GameObject hintTextEmpty;
int innerTaskCount;
public bool isFinishPanelOn;
void Awake(){
if (instance == null) {
instance = this;
}
}
void Start () {
collectPoint = (PlayerPrefs.GetInt ("points"));
isLearnOn = false;
//Variable assignment
//Tasks Elements
taskAllElementsEmpty = GameObject.Find ("TaskAllElementsEmpty");
taskImage = GameObject.Find ("TaskImage").GetComponent <Image>();
taskTextEmpty = GameObject.Find ("TaskTextEmpty");
taskText = GameObject.Find ("TaskText").GetComponent <Text>();
taskInputField = GameObject.Find ("TaskInputField").GetComponent <InputField>();
taskAudio = GameObject.Find ("GameManager").GetComponent <AudioSource>();
pointsBoard = GameObject.Find ("PointsBoard").GetComponent <Text>();
hint = GameObject.Find ("Hint").GetComponent <Text>();
hintTextEmpty = GameObject.Find ("HintTextEmpty");
finishPanel = GameObject.Find ("FinishPanel").GetComponent <Animator>();
taskImageEmpty = GameObject.Find ("TaskImageEmpty");
frontMenuEmpty = GameObject.Find ("FrontMenuEmpty");
frontMenu = GameObject.Find ("FrontMenuEmpty").GetComponent <Animator>();
pointsBoard.text = collectPoint.ToString ();
allWordsCount = words.Length;
Debug.Log (allWordsCount);
isFrontMenuActive = false;
FrontMenuShowHide ();
taskAllElementsEmpty.SetActive (false);
isHintShown = false;
hint.text = "";
innerTaskCount = 0;
isFinishPanelOn = false;
//TODO Disable finisih panel
}
void Update () {
if (isLearnOn == true) {
if (wordCount < allWordsCount) {
if ((taskInputField.text == words [wordCount]) && innerTaskCount == 0) {
Task1 ();
taskText.text = "";
taskInputField.placeholder.GetComponent<Text>().text = "What is it?";
innerTaskCount = 1;
}
else if ((taskInputField.text == words [wordCount]) && innerTaskCount == 1) {
Task1 ();
taskText.text = "";
taskInputField.placeholder.GetComponent<Text>().text = "Listen and type the word down";
taskImageEmpty.SetActive (false);
innerTaskCount = 2;
}
else if ((taskInputField.text == words [wordCount]) && innerTaskCount == 2){
if (isHintShown == false) {
CollectPoints ();
NextTask ();
Debug.Log (wordCount);
innerTaskCount = 0;
} else {
NextTask ();
innerTaskCount = 0;
}
}
} else {
if(isFinishPanelOn == false){
HideFinishPanel ();
wordCount = 0;
}
}
} else {
if (taskInputField.text == words [randomWord]) {
if (isHintShown == false) {
CollectPoints ();
RandomTask ();
} else {
RandomTask ();
}
}
}
}
public void FrontMenuShowHide(){
if (isFrontMenuActive == true) {
frontMenu.Play ("FrontMenuOut");
isFrontMenuActive = false;
} else {
frontMenu.Play ("FrontMenu");
isFrontMenuActive = true;
}
}
public void Task1(){
isHintShown = false;
wordCount = (PlayerPrefs.GetInt ("wordCountPrefs"));
taskAllElementsEmpty.SetActive (true);
taskText.text = words[wordCount];
taskInputField.text = "";
taskInputField.ActivateInputField ();
//SoundPlay ();
LoadPicture ();
taskTextEmpty.SetActive (true);
hint.text = "";
taskInputField.placeholder.GetComponent<Text>().text = "Copy the word, please...";
string path = "audio/" + words [wordCount];
taskAudio.clip = (AudioClip)Resources.Load(path, typeof(AudioClip));
taskAudio.Play ();
taskImageEmpty.SetActive (true);
}
public void RandomTask(){
isHintShown = false;
randomWord = Random.Range (0, allWordsCount);
taskAllElementsEmpty.SetActive (true);
taskText.text = words[randomWord];
taskInputField.text = "";
taskInputField.ActivateInputField ();
//SoundPlay ();
LoadRandomPicture ();
taskTextEmpty.SetActive (false);
hint.text = "";
taskImageEmpty.SetActive (true);
taskInputField.placeholder.GetComponent<Text>().text = "What is it?";
string path = "audio/" + words [randomWord];
taskAudio.clip = (AudioClip)Resources.Load(path, typeof(AudioClip));
taskAudio.Play ();
}
public void SoundPlay(){
if (isLearnOn == true) {
string path = "audio/" + words [wordCount];
taskAudio.clip = (AudioClip)Resources.Load(path, typeof(AudioClip));
taskAudio.Play ();
} else {
string path = "audio/" + words [randomWord];
taskAudio.clip = (AudioClip)Resources.Load(path, typeof(AudioClip));
taskAudio.Play ();
}
}
public void LoadPicture(){
string path = "img/" + words [wordCount];
taskImage.sprite = (Sprite)Resources.Load(path, typeof(Sprite));
}
public void LoadRandomPicture(){
string path = "img/" + words [randomWord];
taskImage.sprite = (Sprite)Resources.Load(path, typeof(Sprite));
}
public void NextTask(){
wordCount++;
PlayerPrefs.SetInt ("wordCountPrefs", wordCount);
Task1 ();
}
public void LearnIsOn(){
isLearnOn = true;
}
public void LearnIsOff(){
isLearnOn = false;
}
public void CollectPoints(){
collectPoint++;
PlayerPrefs.SetInt ("points", collectPoint);
pointsBoard.text = collectPoint.ToString ();
}
public void ShowHint(){
if (isLearnOn == true ) {
if (innerTaskCount != 0){
hint.text = words [wordCount];
isHintShown = true;
}
} else {
hint.text = words [randomWord];
isHintShown = true;
}
}
public void HideFinishPanel(){
if (isFinishPanelOn == true) {
finishPanel.Play ("FinishPanelOut");
isFinishPanelOn = false;
} else {
finishPanel.Play ("FinishPanel");
isFinishPanelOn = true;
}
}
public string[] words = {
"apple",
"banana",
"big",
"blue",
"book",
"one",
"two",
"colours",
"green",
"orange",
"pencil",
"yellow",
"four",
"five",
"six",
"small",
};
}
`
This happens because Unity initialize serialized public objects itself. When you define your variable first time in script if you initialized it manually, Unity serialize it with your values. Else Unity serialize it with default values.
For example. When you create the script below first time like;
public class GameManager : MonoBehaviour {
public string[] words = {
"one",
"two",
"three",
"four",
"five",
"six",
};
}
Unity serialize words with this values. After that even if you change initial values from script, next time you run, it actually doesn't change.
For this, there are two options. First; define your variable in script with [System.NonSerialized] attribute.
[System.NonSerialized] public string[] words = {};
Second choice, select the gameobject from hierarchy. On inspector, chose your scripts component and Reset it when you change initial variables.
You need to use list in place of array. List allows you to add or delete any item.
List <string> names = new List<string>();
Void Start()
{
names.Add(“apple”);
}
If you want to be able to do both, adding elements in the editor and by script you should rather use a List<string> words and check if the value already exists in the list before adding it in the script:
[SerializeField]
private List<string> words = new List<string>();
private void Start(){
if(!words.Contains("apple")){
words.Add("apple")
}
if(!words.Contains("banana")){
words.Add("banana")
}
}
Independent from that, if you want to update the List/Array also within the Editor I recomend you use the [ContextMenu] tag:
e.g. for your array:
public string[] words; // you don't set it here but expect it to be set in the editor
[ContextMenu("Import scripted array")]
private void ImportScriptedArray(){
// Note in this case I simply overwrite any setting within the editor
// There are multiple ways to prevent this like before using List or other methods
words = new [] {
"bla",
"bli",
"blub"
};
}
This adds the method ImportScriptedArray to the context menu of this component in the editor. So first you have this unset array:
On your script/component you now can click on the settings icon to open the context menu.
And in the context menu click on your just generated Import Scripted Array to import your array from the script.
i have one method in class call Class1 like
' public void getEventFromUser() {
int event;
Scanner input = new Scanner(System.in);
date.getDateFromUser();
// od.inputday();
// od.inputyear();
time.getTimeFromUser();
System.out.println("Enter description :");
description = input.nextLine();
}'
and i want to execute this method and store in array in another class
like
public void addEvent() {
if (numEvent == maxEvent) {
System.out.println("error…no more room to add events");
} else {
schedule[numEvent]=getEventFromUser();
int count = 0;
while (count < numEvent - 1) {
if (schedule[numEvent].isEqual(schedule[count])) {
isFound = true;
break;
}
count++;
if (isFound == true) {
System.out.println("Event already exists-notadding");
schedule[numEvent] = null;
} else {
schedule[numEvent].setDate();
schedule[numEvent].setTime();
schedule[numEvent].setDescription();
numEvent++;
//schedule[numEvent]=schedule[numEvent].getEventFromUser();
}
}
}
} '
so,how can i do this?
pls give me some solution
getEventFromUser() doesn't return a value, which is why schedule[numEvent]=schedule[numEvent].getEventFromUser() is giving you trouble.
Without knowing a bit more about what you're trying to do, it's hard to say if you should have getEventFromUser() return a value or have getEventFromUser() directly store a value in a field in the class. (I'm guessing the setDate, setTime and setDescription methods do this.)