From JTextField into string array
hello,
Me and my friend are currently doing a cryptography project for UNI. We are required to read in a word from the JTextField into an array. the problem is the whole word seems to be going into the array as one element. Is there any way to read in each letter in the word into a seperate element of the array??
Well you can always read the value in the textfield, convert it to a character array and then as you transfer each character to your string array you add a blank string to it, so then it becomes a string.
Example:
String sentence = "hello, I am a really loooooooooong string";
String[] stringArray = new String[sentence.length()];
char[] charArray = sentence.toCharArray();
for (int count = 0; count < sentence.length(); count++)
stringArray[count] = charArray[count] + "";I hope this helps.
Similar Messages
-
Reading from file into an array
Hello, new to Java and we need to modify a mortgage calculator to read interest rate from a file into an array and not have them hard coded in the program. I have read many post on how to perform this but am lost on where to put the new code and format. Here is my code and I hope I posted this right.
import javax.swing.*; // Imports the Main Swing Package
import javax.swing.event.*;
import javax.swing.text.*; // Used for Text Box Caret Position
import java.awt.*; // Imports the main AWT Package
import java.awt.event.*; // Event handling class are defined here
import java.text.NumberFormat;
import java.text.*; // Imports the Main Text Package
import java.util.*; // Imports the Main Utility Package
public class mortgageCalculator1 extends JFrame implements ActionListener // Creates class mortgageCalculator
JLabel AmountLabel = new JLabel(" Enter Mortgage Amount:$ "); // Declares Mortgage Amount Label
JTextField mortgageAmount = new JTextField(10); // Declares Mortgage Amount Text Field
JButton IntandTerm1B = new JButton("7 years at 5.35%"); // Declares 1st Mortgage Term and Interest Rate
JButton IntandTerm2B = new JButton("15 years at 5.50%"); // Declares 2nd Mortgage Term and Interest Rate
JButton IntandTerm3B = new JButton("30 years at 5.75%"); // Declares 3rd Mortgage Term and Interest Rate
JLabel PaymentLabel = new JLabel(" Monthly Payment: "); // Declares Monthly Payment Label
JTextField monthlyPayment = new JTextField(10); // Declares Monthly Payment Text Field
JButton exitButton = new JButton("Exit"); // Declares Exit Button
JButton newcalcButton = new JButton("New Calculation"); // Declares New Calculation Button
JTextArea mortgageTable = new JTextArea(35,65); // Declares Mortgage Table Area
JScrollPane scroll = new JScrollPane(mortgageTable); // Declares ScrollPane and puts the Mortgage Table inside
public mortgageCalculator1() // Creates Method
super("MORTGAGE CALCULATOR"); // Title of Frame
JMenuBar mb = new JMenuBar(); // Cretes Menu Bar
JMenu fileMenu = new JMenu("File"); // Creates File Menu
fileMenu.setMnemonic('F'); // Enables alt + f to Access File Menu
JMenuItem exitItem = new JMenuItem("Exit"); // Creates Exit in File Menu
fileMenu.add(exitItem); // Adds Exit to File Menu
exitItem.addActionListener(new ActionListener() // Adds Action Listener to the Exit Item
public void actionPerformed(ActionEvent e) // Tests to Verify if File->Exit is Pressed
System.exit(0); // Exits the Programs when File->Exit is Pressed
mb.add(fileMenu); // Adds the File Menu
setJMenuBar(mb);
setSize(600, 400); // Sets Size of Frame
setLocation(200,200); // Sets the Location of the Window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Command on how to close frame
JPanel pane = new JPanel(); // Declares the JPanel
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS)); // Sets Panel Layout to BoxLayout
Container grid = getContentPane(); // Declares a Container called grid
grid.setLayout(new GridLayout(4,3,5,5)); // Sets grid Layout to GridLayout
pane.add(grid); // Adds the grid to the Panel
pane.add(scroll); // Addes the scrollPane to the Panel
grid.setBackground(Color.yellow); // Set grid color to Yellow
setCursor(new Cursor(Cursor.HAND_CURSOR)); // Makes the cursor look like a hand
mortgageAmount.setBackground(Color.black); // Sets mortgageAmount JPanel JTextField Background Color
mortgageAmount.setForeground(Color.white); // Sets mortgageAmount JPanel JTextField Foreground Color
mortgageAmount.setCaretColor(Color.white); // Sets mortgageAmount JPanel JTextField Caret Color
mortgageAmount.setFont(new Font("Lucida Sans Typewriter", Font.PLAIN, 18)); // Sets mortgageAmount JPanel JTextField Font
monthlyPayment.setBackground(Color.black); // Sets monthlyPayment JPanel JTextField Background Color
monthlyPayment.setForeground(Color.white); // Sets monthlyPayment JPanel JTextField Foreground Color
monthlyPayment.setFont(new Font("Lucida Sans Typewriter", Font.PLAIN, 18)); // Sets monthlyPayment JPanel JTextField Font
mortgageTable.setBackground(Color.yellow); // Sets mortgageTable JTextArea Background Color
mortgageTable.setForeground(Color.black); // Sets mortgageTable JTextArea Foreground Color
mortgageTable.setFont(new Font("Arial", Font.PLAIN, 18)); // Sets JTextArea Font
grid.add(AmountLabel); // Adds the Mortgage Amount Label
grid.add(mortgageAmount); // Adds the Mortgage Amount Text Field
grid.add(IntandTerm1B); // Adds 1st Loan and Rate Button
grid.add(PaymentLabel); // Adds the Payment Label
grid.add(monthlyPayment); // Adds the Monthly Payment Text Field
monthlyPayment.setEditable(false); // Disables editing in this Text Field
grid.add(IntandTerm2B); // Adds 2nd Loan and Rate Button
grid.add(exitButton);
grid.add(newcalcButton); // Adds the New Calc Button
grid.add(IntandTerm3B); // Adds the Exit Button
setContentPane(pane); // Enables the Content Pane
setVisible(true); // Sets JPanel to be Visable
exitButton.addActionListener(this); // Adds Action Listener to the Exit Button
newcalcButton.addActionListener(this); // Adds Action Listener to the New Calc Button
IntandTerm1B.addActionListener(this); // Adds Action Listener to the 1st loan Button
IntandTerm2B.addActionListener(this); // Adds Action Listener to the 2nd loan Button
IntandTerm3B.addActionListener(this); // Adds Action Listener to the 3rd loan Button
mortgageAmount.addActionListener(this); // Adds Action Listener to the Mortgage Amount Text Field
monthlyPayment.addActionListener(this); // Adds Action Listener to the Monthly payment Text Field
public void actionPerformed(ActionEvent e) // Tests to Verify Which Button is Pressed
Object command = e.getSource(); // Enables command to get data
if (command == exitButton) //sets exitButton // Activates the Exit Button
System.exit(0); // Exits from exit button // Exits from exit button
int loanTerm = 0; // Declares loanTerm
if (command == IntandTerm1B) // Activates the 1st Loan Button
loanTerm = 0; // Sets 1st value of Array
if (command == IntandTerm2B) // Activates the 2nd Loan Button
loanTerm = 1; // Sets 2nd value of Array
if (command == IntandTerm3B) // Activates the 3rd Loan Button
loanTerm = 2; // Sets 3rd value of Array
double mortgage = 0; // Declares and Initializes mortgage
double rate = 0; // Declares and Initializes rate
double [][] loans = {{7, 5.35}, {15, 5.50}, {30, 5.75},}; // Array Data for Calculation
try
mortgage = Double.parseDouble(mortgageAmount.getText()); // Gets user input from mortgageAmount Text Field
catch (NumberFormatException nfe) // Checks for correct number fformatting of user input
JOptionPane.showMessageDialog (this, "Error! Invalid input!"); // Outputs error if number is wrong format or nothing is entered
return;
double interestRate = loans [loanTerm][1]; // Sets interestRate amount
double intRate = (interestRate / 100) / 12; // Calculates Interst Rate
double loanTermMonths = loans [loanTerm] [0]; // Calculates Loan Term in Months
int months = (int)loanTermMonths * 12; // Converts Loan Term to Months
double interestRateMonthly = (intRate / 12); // monthly interst rate
double payment = mortgage * intRate / (1 - (Math.pow(1/(1 + intRate), months))); // Calculation for Monthly payment
double remainingLoanBalance = mortgage; // Sets Reamaining Balance
double monthlyPaymentInterest = 0; // holds current interest payment
double monthlyPaymentPrincipal = 0; // holds current principal payment
NumberFormat myCurrencyFormatter = NumberFormat.getCurrencyInstance(Locale.US); // Number formatter to format output in table
monthlyPayment.setText(myCurrencyFormatter.format(payment));
mortgageTable.setText("Month\tPrincipal\tInterest\tEnding Balance\n" + // Formats morgageTable Header
"---------\t----------\t------------\t---------------------\n");
for (;months > 0 ; months -- )
monthlyPaymentInterest = (remainingLoanBalance * intRate); // Calculation for Monthly Payment Toward Interest
//Calculate H = R x I
monthlyPaymentPrincipal = (payment - monthlyPaymentInterest); // Calculation for Monthly Payment Toward Principal
//Calculate C = P - H
remainingLoanBalance = (remainingLoanBalance - monthlyPaymentPrincipal); // Calculation for Reamining loan Balance
// Calculate R = R - C
// H = monthlyPaymentInterest
// R = remainingLoanBalance
// P = payment
// C = monthlyPaymentPrincipal
// I = interestRateMonthly
mortgageTable.setCaret (new DefaultCaret()); // Sets Scroll position to the top left corner
mortgageTable.append(String.valueOf(months) + "\t" + // Pulls in data and formats MortgageTable
myCurrencyFormatter.format(monthlyPaymentPrincipal) + "\t" +
myCurrencyFormatter.format(monthlyPaymentInterest) + "\t" +
myCurrencyFormatter.format(remainingLoanBalance) + "\n");
if(command == newcalcButton) // Activates the new calculation Button
mortgageAmount.setText(null); //clears mortgage amount fields
monthlyPayment.setText(null); //clears monthly payment fields
mortgageTable.setText(null); //clears mortgage table
public static void main(String[] args) //This is the signature of the entry point of all the desktop apps
new mortgageCalculator1();
}OK, making a little progress but am still very confused.
What I have is a file (int&term.dat) with three lines;
5.75, 30
5.5, 15
5.35 ,7
I have three JButtom that I what to read a seperate line and place the term in a term TextField and a rate in a Rate TextField
I have added the following code and all it does now is output a black space to the screen; I am working with one Button and Just the rate for now to try and get it to work. I have been looking at the forums, reading the internet and several books to try and figure this out. I think I may be getting closer.
public static void read()
String line;
StringTokenizer tokenizer;
String rate;
String term;
try
FileReader fr = new FileReader ("int&term.dat");
BufferedReader inFile = new BufferedReader (fr);
line = inFile.readLine();
while (line != null)
tokenizer = new StringTokenizer(line);
rate = tokenizer.nextToken();
line = inFile.readLine();
inFile.close();
System.out.println(new String());
catch (FileNotFoundException exception)
System.out.println ("The file was not found.");
catch (IOException exception)
System.out.println (exception);
} -
Loading into String array?
I made a method that loads 2 strings from a text file, and adds them into an array, but it won't work, heres the code.
public static void loadFile() {
for(int i = 0; i < 2; i++) {
try {
final Properties testCheck = new Properties();
final FileInputStream fis = new FileInputStream("myfile.txt");
testCheck.load(fis);
fis.close();
toTest[i] = testCheck.getProperty("test","Nothing Found");
} catch (IOException ioexception) {
System.err.println ("Error reading");
} Thats the method, I make it print out the array, and it shows up Nothing Found, which means it didn't find what the value in the text file? Any help is greatly appreaciated.Whatever your problem is, you haven't described it completely.
Please excuse any typos in the following; my development environment and my internet are on different machines tonight,and I cannot copy-and-paste this over.
package rc.test;
import java.io.*;
import java.util.*;
public class TestLP
static String[] toTest = new String[2];
public static void main (String[] arguments)
{ loadFile();
for (int i=0; i<toTest.length; i++)
{ System.out.println(toTest);
public static void loadFile()
for (int i=0; i<2; i++)
try
final Properties testCheck = new Properties();
final FileInputStream fis = new FileInputStream("myfile.txt");
testCheck.load(fis);
fis.close();
toTest[i] = testCheck.getProperty("test", "Nothing Found");
catch (IOException ioexception)
{ System.err.println("Error reading");
With the file "myfile.txt" in the directory in which the program is run, and containing the single line "test TESTING", this program prints:
TESTING
TESTING
All of your code is here, reformatted but otherwise intact; I've added what I surmised to be reasonable drivers to show us whether this code works as expected, and it does.
Possibilities:
The array you think you're loading the data into is in a different scope than the one loaded. You do not give us the declaration of that array, so we cannot tell.
The printout of the information is somehow flawed. You don't show us how you output it, so we cannot tell.
myfile.txt doesn't contain what you expect, or there is more than one copy. Perhaps "test" is capitalized, which would give the result you indicate. So would a file that doesn't actually contain "test" as a key.
Part of the point here is that complete information would cost very little compared to what you've already done, and would allow us to help you better. -
How do I read directly from file into byte array
I am reading an image from a file into a BuffertedImage then writing it out again into an array of bytes which I store and use later on in the program. Currently Im doing this in two stages is there a way to do it it one go to speed things up.
try
//Read File Contents into a Buffered Image
/** BUG 4705399: There was a problem with some jpegs taking ages to load turns out to be
* (at least partially) a problem with non-standard colour models, which is why we set the
* destination colour model. The side effect should be standard colour model in subsequent reading.
BufferedImage bi = null;
ImageReader ir = null;
ImageInputStream stream = ImageIO.createImageInputStream(new File(path));
final Iterator i = ImageIO.getImageReaders(stream);
if (i.hasNext())
ir = (ImageReader) i.next();
ir.setInput(stream);
ImageReadParam param = ir.getDefaultReadParam();
ImageTypeSpecifier typeToUse = null;
for (Iterator i2 = ir.getImageTypes(0); i2.hasNext();)
ImageTypeSpecifier type = (ImageTypeSpecifier) i2.next();
if (type.getColorModel().getColorSpace().isCS_sRGB())
typeToUse = type;
if (typeToUse != null)
param.setDestinationType(typeToUse);
bi = ir.read(0, param);
//ir.dispose(); seem to reference this in write
//stream.close();
//Write Buffered Image to Byte ArrayOutput Stream
if (bi != null)
//Convert to byte array
final ByteArrayOutputStream output = new ByteArrayOutputStream();
//Try and find corresponding writer for reader but if not possible
//we use JPG (which is always installed) instead.
final ImageWriter iw = ImageIO.getImageWriter(ir);
if (iw != null)
if (ImageIO.write(bi, ir.getFormatName(), new DataOutputStream(output)) == false)
MainWindow.logger.warning("Unable to Write Image");
else
if (ImageIO.write(bi, "JPG", new DataOutputStream(output)) == false)
MainWindow.logger.warning("Warning Unable to Write Image as JPEG");
//Add to image list
final byte[] imageData = output.toByteArray();
Images.addImage(imageData);
If you don't need to manipulate the image in any way I would suggest you just read the image file directly into a byte array (without ImageReader) and then create the BufferedImage from that byte array.
-
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 -
Splitting html ul tags and their content into string arrays using regular expression
<ul data-role="listview" data-filter="true" data-inset="true">
<li data-role="list-divider"></li><li><a href="#"><h3>
my title
</h3><p><strong></strong></p></a></li>
</ul>
<ul data-role="listview" data-filter="true" data-inset="true">
<li data-role="list-divider"></li><li>test.</li>
</ul>
I need to be able to slip this html into two arrays hold the entire <ul></ul> tag. Please help.
Thanks.Hi friend.
This forum is to discuss problems of C# development. Your question is not related to the topic of this forum.
You'll need to post it in the dedicated Archived Forums N-R > Regular Expressions
for better support. Thanks for understanding.
Best Regards,
Kristin -
Entering data from JTextfield into Database--- Techniques
hello friends,
I am developing an application where i want to insert data from my Jtextfield to data base.
I know all the procedure but i am confused.
I have 11 fields in my frame, out of which 3 are compulsory. rest are optional.
i am validating those 3 compulsory fields.
so i have to generate run time insert query, depending on the fields Populated.
Also i have my connection to db in other class. that not a problem as i can call a method. But how to pass so many arguments. when no. of arguments also change runtime.Thanks Aniruddha,
But i didn't understand what u said.
I think I will do as following
1. check the populated field.
2. if yes then insert them into a hashmap .
key = field name, value = field value
3. send the hash map as the argument to function connecting my db.
4. retrieve the fields. and dependingly make a prepared statement for insertion.
5. as some of my fields are integer, convert them to int . then set them
6. then execute the query.
if u have any other suggestions please tell.... -
Reading a pdf file from URL into Byte array/ByteBuffer in an applet.
I'm trying to figure out why this particular snippet of code isn't working for me. I've got an applet which is supposed to read a .pdf and display it with a pdf-renderer library, but for some reason when I read in the .pdf files which sit on my server, they end up as being corrupt. I've tested it by writing the files back out again.
I've tried viewing the applet in both IE and Firefox and the corrupt files occur. Funny thing is, when I trying viewing the applet in Safari (for Windows), the file is actually fine! I understand the JVM might be different, but I am still lost. I've compiled in Java 1.5. JVMs are 1.6. The snippet which reads the file is below.
public static ByteBuffer getAsByteArray(URL url) throws IOException {
ByteArrayOutputStream tmpOut = new ByteArrayOutputStream();
URLConnection connection = url.openConnection();
int contentLength = connection.getContentLength();
InputStream in = url.openStream();
byte[] buf = new byte[512];
int len;
while (true) {
len = in.read(buf);
if (len == -1) {
break;
tmpOut.write(buf, 0, len);
tmpOut.close();
ByteBuffer bb = ByteBuffer.wrap(tmpOut.toByteArray(), 0,
tmpOut.size());
//Lines below used to test if file is corrupt
//FileOutputStream fos = new FileOutputStream("C:\\abc.pdf");
//fos.write(tmpOut.toByteArray());
return bb;
}I must be missing something, and I've been banging my head trying to figure it out. Any help is greatly appreciated. Thanks.Keshav.. wrote:
I too was going through the same problem but I found for some pdfs it worked fine.I didnt get ur solution.Please explain bcoz it may work for every pdfThis thread is over 3 years old and dead. Please open a new thread which provides details of the problem you are having. Link to this thread if you think it is necessary.
I shall lock this thread. -
How convert integer into string
Hi,
I need to convert answer3 from double into String
answer3 = Double.parseDouble(dij3)/(1 + Math.pow(( Double.parseDouble(tesside_luas_i) / Double.parseDouble(tesside_luas_j) ),0.5847));Now the integer value is string but why i cannot get valur from my servlet to my web page
package net.mybizaid.isodms.servlet;
import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import net.mybizaid.isodms.*;
public class SPLDataInputServlet extends HttpServlet {
public void doPost (HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
System.out.println( "******************** Calculation Servlet ******************" );
String dij ;
String population_i ;
String population_j ;
String project_name = "";
String project_status = "";
double answer;
String handler = "";
String url = "";
double answer3;
String dij3 ="";
String tesside_luas_i ="";
String tesside_luas_j ="";
double answer2;
String dij2 ="";
String luas_i ="";
String luas_j ="";
String counter = "";
String i = "";
handler = request.getParameter( "handler" );
dij = request.getParameter("dij");
population_i = request.getParameter("population_i");
population_j = request.getParameter( "population_j");
project_name = request.getParameter( "project_name");
project_status = request.getParameter( "project_status");
dij2 = request.getParameter("dij2");
luas_i = request.getParameter("luas_i");
luas_j = request.getParameter( "luas_j");
dij3 = request.getParameter("dij3");
tesside_luas_i = request.getParameter("tesside_luas_i");
tesside_luas_j = request.getParameter( "tesside_luas_j");
HttpSession session = null;
session = request.getSession(true);
int cnt = counter != null && !counter.equals("") ? Integer.parseInt(counter) : 0;
int ii = i != null && !i.equals("") ? Integer.parseInt(i) : 0;
//Tesside
if (handler != null && !handler.equals( "" ) && handler.equals( "cal3" ))
try
System.out.println("The DIJ3 value is :"+dij3);
System.out.println("The tesside_luas_i value is :"+tesside_luas_i);
System.out.println("The tesside_luas_j value is :"+tesside_luas_j);
answer3 = Double.parseDouble(dij3)/(1 + Math.pow(( Double.parseDouble(tesside_luas_i) / Double.parseDouble(tesside_luas_j) ),0.5847));
String str = String.valueOf( answer3 );
System.out.println("The answer value is :"+str);
url = "/jsp/model/tessideAnswer.jsp";
dispatchErrorMsg( request, response, url, "" );
catch (Exception e)
request.setAttribute("pd.errorMessage", e.getMessage());
dispatchErrorMsg( request, response, "/jsp/Error.jsp", e.getMessage() );
//PotensiPasaran
if (handler != null && !handler.equals( "" ) && handler.equals( "cal2" ))
try
System.out.println("The DIJ2 value is :"+dij2);
System.out.println("The luas_i value is :"+luas_i);
System.out.println("The luas_j value is :"+luas_j);
answer2 = Double.parseDouble(dij2)/(1 + Math.sqrt(( Double.parseDouble(luas_i) / Double.parseDouble(luas_j) )));
System.out.println("The answer value is :"+answer2);
url = "/jsp/model/potensiPasaranAnswer.jsp";
dispatchErrorMsg( request, response, url, "" );
catch (Exception e)
request.setAttribute("pd.errorMessage", e.getMessage());
dispatchErrorMsg( request, response, "/jsp/Error.jsp", e.getMessage() );
//Reilly
if (handler != null && !handler.equals( "" ) && handler.equals( "add" ))
try
System.out.println("The DIJ value is :"+dij);
System.out.println("The population_i value is :"+population_i);
System.out.println("The population_j value is :"+population_j);
answer = Double.parseDouble(dij)/(1 + Math.sqrt(( Double.parseDouble(population_i) / Double.parseDouble(population_j) )));
System.out.println("The answer value is :"+answer);
url = "/jsp/model/reillyAnswer.jsp";
dispatchErrorMsg( request, response, url, "" );
catch (Exception e)
request.setAttribute("pd.errorMessage", e.getMessage());
dispatchErrorMsg( request, response, "/jsp/Error.jsp", e.getMessage() );
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
doPost(request, response);
}//end doGet
public void dispatchErrorMsg(HttpServletRequest req, HttpServletResponse res,
String target, String message)
try
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(target);
req.setAttribute("eshop.ErrMessage",message);
dispatcher.forward(req, res);
catch (Exception e)
System.err.println( e.getMessage() );
}//end class -
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 -
Moving data string from a jtextarea into an array
i was looking for some advice. how would i be able to take chunks of text on a paragraph by paragraph basis and enter them into an array. which would result in paragraph1 in array 0, and so on. is this possible to do? i have never really used straing arrays before, and if anyone knows of any online tutorials it would be a great help
thank uhere you go, forgive the gui, very sloppy looking, press the Click me button to store the jtextarea data into the array and show output button to see what the value stored in the array is. there are 2 classes:
class MyMain {
public static void main(String args[]){
MyMain main = new MyMain();
main.createIt();
public void createIt() {
MyFrame frame = new MyFrame();
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class MyFrame extends JFrame {
String[] myString = new String[1];
JTextArea textArea = new JTextArea();
JButton myButton = new JButton("Click me");
JButton outButton = new JButton("Show output");
MyFrame() {
myButton.addActionListener(new ButtonListener());
outButton.addActionListener(new OutListener());
getContentPane().setLayout(new GridLayout(1,3));
getContentPane().add(myButton);
getContentPane().add(textArea);
getContentPane().add(outButton);
setVisible(true);
class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e){
myString[0] = textArea.getText();
class OutListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
System.out.println(myString[0]);
} -
Reading one line from a text file into an array
i want to read one line from a text file into an array, and then the next line into a different array. both arays are type string...i have this:
public static void readAndProcessData(FileInputStream stream){
InputStreamReader iStrReader = new InputStreamReader (stream);
BufferedReader reader = new BufferedReader (iStrReader);
String line = "";
try{
int i = 0;
while (line != null){
names[i] = reader.readLine();
score[i] = reader.readLine();
line = reader.readLine();
i++;
}catch (IOException e){
System.out.println("Error in file access");
this section calls it:
try{
FileInputStream stream = new FileInputStream("ISU.txt");
HighScore.readAndProcessData(stream);
stream.close();
names = HighScore.getNames();
scores = HighScore.getScores();
}catch(IOException e){
System.out.println("Error in accessing file." + e.toString());
it gives me an array index out of bounds erroroh wait I see it when I looked at the original quote.
They array you made called names or the other one is prob too small for the amount of names that you have in the file. Hence as I increases it eventually goes out of bounds of the array so you should probably resize the array if that happens. -
String array into formula node
Hello,
I am taking data from SQL, I am getting multiple rows of data for many different devices. I would like to wire the data into a formula node so I can sepearate and sort via script. However, I am getting an error for "Polymorphic terminal cannot accept this data type". Is there a work around? Can I not wire in a string array to a formula node.
/r
TravoThere are lots of basic string VIs that you can use to parse the string and separate out the individual fields. I would recommend "programming" your application using script nodes. Use the native language. LabVIEW is a fully functional and capable programming language.
Mark Yedinak
"Does anyone know where the love of God goes when the waves turn the minutes to hours?"
Wreck of the Edmund Fitzgerald - Gordon Lightfoot -
How to Pass String array from Java to PL/SQL and this use in CURSOR
hi,
I cant understand how to pass Array String as Input Parameter to the Procedure and this array use in Cursor for where condition like where SYMPTOM in( ** Array String **).
This array containing like (SYMPTOM ) to be returned from the java to the
pl/sql (I am not querying the database to retrieve the information).
I cannot find an example on this. I will give the PL/SQL block
create or replace procedure DISEASE_DTL<*** String Array ***> as
v_SYMPTOM number(5);
CURSOR C1 is
select distinct a.DISEASE_NAME from SYMPTOM_DISEASE_RD a
where ltrim(rtrim(a.SYMPTOM)) in ('Fever','COUGH','Headache','Rash') ------- ***** Here use this array element(like n1,n2,n3,n4,n5..) ******
group by a.DISEASE_NAME having count(a.DISEASE_NAME) > 3 ----------- ***** 3 is no of array element - 1 (i.e( n - 1))*****
order by a.DISEASE_NAME ;
begin
for C1rec IN C1 loop
select count(distinct(A.SYMPTOM)) into v_SYMPTOM from SYMPTOM_DISEASE_RD a where A.DISEASE_NAME = C1rec.DISEASE_NAME;
insert into TEMP_DISEASE_DTLS_SYMPTOM_RD
values (SL_ID_SEQ.nextval,
C1rec.DISEASE_NAME,
(4/v_SYMPTOM), --------**** 4 is no of array element (n)************
(1-(4/v_SYMPTOM)));
end loop;
commit;
end DISEASE_DTL;
Please give the proper solution and step ..
Thanking you,
AsishI've haven't properly read through your code but here's an artificial example based on a sql collection of object types - you don't need that, you just need a type table of varchar2 rather than a type table of oracle object type:
http://orastory.wordpress.com/2007/05/01/upscaling-your-jdbc-app/ -
Help! Inserting a 1-D comment array into a 2-D string array at specified row AND column
Hello everyone,
I am writing a 2-D string array to excel and i need a way to add comments to my file like this:
SLAM NAME G Level Comments
1 RALF 26
1 RALF 26
1 RALF 26
1 RALF 26
For some reason, i cannot specify a row AND column to write because:
When i use replace array subset it only replaces 1 element at my index.
When i use replace array subset with a loop, it creates empty spaces until it reaches the end of the array it is replacing.
When i use Insert into array: i cannot wire 2 inputs for row and column.
In my complete VI i will need to write from row 1-1001, a different comment from 2-2002, a different comment from 3-3003, etc until a stop condition is met so i need to figure out how to do this programatically and not have it replace any elements outside of the range or it will override previous commetns.
I am at a loss of what to do. Any and all suggestions are greatly appreciated.
Thanks!
Solved!
Go to Solution.
Attachments:
array.vi 13 KBHi proph,
I made a small subtile change to yur VI and now it replaces all values of the 4th column…
THINK DATAFLOW!
Use shift registers when you need to propagate values from one loop iteration to the next!
USE/LEARN DEBUGGING TECHNIQUES!
There are tools like probes and highlight to understand your VI execution and to find problems…
Go through all those free online courses offered by NI!
Best regards,
GerdW
CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
Kudos are welcome
Attachments:
array.vit 12 KB
Maybe you are looking for
-
Index:0 Size:0 error for non administrator group
Hello, I have some dasboards and webis that I want to run in the iPad, If I login as Administrator everything is fine, but if I login as any other user I get the error: Index:0 Size: 0 can anyone tell me what I am missing? I already check the note 1
-
End Point URI change in Business service?
Hi all, We had done all our osb code development and moving from one environment to other(Eg. E2E testing to UAT, Then UAT to Production). When we move the codes from one server to the other we need to change the End Point URI in the business service
-
I can't get Bryce 5.0 to install..Please Help!
I downloaded Bryce 5.0 for my son new class at school as requested by his teacher. But when I try to install it, the Disk Utility page pops open and I dont know what to do? Im not (obviously,lol) very apt at this, but this should have been a no-brain
-
Installing Ora10G v.1.0.3 in Red Hat ES/AS 3 fails
During the install of Oracle Database 10G v.1.0.3, the last version, in Red Hat Linux ES/AS 3, it fails when installing the OEM, and in the log file the next error is write : v-2004 18:04:29 oracle.sysman.emcp.EMConfig checkParameters GRAVE: Failed t
-
Hi, sometimes I have problems initialing the OEM, after a lot of tries a solution that solve my problems is: emca -deconfig dbcontrol db -repos drop emca -config dbcontrol db -repos create And it works... But whats real effect of this commands? Which