How to setText of JTextfield to a method with an array - java

I have a class called ShoutBox, and there it has this array and this method:
String messages[] = new String[10];
//declare 10 arrays
messages[0] = "Miley";
messages[1] = "Katy";
messages[2] = "Gaga";
messages[3] = "Beyonce";
messages[4] = "Taylor";
messages[5] = "Missy";
messages[6] = "Nicki";
messages[7] = "Adele";
messages[8] = "Rihanna";
messages[9] = "Selena";
String x = new ShoutBox().shoutOutCannedMessage(messages);
System.out.println(x);
public String shoutOutCannedMessage(String[] messages) {
for (int i = 0; i < messages.length; i++) {
System.out.println(i+". "+messages[i]);
}
System.out.print("Select a message: ");
int n = scan.nextInt();
String message = messages[n];
return message;
}
And then I have a another class for GUI, how to I make that result appear in a JTextField when an action is perform?
private void shoutOutMessageActionPerformed(java.awt.event.ActionEvent evt) {
JTextArea.setText(????);
}
Thanks!

Assuming that you want to show the next phrase in the array in response to an event and not show all phrases all at once:
Give your class an int index counter field, such as private int shoutIndex and initialize it to 0.
On any pertinent event (such as in an ActionListener), increment that index, e.g., shoutIndex++
Then make sure that the index is not larger than the length of the array using the remainder operator: shoutIndex %= messages.length
Then get the corresponding item from the array using the index, messages[shoutIndex], and use it to set the text of the JTextField.

Related

Adding more variables to an array of objects in java

