Array output in a box - java

I am learning Java and I would like to know how you can print an array in a pop-up Box using JOptionPane?
I don't mean printing them in separate boxes for each element of the array but printing the whole array content in a single box with JOptionPane.showMessageDialog, after having input the values one by one by JOptionPane.showInputDialog.
Example:
Write a program that inputs 5 Integers (or strings) and store them in an array. It then print the array in a pop-up box at the end, with all the variable values.
Basically, this is how I'd start:
int numberBox[] = new int[5];
for (int i = i; i<numberBox.lenght; i++)
{
String text = JOptionPane.showMessageDialog (null, "Give me numbers:");
numberBox[i] = Integer.parseInt (text);
}
Actually, the code I have written I am sure it has mistakes. Then again, that is why I need your help.

Once you have gathered input and built an array of ints or Strings, here's how you can print them in a dialog box:
// Get the input; this could be an array of ints or strings, either will work
int numberBox[] = gatherInput();
// Convert the array into a String form: "[1, 2, 3, 4, 5]"
final String numbers = Arrays.toString( numberBox );
// And show a simple dialog box with the numbers
JOptionPane.showMessageDialog( null, numbers );
For gathering user input: Getting the User's Input from a Dialog

You need to build a string that contains entered numbers separated by delimiter. To build a String take a look at StringBuilder. This class is mutable, it means that new object won't be created every time you add something to the string. To compare with, String is immutable and not efficient if you're going to concatenate several elements.
It's also possible to use Arrays Java class, but I would recommend to look at StringBuilder also to extend your knowledge.

you could try something like this
int[] array = {1,2,3,4,5};
String end = "";
for(int i = 0; i < array.length; i++){
end += array[i] + " ";
}
JOptionPane.showMessageDialog(new JFrame(), end);

Related

Printing user input in array says null

I am trying to print user input from an array to display in java. When i run this, it just prints out "null" for each amount no matter what the user inputs. I am a beginner at java and want to learn more about arrays, and I can't seem to figure this out.
String itemAmount = ss.getInputString("How many items?");
int amount = Integer.parseInt(itemAmount);
String[] Items = new String[amount];
for (int i = 0; i < Items.length; i++) {
ss.getInputString("Please enter items?");
}
for (int i = 0; i < Items.length; i++) {
ss.println((Items[i]));
}
Also, how would i be able to print the items, for example user inputs 3 items -> "Eggs", "Bacon", "Tomato" how would I print this to show in a line separated by commas.
I'm not sure what gt is, but since you're using it this way
String itemAmount = gt.getInputString("How many items?");
I guess it's some sort of wrapper around the standard input.
You can use it the same way to populate an array, one item at a time.
for (int i = 0; i < Items.length; i++) {
Item[i] = gt.getInputString("Please enter items?");
}
You seem to be able to use the array in the other loop, so I'll assume you don't need further explanation.
Then to print them on a single line, separated by a comma you can use the join method of String (note: you need to convert your array to a List, first)
String joinedString = String.join(", ", Arrays.asList(Items));
I think you are checking the length of wrong array/string in second for loop. It should be Items.length not Appliances.length

Read an element of an array whilst containing various data

I am currently seeking for a bit of help with the use of arrays. Quite a newbie on the Java language, so excuse the poor etiquette towards the programming format and I forwardly thank for any answers provided.
My current quarrel with the Array is how to fetch data from any array element. Currently I use the method System.out.println(Arrays.toString(listarray)) but the problem with this method is that it's not necessarily User friendly and it can't be formatted (to my little knowledge). So I'd like to ask help on how to fetch data from an element of an array and put it in a way so its readable by any given user.
Here is the code I'm utilizing:
import java.util.Arrays;
import java.util.Scanner;
public class principal {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Array Example");
String[] listarray = new String[10];
int i = 0;
byte op;
do {
System.out.println("Select your option:");
System.out.println("1-Add");
System.out.println("2-Check");
System.out.println("3-Change");
op = input.nextByte();
switch (op) {
case 1:
input.nextLine();
System.out.println("First String:");
String a1 = input.nextLine();
System.out.println("Second String:");
String a2 = input.nextLine();
System.out.println("Third String:");
String a3 = input.nextLine();
System.out.println("(" + (i + 1) + "/10)");
listarray[i] = a1 + a2 + a3;
i++;
break;
case 2:
System.out.println(Arrays.toString(listarray));
break;
}
}while(op != 9);
}
}
While the code does work, I'd like to know how to format the data, and from a single element, not every element. Or even if I can. Thanks and I appreciate the time spent reading this question.
You have two questions:
How do you reference an array element?
How do you format output?
When you declare an array like
String[10] names;
You have an array that can hold 10 strings, numbered 0 to 9. To reference the fifth element (remembering that array indices start at 0), you would use
names[4]
You can do various things with a reference. If you put it on the right side of an equals sign, then you are assigning the value at that element to something else.
currentName = names[4];
If you put it on the left side, you are assigning something to that element.
names[4] = "Michael";
And if you put it in a println statement, it will output the value to wherever the println statement is putting things at that time, usually the console:
System.out.println(names[4]);
So much for references. And, incidentally, that's what it is called -- you are referencing the 5th element of the array, or you are referencing the indicated element of the array. You can also put the number in a variable:
var i = 4;
System.out.println[i];
Note that most of these uses of the reference assume there is something IN that element of the array. Until something is assigned there, the element is a null.
To format, I recommend looking (carefully) into the Format / Formatter classes and choosing some simple things to do what you want. As an example, you could have:
String formatString = "The name is currently %s.";
String outputString = String.format(formatString, names[i]);
and String's format method will substitute whatever is in names[i] for the %s in the format. There are also formats for ints, doubles, and dates.
For more info, see the Oracle Tutorial on arrays and on manipulating Strings.
Hope that helps
If you want to traverse the Array that is how you can do it:-
for(int i = 0; i < listArray.length; i++) {
System.out.println(listArray[i]);
}
or
for (String s : listArray) {
System.out.println(s);
}

