Print string array
Hi
for printing numbers, I would do this:
for (int x=0; x<=myArray; x++)
System.out.prin(x);
But How would I do for printing String values I have read in to a string array?
I have read in som names to a string array and can print them by:
System.out.print(myarray[0] + myArray[2]);
This would print index 0 and 2 in the array. But this is not so good if you have an index large as 100 for example. So how would i go thru the String array and print out the variables?
Martin
dream77 wrote:
case 2: // Print out the list
for (int x=0;x<arrNames.length; x++)
if (x < nameCount)
System.out.print(arrNames[x]);
1) ALWAYS enclose for loop and if statements in curly braces, even if it's only one statement. So don't do either of these:
if (fubar ==3)
doThis();
// and
for (int snafu = 0; snafu < myLength; snafu++)
doThat();instead write:
if (fubar ==3)
doThis();
// and
for (int snafu = 0; snafu < myLength; snafu++)
doThat();
}You'll thank me for this later.
2) If nameCount is less than arrNames.length always, why use this as the exit condition in your for loop? i.e.,
for (int x = 0; x < nameCount; x++)
System.out.print(arrNames[x]);
}
Similar Messages
-
Problems with string array, please help!
I have a String array floor[][], it has 20 rows and columns
After I do some statement to modify it, I print this array
out in JTextArea, why the output be like this?
null* null....
null null...
null null...
How to correct it?a turtle graphics applet:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TG extends JApplet implements ActionListener {
private int x, y;
private int pendown, command, movement;
String direction, output, temp;
JLabel l1;
JTextField tf1;
JTextArea ta1;
String floor[][] = new String[20][20];;
public void init()
x = 0;
y = 0;
pendown = 0;
direction = "r";
Container c = getContentPane();
c.setLayout( new FlowLayout() );
l1 = new JLabel( "Please type a command:" );
c.add( l1 );
tf1 = new JTextField(20);
tf1.addActionListener( this );
c.add( tf1 );
ta1 = new JTextArea(20,20);
ta1.setEditable( false );
c.add( ta1 );
public void actionPerformed( ActionEvent e )
temp = tf1.getText();
if( temp.length() > 1)
command = Integer.parseInt(temp.substring(0,1));
movement = Integer.parseInt(temp.substring(2,temp.length()));
else
command = Integer.parseInt(temp);
switch(command)
case 1:
pendown=0;
break;
case 2:
pendown=1;
break;
case 3:
direct("r");
break;
case 4:
direct("l");
break;
case 5:
move(movement);
break;
case 6:
print();
break;
public void direct(String s)
if(direction == "r" && s =="r")
direction = "d";
else if(direction == "r" && s =="l")
direction = "u";
else if(direction == "l" && s =="r")
direction = "u";
else if(direction == "l" && s =="l")
direction = "d";
else if(direction == "u" && s =="r")
direction = "r";
else if(direction == "u" && s =="l")
direction = "l";
else if(direction == "d" && s =="r")
direction = "l";
else if(direction == "d" && s =="l")
direction = "r";
public void move(int movement)
if(pendown == 1)
if(direction == "u")
for(int b=0;b<movement;b++)
floor[x][y+b] = "*";
else if(direction == "d")
for(int b=0;b<movement;b++)
floor[x][y-b] = "*";
else if(direction == "l")
for(int b=0;b<movement;b++)
floor[x-b][y] = "*";
else if(direction == "r")
for(int b=0;b<movement;b++)
floor[x+b][y] = "*";
else if(pendown == 0)
if(direction == "u")
for(int b=0;b<movement;b++)
floor[x][y+b] = "-";
else if(direction == "d")
for(int b=0;b<movement;b++)
floor[x][y-b] = "-";
else if(direction == "l")
for(int b=0;b<movement;b++)
floor[x-b][y] = "-";
else if(direction == "r")
for(int b=0;b<movement;b++)
floor[x+b][y] = "-";
public void print()
for(int row=0;row<20;row++)
for( int column=0;column<20;column++)
output += floor[row][column];
if(column == 19)
output+="\n";
ta1.setText(output);
} -
Remove null values from string array
Hi ,
I have a string array in a jsp page which I save some values inside. After I store the values I want to print only those who are not null. How can I do this? Is there a way to delete the null values?Thank you but because I am new in programming what do you mean to use continue. Can you explain it a little bit further?<%
//go through the array to check all the values
for(int i=0; i<array.length();i++) {
//If array is null, nothing happen
if(array==null){
//leave here blank; instead use continue like:
//this will skip the statements next to it, and increments the value of i in for loop and continues to execute the body of for loop.
//The same will be repeated till the last iteration.
continue;
//If array not null, then print value in a new line
else{
out.print(array+"<br>"); //don't change the logic here
%> -
How to Display string array in jsp page using netui-data:repeater tag ??
hi,
I am trying to display a string array in a table using the netui-data:repeater tag.
I have to use a page flow controller Array(1 Dimensional) to be displayed in the jsp.
Can any one tell me how to print the array in a table of 3rows & 5 columns.
Here is the code on which I am crrently working on.
<netui-data:repeater dataSource="{pageFlow.strWorkObject_Array}">
<netui-data:repeaterHeader>
<table cellpadding="4" border="1" class="tablebody">
</netui-data:repeaterHeader>
<netui-data:repeaterItem>
<tr>
<td><netui:label value="{container.item}" >
</netui:label></td>
<td><netui:label value="{container.item}">
</netui:label></td>
<td><netui:label value="{container.item}">
</netui:label></td>
</tr>
</netui-data:repeaterItem>
<netui-data:repeaterFooter>
</table>
</netui-data:repeaterFooter>
</netui-data:repeater>weblogic.developer.interest.workshop
Mansoor Naseem wrote:
I would like to know where the pageflow newsgroup is.
These are all the groups in weblogic.developer.interest:
weblogic.developer.interest.60beta.* (5 groups) weblogic.developer.interest.management
weblogic.developer.interest.61beta.* (2 groups) weblogic.developer.interest.misc
weblogic.developer.interest.clustering.* (1 group) weblogic.developer.interest.performance
weblogic.developer.interest.commerce weblogic.developer.interest.personalization
weblogic.developer.interest.ejb.* (3 groups) weblogic.developer.interest.portal
weblogic.developer.interest.environment weblogic.developer.interest.rmi-iiop
weblogic.developer.interest.jdbc weblogic.developer.interest.security
weblogic.developer.interest.jms weblogic.developer.interest.servlet
weblogic.developer.interest.jndi weblogic.developer.interest.tools
weblogic.developer.interest.jsp weblogic.developer.interest.weblogicenterprise
MN -
Number of repeated characters in string array
Hi,
I m trying to get number of repeated characters in string array. I couldnt figure out where am i doing mistake.
thank you,
For example: count({"alpha, beta,"}, 'a')
a is repeated 3
l is repeated 1 etc.
public class Test
public static int count(String[] stringArray, char c)
public String [] str = new String [2];
int count = 0;
str[0]
str[1]
for(int i = 0; i<str.length(); i++)
if (str.charAt(i)
count++;
return count;There is a difference between a String and a String [].
A String [] is an array of String class objects:/* Traverse_Array_Of_Strings_1.java */
public class Traverse_Array_Of_Strings_1
public static void main(String [] argv)
/* here is an array of Strings */
String [] s = { "hello", "how", "are", "you" };
int i, j;
System.out.println("s.length = "+ s.length );
for (i= 0; i < s.length; i++)
System.out.println("s= <"+ s[i] +">");
for (j= 0; j < s.length(); j++)
System.out.print(s[i].charAt(j) +", ");
System.out.println("\n-----");
}output:java> javac Traverse_Array_Of_Strings_1.java
java> java Traverse_Array_Of_Strings_1
s.length = 4
s= <hello>
h, e, l, l, o,
s= <how>
h, o, w,
s= <are>
a, r, e,
s= <you>
y, o, u,
Edited by: vim_no1 on Jul 15, 2010 7:43 AM -
Combining string array elements into one string
Right, I have an string array called str which stores 1 character in each of its 16 elements. It gets this character from another array, strArray. Now, what I want to be able to do is to take all 16 elements and combine them into one string called keyString. Using the code below keyString only prints out the last character. The code is shown below:
for (x=0; x<16; x++) {
str = new String[16];
str[x] = "";
str[x] += (strArray[(index+x)%16].charAt(strChar[x]));
keyString = str[x];
System.out.print(keyString);
}Any help would be very much appreciated.
Edited by: Paragon96 on May 20, 2008 7:32 AMyour logic is wrong ; if you want to concatenate the content of the array, you have to loop (what you did), and concatenate keyString for each index, meaning:
keyString += str[x];you can also use a StringBuilder for such kind of operations -
Searching two dimensional string arrays
Hello, I'm very new to Java. I would like some advice on the code below. What I'm trying to do is: I want the user to enter a 9 digit number which is already stored in an two dimensional array. The array is to be searched and the 9 digit number and corresponding name is to be printed and stored for future reference. Something is wrong with my array checking. If I enter the nine digit number, the program errors and asks me again for the number. If I enter 0-4, I receive an output. I just don't know how to compare string array values. Could someone please help me with this?
import java.io.*;
import java.util.*;
public class SocialSn2
public static void main(String args[]) throws Exception
boolean validSSAN = false;
Ssn(validSSAN);
if (validSSAN)
//Ssn(false);//write the code here to continue processing
}//end main
public static void Ssn(boolean Validated)
String[][] employees =
{{"333333333", "Jeff"},
{"222222222", "Keith"},
{"444444444", "Sally"},
{"555555555", "Kaylen"},
{"111111111", "Sheriden"} };
boolean found = false;
while (!found)
System.out.println("Enter the employee's Social Security number.");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try
String line = in.readLine();
int input = Integer.parseInt(line); //added
found = false;
for(int j = 0; j < 5; j++)
if(input >= 0 && input <= employees.length)
//if(employees[j][0].equals(input))
//System.out.println(employees[input][0] + employees[input][1]);
found = true;
System.out.println(employees[input][0] + " " + employees[input][1]);
catch (Exception exc)
System.out.println("error");
found = false;
Validated = found;
}//end Ssn
}//end classThere seems to be some problem with your loop for checking those values
if you had used System.err.println() in your catch block you would see that you were getting an ArrayIndexOutOfBoundsException
The following works for me.
import java.io.*;
import java.util.*;
public class SocialSn2
public static void main(String args[]) throws Exception
boolean validSSAN = false;
Ssn(validSSAN);
if (validSSAN)
//Ssn(false);//write the code here to continue processing
}//end main
public static void Ssn(boolean Validated)
String[][] employees =
{{"333333333", "Jeff"},
{"222222222", "Keith"},
{"444444444", "Sally"},
{"555555555", "Kaylen"},
{"111111111", "Sheriden"} };
boolean found = false;
System.out.println(employees.length);
System.out.println(employees[0].length);
while (!found)
System.out.println("Enter the employee's Social Security number.");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try
String line = in.readLine();
//int input = Integer.parseInt(line); //added
found = false;
for (int i=0; i< employees.length;i++)
if(employees[0].equals(line))
System.out.println(employees[i][0]+" "+employees[i][1]);
found = true;
catch (Exception exc)
System.err.println(exc);
found = false;
Validated = found;
}//end Ssn
}//end class -
How to print an array out a while loop?
Hi all,
I'm very new with Labview (6h of Practice) and I meet a problem.
I create a while loop in which a read the first characters of each line of three files and put it in an 2D array (3 rows and 50 lines).
My goal is to print this array on the VI's panel in a Table or in a Multicolon Listbox. How to do this? In the While loop or out?
I use Labview 6i.
Thanks for your helpHi,
I don't see any problems. I suppose that you can get a 2D array of strings from files.
Now there are three solutions.
1. Use of Arrays.
Right-click on the wire with your 2D array and select "Create->Indicator" from pop-up menu. Now you have a 2D array on the front panel which will show you your data.
2. Use of Tables.
Select table control from "Controls->List&Tables". Paste it on the front panel of your vi. Right-click on it and select "Change to indicator" from pop-up menu. Then wire this indicato to your 2D array in the block diagram.
3. Use of Multicolumn listboxes.
Paste the multicolumn listbox to the front panel. On the block diagram right-click on it and select "Create->Property node" from pop-up menu. The property node of your control will appea
r in the diagram. Right-click on it and change property to "Item Names" By selectring "Properties->Item Names" from pop-up menu. Now Right-click on the property node once again and select "Change to write" or "Change all to write" to toggle your property into write mode. Then wire your 2D array to this property node.
The example is attached.
Good luck.
Oleg Chutko.
Attachments:
Tables.vi 26 KB -
I am trying to learn java.
The problem I am having now is using toLowerCase
My "how to" book is chock full of syntax examples that don't work as advertised, usually due to simplified examples. This code modifies an example from the book. In fairness the book does not mention String Arrays with toLowerCase info
here is my code:
class newShot {
public static void main(String[ ] arguments) {
String phrase[ ] = {
"What am I doing here",
"When will we get there",
"Are we there yet",
"If I am good can I have a dollar",
"Programming doesn't pay",
"That should do it"
String phrasec[ ] = phrase;
String phraseb[ ] = phrasec.toLowerCase();
}newWheel.java:14: cannot find symbol
symbol : variable phrasebSo you have to declare phraseb - one thing to be careful about is
how big to make it: you can't make arrays bigger later on.class newWheel {
public static void main(String[] arguments) {
String phrase[] = {
"What am I doing here",
"When will we get there",
"Are we there yet",
"If I am good can I have a dollar",
"Programming sucks",
"That should do it"
// phrase.length is the length of phrase
String phraseb[] = new String[phrase.length];
for(int i=0;i<6;i++) {
phraseb[i] = phrase.toLowerCase();
System.out.print("here is all done" + phraseb);
The "6" in the for-loop could also be replaced with phrase.length to
make it more flexible. -
How do you store input from keyboard into a string array
I am trying to learn java and one of the programs I am trying to write needs to be able to accept a machine hostname at the keyboard and stuff it into a string array element. I am sure I will be using something along the lines of:
BufferedReader in = new BufferedReader(new InputStreamReader(
System.in));
String str = "";
System.out.print("Enter a FQDN to look up: ");
str = in.readLine();
but how do I get the input stuffed into hostname[ ].
Any hints or assistance will be appreciated.
MichaelWell part of. I need to be able to take a random number of hostnames (ie. mblack.mkblack.com, fred.mblack.com, joe.mblack.com, ...) and after the user presses the enter key between each entry, the inputted information is stored in an array element. for example with the three shown above the array would look like this after the user finished.
hostname {"mblack.mblack.com","fred.mblack.com","joe.mblack.com"};
the algorithm would be
Prompt for hostname
get user input and press enter
store hostname into array element
prompt for next hostname or enter with no input to complete entry and execute lookup.class methods.
I have the program written and working fine if I use a static array where I put the hostnames in the list, but cannot figure out how to get the information from the keyboard to the array element.
Thanks for the help though, the response is very much appreciated.
Michael -
Problem when passing string array in sessions showing null value
i am trying to pass a string array but it is showing me the null value
i think the the problem is seem to be in session.settAttribute("subject['"+i+"']",subject) in 2.login_action.jsp
or in String sub1=(String) session.getAttribute("subject[0]"); in 3.user_home.jsp
i have following three pages
1.login.html
2.login_action.jsp
3.user_home.html
1.login.html
<html>
<body>
<form method="post" action="login_action.jsp">
Username<input type="text" name="username"></input>
<br>
Password<input type="password" name="password"></input>
<input type="submit" value="login"></input>
</form>
</body>
</html>
2.login_action.jsp
<%@ page contentType="text/html"%>
<%@ page import="java.sql.*" %>
<%!
String user,pwd;
String subject[]=new String[10];
int i,totalsubject;
%>
<%
try
user=request.getParameter("username");
pwd=request.getParameter("password");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:ods","scott","tiger");
PreparedStatement ps = con.prepareStatement("select password from users where username='"+user+"'");
ResultSet rs = ps.executeQuery();
if(rs.next())
if(rs.getString("password").equals(pwd))
session.setAttribute("username",user);
PreparedStatement ps2 = con.prepareStatement("select subject_id from allot_teachers where staff_id='"+user+"'");
ResultSet rs2 = ps2.executeQuery();
while(rs2.next())
i=0;
subject[i]=rs2.getString(1);
// if i display here the subjects in out.println(subject[i]) it is working fine
// but in next redirected page it is showing null
session.setAttribute("subject['"+i+"']",subject[i]);
//out.println(subject[i]);
i++;
response.sendRedirect("user_home.jsp");
else
out.println("error invalid username or password");
else
out.println("error invalid username or password");
con.close();
catch(Exception e)
out.println(e);
%>
3. user_home.jsp
<%@ page contentType="text/html"%>
<%@ page import="java.sql.*" %>
<html>
<%
String user,pwd,cat,cat1;
String username=(String) session.getAttribute("username");
if(username==null)
response.sendRedirect("login.html");
//just tried for first two subjects
String sub1=(String) session.getAttribute("subject[0]");
String sub2=(String) session.getAttribute("subject[1]");
//here it is printing null
out.println(sub1);
//here it is printing null
out.println(sub2);
%>
<form method="post" action="logout.jsp">
<input type="submit" value="Logout"></input>
</form>
</html>
Cheers & Regards
sweetyThe name in getAttributre doesnt match the name in setAttribute.
Note "subject[0]" is a string containing 10 chars, "subject" is a string containing 7 chars.
Here is your code:
session.setAttribute("subject",subject);
String sub1=(String) session.getAttribute("subject[0]"); -
Display string array in a table using netui-data:repeater tags
hi,
I am trying to display a string array in a table using the netui-data:repeater tag.
I have to use a page flow controller Array(1 Dimensional) to be displayed in the jsp.
Can any one tell me how to print the array in a table of 3rows & 5 columns.
Here is the code on which I am crrently working on.
<netui-data:repeater dataSource="{pageFlow.strWorkObject_Array}">
<netui-data:repeaterHeader>
<table cellpadding="4" border="1" class="tablebody">
</netui-data:repeaterHeader>
<netui-data:repeaterItem>
<tr>
<td><netui:label value="{container.item}" >
</netui:label></td>
<td><netui:label value="{container.item}">
</netui:label></td>
<td><netui:label value="{container.item}">
</netui:label></td>
</tr>
</netui-data:repeaterItem>
<netui-data:repeaterFooter>
</table>
</netui-data:repeaterFooter>
</netui-data:repeater>weblogic.developer.interest.workshop
Mansoor Naseem wrote:
I would like to know where the pageflow newsgroup is.
These are all the groups in weblogic.developer.interest:
weblogic.developer.interest.60beta.* (5 groups) weblogic.developer.interest.management
weblogic.developer.interest.61beta.* (2 groups) weblogic.developer.interest.misc
weblogic.developer.interest.clustering.* (1 group) weblogic.developer.interest.performance
weblogic.developer.interest.commerce weblogic.developer.interest.personalization
weblogic.developer.interest.ejb.* (3 groups) weblogic.developer.interest.portal
weblogic.developer.interest.environment weblogic.developer.interest.rmi-iiop
weblogic.developer.interest.jdbc weblogic.developer.interest.security
weblogic.developer.interest.jms weblogic.developer.interest.servlet
weblogic.developer.interest.jndi weblogic.developer.interest.tools
weblogic.developer.interest.jsp weblogic.developer.interest.weblogicenterprise
MN -
How to convert String array into int.
void getSoldSms(Vector vecSoldSms)
String str[]=new String[vecSoldSms.size()];
String words[]=new String[str.length]; // String array
for(int i=0;i< vecSoldSms.size();i++)
str=(String)vecSoldSms.get(i);
} //End for
for(int i=0;i<str.length;i++)
words = str[i].split("\\|\\|");
System.out.println();
for(int j=0;j<1;j++)
int count[str.length]=Integer.parseInt(words[i]);
System.out.print(count[j]*advance_count);
} // end inner for loop
} //End for
} //End function getSoldSms
how do i convert words which is a string array into int type. i kno string can be converted into int using interger.parseint. but wat abt string arrays??? plz help me out with the above code.i did tht its still giving the same errorFor Heaven's sake, what about taking a second to try to understand the code you're copying first? If you really can't fix the error yourself, you have a more serious problem than just convertingStrings to ints.
And if you want { "1", "2", "3" } to be 123:
StringBuffer b = new StringBuffer();
for (int i = 0; i < array.length; i++) {
b.append(array);
int result = Integer.parseIn(b.toString()); -
How to avoid NullPointerException---String array created from JTextArea
Hi,
I use the method getText() to put the contents of a JTextArea into a String object. Then I use split("\\s+") on that String object to get a String array. Before the contents of the String array are output, I get a NullPointerException. How do I avoid this exception? My code is below.
//: net/mindview/util/SwingConsole.java
package net.mindview.util;
import javax.swing.*;
public class SwingConsole {
public static void
run(final JFrame f, final int width, final int height) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
f.setTitle(f.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(width, height);
f.setVisible(true);
} ///:~
//: gui/Charts.java
package gui;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import net.mindview.util.SwingConsole;
public class Charts extends JFrame {
private int[] numbers;
private JTextArea input = new JTextArea();
private JScrollPane areaScrollPane = new JScrollPane(input);
private JButton b1 = new JButton("Submit");
private JButton b2 = new JButton("Clear");
public Charts() {
add(areaScrollPane);
areaScrollPane.setPreferredSize(new Dimension(250, 250));
b1.addActionListener(a1);
b2.addActionListener(a2);
add(b1);
add(b2);
private ActionListener a1 = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = input.getText();
String[] stringArray = data.split("\\s+");
for (String s:stringArray)
System.out.print(s + " ");
int i = 0;
for (String s:stringArray)
numbers=Integer.parseInt(s);
i++;
private ActionListener a2 = new ActionListener() {
public void actionPerformed(ActionEvent e) {
input.setText("");
* @param args the command line arguments
public static void main(String[] args) {
// TODO code application logic here
SwingConsole.run(new Charts(), 400, 400);
Edited by: gluedtothecomputer on Feb 1, 2009 7:59 PMdon't forget to init your int array:
String[] stringArray = data.split("\\s+");
numbers = new int[stringArray.length]; -
SET into string array using toArray()
I have a object java.util.Set collection and I want to convert all the elements
into a string array but i don't know why it is not working in my JSP page...
as i am trying to use toArray() method
i have tried this
String[] arr = collection.toArray();this
String[] arr = (String []) collection.toArray();could you please tell me the right way to aplly it...
thanks in advance....:)I am using session listener which map sessions and it stores sessionid which i hope is a string
when i directly print this set object it shows
[ED0EF456BD1EE956A069340633C8DB87,UT0EF456BD1EE956A069340633C8DB34,RD0EF456BD1EE956A069340633C8DB98]
Message was edited by:
hunterzz
Maybe you are looking for
-
How to use the find Iphone app on two devices with the same itunes and apple id number?
I have two Iphones connected to the same apple id . I am unable to use the find my iphone app on both devices. It only works on one!! Please help! It is driving me crazy lol!!
-
IPod communication error when i updated iTunes!
I updated my itunes and now when i connect my iPod Nano to my computer this error message appears: The software for communicating with the iPod is not installed correctly. Please reinstall iTunes to intall the iPod's software. When I reinstall iTunes
-
Aftr updating s/w - told to reinstall itunes. Error msg Service Apple Mobile Device failed to start. Vertify that you have suff privileges to start system services
-
Modify Journal line description by SLA
Hi, I modified the journal line description in AP by SLA, change the journal line description from invoice distribution description to invoice number+supplier name+invoice distribution description(default setup is invoice distribution description wil
-
Problems displaying Chinese character songs.
Hi, I just transfered my library from my old computer to Windows 7 and the songs with foreign characters such as Chinese display correct when I browse through my library. However, it converts to random characters after I play the song one time. Is th