I've made a bit of a mess on a project of mine. I have to create an array of objects. I have made an array but it only has 1 field 'myMonths' referring to the length of time of the project.
In my main method:
case 1:
int n = 1; //int n = number of projects
Scanner sc = new Scanner(System.in);
//myMonths = new int[amount];
System.out.println("** Only projects with a duration between 2 and 12 months can be included **");
System.out.println("What was the duration of your projects in months?");
for(int i=0; i<1; i++){
int a = sc.nextInt();
//display error message
if((a < 2) || (a > 12)){
System.out.println(" Please enter an amount between 2 and 12 months. ");
}
//add to the array
else{
myMonths[index++] = a;
}
}
calc.setMyMonths(myMonths); //creating the object
break;
In my class on separate file:
public class MenuTestClass{
private int myMonths[];
private double average; //store average value of numbers
private boolean averageCanBeCalculated;
private int max; // store max number from array. to be calculated
public MenuTestClass(){
myMonths = new int[5];
}
public MenuTestClass(int[] myMonths){
this.myMonths = myMonths;
}
public void setMyMonths(int[] values){ //declare setter method
myMonths = values;
}
I should have added in two more fields, both strings. Is there a way I can add more fields/attributes to this array and have them viewable at the same time under 1 index? For example at [0] projectName, projectManager, myMonths ie(string, string, integer).
Any advice would be great, I am getting really confused with OOP. Thanks in advance!
Yes, create a class containing your three properties:
class MyContainer {
public MyContainer(int durationMonths, String projectName, String projectManager) {
this.durationMonths = durationMonths;
this.projectName = projectName;
this.projetManager = projectManager;
}
public int durationMonths;
public String projectName;
public String projectManager;
}
Then create an array of this class with:
MyContainer[] myArray = new MyContainer[numberOfProjects];
Add items to the array like this:
myArray[0] = new MyContainer(3, "super project", "awesome manager");

Java - How can I print out a value as a word after BubbleSorting?

I used integer so that I can write out Numbers as an input, but now i would like the programm to output the number as Words again.
public class KartenSort {
private int zwei = 2;
private int drei = 3;
private int vier = 4;
private int fuenf = 5;
public int[] liste ={drei,zwei,fuenf,vier};
public int[] sortieren(){
int unsortiert;
for(int sortiert = 0; sortiert < liste.length -1; sortiert++){
if(liste[sortiert] < liste[sortiert+1]){
continue;
}
unsortiert = liste[sortiert];
liste[sortiert] = liste[sortiert+1];
liste[sortiert+1] = unsortiert;
sortieren();
}
return liste;
}
public static void main (String[] args){
KartenSort bs = new KartenSort();
int[] array = bs.sortieren();
for (int sortiert=0;sortiert < array.length; sortiert++){
System.out.println(sortiert + 1 +":" + array[sortiert]);
}
}
}
thank you in advance
In your case you could use Map
Map<Integer,String> numbers = new HashMap<>();
numbers.put(2, "zwei");
numbers.put(3, "drei");
numbers.put(4, "vier");
numbers.put(5, "funf");
for (int sortiert=0;sortiert < array.length; sortiert++){
System.out.println(numbers.get(array[sorted]));
}
The array liste does not contain Strings (what you probably mean by "words").
I think, you wanted to have something like
String[] liste = ...
Your version of liste is
int[] liste = ...
This means it contains integer numbers, not strings. Although you write
int[] liste = {drei,zwei, ...}
the content of the array are still integer numbers. drei is a variable and you will get the value of the variable into the list. The value of drei is the integer value 1.
When you have the value 1 there is no reference back to the name of the variable that had hold it some time ago.

How to creart an ArrayList from array?

I am trying to create an ArrayList from a given array. This is the array I have:
public class Warehouse
{
private final static int MAX = 60;
private Item [] stock;
private int numItems;
public Warehouse()
{
stock = new Item[MAX];
numItems = loadData();
}
Now where should I change the processing from an array to an arraylist? Is this supposed to be done in the constructor or somewhere else? Thanks.
Why not use this?
List<Item> stockList = Arrays.asList(stock);
Just keep a separate class for the array and within the class that you want to get that specific array you can create an ArrayList Object.
public class ArrayaData {
public int Id;}
And the within the next class,
public class ClassYouWant {
ArrayList<ArrayaData> arrayList ;
}
and when ever you want to add a value to that array just create a new instance and then save it.
arrayList = new ArrayList<ArrayaData>();
arrayList.Id = "Value you want.."
arrayList = new ArrayList<ArrayaData>();
arrayList.Id = "Value 2 you want.."
Or you can simply set it in a Loop as well,
int arraySize = 5; //Size of the array you want
for (int i = 0; i < arraySize; i++) {
arrayList = new ArrayList<ArrayData>();
arrayList.Id = "Value you want";
}
And to get the vlaues you can use a Loop also,
int arraySize = arrayList.size(); //Size of the created arrayList
int value;
for (int i = 0; i < arraySize; i++) {
value = arrayList.get(i);
Toast.makeText(this, "Value " + i + ":" + value, Toast.LENGTH_SHORT).show();
}
Hope this helps..

array index out of bound for append array result into java text area

I have two program which are SocketServer and MyNoteCenter. Every time the user click the download button,it will send to the SocketServer for storing. The user can retrieve their record by click the show button to show the record. After that, append to the text area but unfortunately I get an ArrayOutOfBound error for my code. The errors show me that the display method in MyNoteCenter and show method in SocketServer method. I had search a lot of solution on my problem but it still look the same and I checked the array index was enough to hold 5 data. The 5 data will bring to the SocketServer by using the parameter constructor when certain function being invoke at MyNoteCenter
MyNoteCenter program(portion)
if(e.getSource()==btn3)
{
String [] ds = new String[5];
ds = display();
for(int i = 0; i <=ds.length;i++)
{
ta1.append("Result"+i+":"+ds[i]);
}
}
public String[] display()
{
SocketServer ds = new SocketServer();
String [] STRarr = new String[5];
STRarr[5] = ds.show();
return STRarr;
}
SocketServer program(portion)
public SocketServer(String selection,String id,String name,String year,String major) //The constructor accept the value from user and store it, it's being implement at others function
{
this.selection = selection;
this.name = name;
this.id = id ;
this.year = year ;
this.major = major ;
}
public String show()
{
String [] arr = new String[5];
arr[0] = name;
arr[1] = id;
arr[2] = year;
arr[3] = major;
arr[4] = selection;
counter++;
JOptionPane.showMessageDialog(null,"You are in" +counter);
return arr[5];
}
for(int i = 0; i <=ds.length;i++)
The standard looping construct is to NOT use the "=" in the looping condition since indexes in Java are 0 based. The code should be:
for(int i = 0; i < ds.length; i++)
Don't be afraid to use white space when coding. It is easier to spot the test condition when it is separated by spaces.
Edit:
return arr[5];
You can't hardcode 5. The only valid indexes are 0, 1, 2, 3, 4.
Why are you creating an Array with 5 values and then only returning a single String? The other 4 values will be lost.
Maybe you need to return the entire array:
public String[] show()
...
return arr;

getting a length of a string from a variable array java

Im a student learning Java and this is part of my program and it is supposed to get the length of a string but the strings are all in an array. I try to run this in eclipse and it says i get an error where it sayslength = name[x].length() can someone let me know if there is a way to fix this
public class GuessName
{
Random random = new Random();
Scanner scan = new Scanner(System.in);
String[] name = new String[10];
int x,length;
char guess1,guess2,guess3;
public void names()
{
name[0] = "MARK";
name[1] = "CHARLIE";
name[2] = "MEG";
name[3] = "KYLE";
name[4] = "JUSTIN";
name[5] = "KATARINA";
name[6] = "JOEL";
name[7] = "KEVIN";
name[8] = "MICHAEL";
name[9] = "JENNA";
name[10] = "GREG";
}
public void start()
{
x = random.nextInt(10);
length = name[x].length();
}
You have an array, as follows:
String[] name = new String[10];
The number between the [] represents the size of the array. In your example, your array has a size of 10 meaning your array has 10 indexes which are [0,9] (because indexes start at 0). The last line of your names() method is:
name[10] = "GREG";
Do you know where I'm getting at?
Also, what does your main method look like? If you're receiving a NullPointerException it probably means you are calling start() before names().
I commented out the parts that was problematic. Also, you are trying to initialize 11 names as opposed to 10. Please note that arrays index starts at 0. I don't know why you have scanner object in there but you can use this block to complete your code.
import java.util.Random;
import java.util.Scanner;
public class GuessName {
// Scanner scan = new Scanner(System.in);
String[] name = new String[10];
int x,length;
char guess1,guess2,guess3;
public GuessName()
{
name[0] = "MARK";
name[1] = "CHARLIE";
name[2] = "MEG";
name[3] = "KYLE";
name[4] = "JUSTIN";
name[5] = "KATARINA";
name[6] = "JOEL";
name[7] = "KEVIN";
name[8] = "MICHAEL";
name[9] = "JENNA";
// name[10] = "GREG";
}
public void start()
{
Random random = new Random();
this.x = random.nextInt(10);
this.length = name[this.x].length();
}
public static void main(String[] args) {
GuessName gn = new GuessName();
gn.start();
System.out.println("The name is: "+gn.name[gn.x]+" and the length is: "+ gn.x);
} }

Categories