convert String to arraylist of integers using wrapper class

Im trying to write a program that takes a string of user inputs such as (5,6,7,8) and converts it to an arrayList of integers e.g. {5,6,7,8}. I'm having trouble figuring out my for loop. Any help would be awesome.
String userString = "";
ArrayList<Integer> userInts = new ArrayList<Integer>();
System.out.println("Enter integers seperated by commas.");
userString = in.nextLine();
for (int i = 0; i < userString.length(); i++) {
userInts.add(new Integer(in.nextInt()));
}
If your list consists of single-digit numbers, your approach could work, except you need to figure out how many digits there are in the string before allocating the result array.
If you are looking to process numbers with multiple digits, use String.split on the comma first. This would tell you how many numbers you need to allocate. After than go through the array of strings, and parse each number using Integer.parseInt method.
Note: I am intentionally not showing any code so that you wouldn't miss any fun coding this independently. It looks like you've got enough knowledge to complete this assignment by reading through the documentation.
Lets look at the lines:
String userString = ""
int[] userInt = new int[userString.length()];
At this point in time userString.length() = 0 since it doesnt contain anything so this is the same as writing int[] userInt = new int[0] your instantiating an array that cant hold anything.
Also this is an array not an arrayList. An arrayList would look like
ArrayList<Integer> myList = new ArrayList()<Integer>;
I'm assuming the in is for a Scanner.
I don't see a condition to stop. I'll assume you want to keep doing this as long as you are happy.
List<Integer> arr = new ArrayList<Integer>();
while(in.hasNext())
arr.add(in.nextInt());
And, say you know that you will get 10 numbers..
int count = 10;
while(count-- > 0)
arr.add(in.nextInt());
Might I suggest a different input format? The first line of input will consist of an integer N. The next line contains N space separated integers.
5
3 20 602 3 1
The code for accepting this input in trivial, and you can use java.util.Scanner#nextInt() method to ensure you only read valid integer values.
This approach has the added benefit of validate the input as it is entered, rather than accepting a String and having to validate and parse it. The String approach presents so many edge cases which need to be handled.

Creating Method of Arrays Using Scanner in Java

I'd like to create a method where it can print out an array created by user's input in Scanner.
The data type of the array is double.
So far, I have created an array of the size that the user has provided, but how do I enter all the double input elements into an array then print it out in a method?
Do I need to ask the user to give each number one by one? I would like to avoid this. Thanks
If I understand what you are asking, you don't want hundreds of alert messages asking the user for input, correct? Just ask once?
If that is the case, you can ask the user to separate the input with some symbol. For example a semi-colon. Then the user can input something like this:
1;2;3;4;5
Then what you do is split the input to get the array, and you print it out using a for loop and a printing method of your choice (e.g. system.out or show in an alert message)
Hope that solves your problem
You could grab user input from the console, and have them separate entries with spaces... ie:
Enter your series separated by spaces:
123.33 333.44 342.22 43.33
Storing this result to a String and then passing it to this method.
public double[] setDoubleArray(String input, int arraySize) {
double[] doubleArray = new double[arraySize];
Scanner s = new Scanner(input);
for (int i = 0; s.hasNextDouble(); i++) {
doubleArray[i] = s.nextDouble();
}
s.close();
return doubleArray;
}
Is this what your looking for?

How to display an array to the user

I'm trying to display the contents of an ordered array in something like a JTextField.
for (int i=0; i<array.length; i++) {
this.textField.setText(array[i]);
}
This won't work for two reasons. The first minor reason: if the array length is 4 then jtextfield is getting it's value reset 4 times rather than appending each element onto the last.
Second reason: The JTextField only takes strings. I can't find anything I can use in Swing that will let me display integers to the user. Any help?
Quick & Dirty Answer
for (int i=0; i<array.length; i++) {
this.myJTextField.setText(this.myJTextField.getText() + ", " + array[i]);
}
Correct Way
First, calling a member variable JTextField probably isn't wise. Since the class is already called like that, it will confuse readers. Naming conventions in Java state member variables are like myTextField for example. (note: original question changed).
User defined format
Note you can convert any number to a string by simply doing "" + number too. If you have many strings, consider using a string builder, as that's faster and won't update the GUI element multiple times: (also fixes the initial ", " before the first item, which happens above)
StringBuilder builder = new StringBuilder();
for (int i=0; i<array.length; i++) {
builder.append(array[i]));
if(i + 1 != array.length)
builder.append(", ");
}
this.myJTextField.setText(builder.toString());
Canonical array representation
Alternatively, you can use this:
this.myJTextField.setText(Arrays.toString(array));
It will look like [1, 4, 5, 6].
You can concatenate all those integers into a string the then present that value in the textfield.
StringBuilder sb = new StringBuilder();
for( int i : array ) { // <-- alternative way to iterate the array
sb.append( i );
sb.append( ", " );
}
sb.delete(sb.length()-2, sb.length()-1); // trim the extra ","
textField.setText( sb.toString() );
You can use a JTextArea instead of the textfield too.

Categories

Resources