Array of Matches
Hello all.
I'm trying to figure out the best way to get the following information:
Column A is filled with items, say Gold, Silver, Copper, Brass, Aluminum
Column C and to the right has references to items in Column A. Each row is different and contains a different amount of references.
Here's an example:
___A______________B___________C________D______E
1| Brass
2| Copper___________________Brass (this would actually be =A1 and all below are also references)
3| Silver______________________Brass___Gold
4| Gold_______________________Copper__Silver__Brass
5| Aluminum________________Gold
I can put =MATCH(C2,$A) in B2 and get 1 back, but what I'm looking for is the highest return out of the matches on a row. So for row 4, I'd want the result of 3 because Silver is the highest one from the list to the right. I know I can MAX() and array and get that number, but is there a simple way to get the matches into an array without having to resort to =MAX(MATCH(C4,$A),MATCH(D4,$A),MATCH(E4,$A) to get it? Thanks in advance for any help and wisdom.
Jeff
Message was edited by: Jeff Langston
For your example (values between 0.5 and 2) if you want this:
I would do something like this:
I just generated an array of 10 random numbers between 0.0 and 2.0
The next loop sorts through the data, by using 'In Range and Coerce'.
It then outputs the data that is in the selected range.
The last step is to take the average
I attached the VI if you would like to use the code.
Message Edited by Cory K on 08-13-2009 09:21 PM
Cory K
Attachments:
In Range.vi 9 KB
Similar Messages
-
How to search for particular string in array?
I am struggling to figure out how to search array contents for a string and then delete the entry from the array if it is found.
The code for a program that allows the user to enter up to 20 inventory items (tools) is posted below; I apologize in advance for it as I am also not having much success grasping the concept of OOP and I am certain it is does not conform although it all compiles.
Anyway, if you can provide some assistance as to how to go about searching the array I would be most grateful. Many thanks in advance..
// ==========================================================
// Tool class
// Reads user input from keyboard and writes to text file a list of entered
// inventory items (tools)
// ==========================================================
import java.io.*;
import java.text.DecimalFormat;
public class Tool
private String name;
private double totalCost;
int units;
// int record;
double price;
// Constructor for Tool
public Tool(String toolName, int unitQty, double costPrice)
name = toolName;
units = unitQty;
price = costPrice;
public static void main( String args[] ) throws Exception
String file = "test.txt";
String input;
String item;
String addItem;
int choice = 0;
int recordNum = 1;
int qty;
double price;
boolean valid;
String toolName = "";
String itemQty = "";
String itemCost = "";
DecimalFormat fmt = new DecimalFormat("##0.00");
// Display menu options
System.out.println();
System.out.println(" 1. ENTER item(s) into inventory");
System.out.println(" 2. DELETE item(s) from inventory");
System.out.println(" 3. DISPLAY item(s) in inventory");
System.out.println();
System.out.println(" 9. QUIT program");
System.out.println();
System.out.println("==================================================");
System.out.println();
// Declare and initialize keyboard input stream
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
do
valid = false;
try
System.out.print(" Enter an option > ");
input = stdin.readLine();
choice = Integer.parseInt(input);
System.out.println();
valid = true;
catch(NumberFormatException exception)
System.out.println();
System.out.println(" Only numbers accepted. Try again.");
while (!valid);
while (choice != 1 && choice != 2 && choice != 9)
System.out.println(" Not a valid option. Try again.");
System.out.print(" Enter an option > ");
input = stdin.readLine();
choice = Integer.parseInt(input);
System.out.println();
if (choice == 1)
// Declare and initialize input file
FileWriter fileName = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileName);
PrintWriter dataFile = new PrintWriter(bufferedWriter);
do
addItem="Y";
System.out.print(" Enter item #" + recordNum + " name > ");
toolName = stdin.readLine();
if (toolName.length() > 15)
toolName = toolName.substring(0,15); // Convert to uppercase
toolName = toolName.toUpperCase();
dataFile.print (toolName + "\t");
do
valid = false;
try
// Prompt for item quantity
System.out.print(" Enter item #" + recordNum + " quantity > ");
itemQty = stdin.readLine();
// Parse integer as string
qty = Integer.parseInt (itemQty);
// Write item quantity to data file
dataFile.print(itemQty + "\t");
valid=true;
catch(NumberFormatException exception)
// Throw error for all non-integer input
System.out.println();
System.out.println(" Only whole numbers please. Try again.");
while (!valid);
do
valid = false;
try
// Prompt for item cost
System.out.print(" Enter item #" + recordNum + " cost (A$) > ");
itemCost = stdin.readLine();
// Parse float as string
price = Double.parseDouble(itemCost);
// Write item cost to data file
dataFile.println(fmt.format(price));
valid = true;
catch(NumberFormatException exception)
// Throw error for all non-number input (integers
// allowed)
System.out.println();
System.out.println(" Only numbers please. Try again.");
while (!valid);
// Prompt to add another item
System.out.println();
System.out.print(" Add another item? Y/N > ");
addItem = stdin.readLine();
while ((!addItem.equalsIgnoreCase("Y")) && (!addItem.equalsIgnoreCase("N")))
// Prompt for valid input if not Y or N
System.out.println();
System.out.println(" Not a valid option. Try again.");
System.out.print(" Add another item? Y/N > ");
addItem = stdin.readLine();
System.out.println();
// Increment record number by 1
recordNum++;
if (addItem.equalsIgnoreCase("N"))
System.out.println();
System.out.println(" The output file \"" + file + "\" has been saved.");
System.out.println();
System.out.println(" Quitting program.");
while (addItem.equalsIgnoreCase("Y"));
// Close input file
dataFile.close();
if (choice == 2)
try {
Read user input (array search string)
Search array
If match found, remove entry from array
Confirm "deletion" and display new array contents
catch block {
} // class
// ==========================================================
// ListToolDetails class
// Reads a text file into an array and displays contents as an inventory list
// ==========================================================
import java.io.*;
import java.util.StringTokenizer;
import java.text.DecimalFormat;
public class ListToolDetails {
// Declare variable
private Tool[] toolArray; // Reference to an array of objects of type Tool
private int toolCount;
public static void main(String args[]) throws Exception {
String line, name, file = "test.txt";
int units, count = 0, record = 1;
double price, total = 0;
DecimalFormat fmt = new DecimalFormat("##0.00");
final int MAX = 20;
Tool[] items = new Tool[MAX];
System.out.println("Inventory List");
System.out.println();
System.out.println("REC.#" + "\t" + "ITEM" + "\t" + "QTY" + "\t"
+ "PRICE" + "\t" + "TOTAL");
System.out.println("\t" + "\t" + "\t" + "\t" + "PRICE");
System.out.println();
try {
// Read a tab-delimited text file of inventory items
FileReader fr = new FileReader(file);
BufferedReader inFile = new BufferedReader(fr);
StringTokenizer tokenizer;
while ((line = inFile.readLine()) != null) {
tokenizer = new StringTokenizer(line, "\t");
name = tokenizer.nextToken();
try {
units = Integer.parseInt(tokenizer.nextToken());
price = Double.parseDouble(tokenizer.nextToken());
items[count++] = new Tool(name, units, price);
total = units * price;
} catch (NumberFormatException exception) {
System.out.println("Error in input. Line ignored:");
System.out.println(line);
System.out.print(" " + count + "\t");
System.out.print(line + "\t");
System.out.print(fmt.format(total));
System.out.println();
inFile.close();
} catch (FileNotFoundException exception) {
System.out.println("The file " + file + " was not found.");
} catch (IOException exception) {
System.out.println(exception);
System.out.println();
// Unfinished functionality for displaying "error" message if user tries to
// add more than 20 tools to inventory
public void addTool(Tool maxtools) {
if (toolCount < toolArray.length) {
toolArray[toolCount] = maxtools;
toolCount += 1;
} else {
System.out.print("Inventory is full. Cannot add new tools.");
// This should search inventory by string and remove/overwrite matching
// entry with null
public Tool getTool(int index) {
if (index < toolCount) {
return toolArray[index];
} else {
System.out
.println("That tool does not exist at this index location.");
return null;
} // classData file contents:
TOOL 1 1 1.21
TOOL 2 8 3.85
TOOL 3 35 6.92Ok, so you have an array of Strings. And if the string you are searching for is in the array, you need to remove it from the array.
Is that right?
Can you use an ArrayList<String> instead of a String[ ]?
To find it, you would just do:
for (String item : myArray){
if (item.equals(searchString){
// remove the element. Not trivial for arrays, very easy for ArrayList
}Heck, with an arraylist you might be able to do the following:
arrayList.remove(arrayList.indexOf(searchString));[edit]
the above assumes you are using 1.5
uses generics and for each loop
[edit2]
and kinda won't work it you have to use an array since you will need the array index to be able to remove it. See the previous post for that, then set the value in that array index to null.
Message was edited by:
BaltimoreJohn -
Simple array comparison not working. Please HELP!
I have been struggling to solve this problem for a few days now, and I'm slowly losing my mind.
I am in Adobe Acrobat 10.
I have a group of button fields called: btn0, btn1, btn2, etc.
I have a group of text fields called: txt0, txt1, txt2, etc.
I have a script that takes the value of txt0 and makes it the caption for btn0, and so on.
I have a script that sets the MouseUp action of btn0 to setFocus to txt0, and so on.
These scripts work fine.
I have a script that takes the values of all the txt fields and puts them in an array, and sorts it.
I have a script that takes the array[0] item and makes it the caption for btn0, and so on (alphabetizing my list of buttons).
Those scripts work fine.
I am trying to compare the value of the array[0] item to each of the txt fields to find the match, and then set the MouseUp action of btn0 to setFocus to the matching txt field, and so on (so my alphabetized list points to the correct locations).
This is where I'm at a loss.
Here is what I have:
//specified the txt fields
var txt0 = this.getField("Z name");
var txt1 = this.getField("A name");
//etc.
//put their values into an array called rxArray
var rxArray = [txt0.value, txt1.value]; //etc.
//sorted the array
rxArray.sort();
//set the captions equal to the sorted array items
for (var i = 0; i < 5; i++) {
var b = ("btn" + i);
this.getField(b).buttonSetCaption(rxArray[i]); //works fine; alphabetizes the list of buttons
//below is what goes wrong
for(var x = 0; x < 5; x++) {
var r = ("txt" + x);
if(rxArray[i] == r.value){
var s = (r + ".setFocus();");
this.getField(b).setAction("MouseUp", s);
//end
Here is what I know:
The alphabetizing and labeling works fine, but the buttons' MouseUp scripts don't work at all. Nothing happens.
If I change the following piece of the above script:
if(rxArray[i] == r.value){
var s = (r + ".setFocus();");
this.getField(b).setAction("MouseUp", s);
To this:
if(rxArray[i] == txt1.value){
var s = (r + ".setFocus();");
this.getField(b).setAction("MouseUp", s);
Because rxArray[0] does equal the value of txt1 ("A name"), then the MouseUp script for btn0 gets set to:
txt4.setFocus();
So I know that, each time the nested loop runs, the if statement is true, and the setFocus script updates. Until the end of the loop, leaving the setFocus as the last item run. So why doesn't my script work? It should only update the setFocus script IF the array item matches the txt field, and should set it to THAT txt field.
Please please help. I know I'm missing something simple in there somewhere.@Try67:
That's a good question. I was running into some other issues and have revamped my code. Here is what I have in my test file:
A list of five buttons and a list of five text fields. One additional button that sets the focus to the next empty text field to add a new item, and two additional buttons, one that sorts my list alphabetically, and one that unsorts it.
with the following field names
The sort button calls function sortName and the unsort calls function sortNumber (the order of entry).
Here are those scripts in final form:
function sortName() {
//first reset the captions for the buttons to blank
for (var a = 0; a < 5; a++) {
var b = ("btn" + a);
this.getField(b).buttonSetCaption("");
var txt0 = this.getField("t0");
var txt1 = this.getField("t1");
var txt2 = this.getField("t2");
var txt3 = this.getField("t3");
var txt4 = this.getField("t4");
var rxArray = [txt0.value, txt1.value, txt2.value, txt3.value, txt4.value];
for(var m = rxArray.length - 1; m > -1; m--){
if(rxArray[m] == ""){
rxArray.splice(m, 1);
rxArray.sort();
var newArray = [txt0, txt1, txt2, txt3, txt4];
for(var n = newArray.length - 1; n > -1; n--){
if(newArray[n].value == ""){
newArray.splice(n, 1);
for (var i = 0; i < rxArray.length; i++) {
var b = ("btn" + i);
this.getField(b).buttonSetCaption(rxArray[i]);
for (var x = 0; x < newArray.length; x++) {
if(rxArray[i] == newArray[x].value){
var s = ("this.getField('" + newArray[x].name + "').setFocus();");
this.getField(b).setAction("MouseUp", s);
//end
function sortNumber() {
var txt0 = this.getField("t0");
var txt1 = this.getField("t1");
var txt2 = this.getField("t2");
var txt3 = this.getField("t3");
var txt4 = this.getField("t4");
var newArray = [txt0, txt1, txt2, txt3, txt4];
for (var x = 0; x < newArray.length; x++) {
var b = ("btn" + x);
this.getField(b).buttonSetCaption(newArray[x].value);
var s = ("this.getField('" + newArray[x].name + "').setFocus();");
this.getField(b).setAction("MouseUp", s);
//end
As you can see, I've used the array lengths rather than fixed numbers, except when clearing the button values. I use a number there because there is no array to reference and didn't feel like making an array just for that. The number of buttons won't change.
I've also added in a splice() method to remove the blank entries from my arrays when appropriate (making using the array length even more important).
The result of the sort is:
The only quirk I've found in all this is with the Add New button, which calls function addNew, which is:
function addNew() {
var txt0 = this.getField("t0");
var txt1 = this.getField("t1");
var txt2 = this.getField("t2");
var txt3 = this.getField("t3");
var txt4 = this.getField("t4");
var newArray = [txt0, txt1, txt2, txt3, txt4];
for (var i = newArray.length - 1; i > -1 ; i--) {
if (newArray[i].value == "") {
newArray[i].setFocus();
//end
For this, I would have though that running through the array from start to finish looking for the first empty text field and setting the focus to it would have been correct. But that resulted in the last empty text field being focused. So I reversed the for loop to run finish to start, and the result was that the first empty field was focused. Not sure why that is... -
Search database for a matching value
An existing database saves the results from a test as col 1 "serial number" col 2 date etc.
There is now a requirement to search on the serial number and display any results related to it (rows).
I have the database toolset and have started by using the SQL vi to extract the serial number passing a recordset ref number. I am at the point where I now need to select the row for that ref number but was wondering if it would be better to just read in the database to an array and then do a search on the serial number col looking for matching text, obtain the row of the array where matches occur and then display those rows, or is this route really long winded and should stick with the SQL vi?
Thanks
Jack
Labview Version 8.5
Labview Version 8.6
Labview Version 2013
Solved!
Go to Solution.Paul
Thanks for reply and I will do as you suggest and go with the SQL vi. I have a few problems using this vi so far. The first is that to Search say the Status field for Pass or Fail I used the query:-
select Status from TestDetails1 where Status="Pass"
This instruction resulted in an error message. So I tried a different field Ambient where the temperature is logged:-
select Ambient from TestDetails1 where Ambient=23 (ambient temperature at 23 deg C)
This command line worked fine and brought up all instances where 23 occurred.
Also when I use the vi 'Fetch recordset data' I get just the values searched on not th erows to which they belong.
Thanks
John
Labview Version 8.5
Labview Version 8.6
Labview Version 2013 -
Searching 1D array for data present in lookup 1D array.
Hi!,
I have a sorted 1D array of strings(say initial array) and I have
three lookup array of string(say array A, array B and array C). I want
to search the initial array with array A, array B and array C and then
create a new array Final which will contain the elements of array A,
if any, its start index and its last index and then element sof
arrayB, if any found, its start index and its end index and then
element of array C its start index and its end index.
The start index and end index are stored in different indicatrs for
all the three found.
How do I search elements of 1D array with another 1D array?
TIA,
RKThere are probably several ways to do it. One way to do it you would create a For Loop with the initial array run into it with auto-indexing turned off. You would then run array A into it with auto-indexing turned on. Inside of the loop, you would use a Search Array to find the index (if any) of the element in the initial array that matched the auto-indexed element of Array A. You will want to either build an array of only the indexes >=0 (trapping the "not found" -1) or you can autoindex the results and have you later code deal with them.
You will need three of these loops, one for each searching array. Or better, you could push it into a subVI and call it three times.
I hope that this helps!
Bob Young
Bob Young - Test Engineer - Lapsed Certified LabVIEW Developer
DISTek Integration, Inc. - NI Alliance Member
mailto:[email protected] -
who knows how to output some text once labview detects something I want using pattern matching(Vision assistant)?
The text is something like"Yes, this is a coin"
Thanks!I attached a SubVI which I used to place an overlay next to a Pattern, found by a Pattern Match before:
As you can see, you simply pass the image reference and the Array of Matches to the VI along with the String you want to have as an overlay next to the Match.
I also modified your VI a bit, but didn't test it. I created an Array of clusters, each elment containing the template path along with the respective text.
Please note that this is just a hint!
Christian
Attachments:
suggestion.vi 146 KB
Overlay_Txt.vi 24 KB -
Search for a regular expression in a 1D array?
I've got a 1D array of strings, and I want to find the row with "Date: yy/mm/dd" in it. Since yy/mm/dd would not necessarily be the same between runs, I can't look for the row with "Date: yy/mm/dd".
I tried using the Search 1D Array with "Date: " and "Date: *" as my element input, but it didn't find either of 'em.
I don't know where in vi.lib the function would be in, otherwise I'd attempt to mod the function to take regular expressions, and my off-the-cuff search attempt (looping through the array & using Match Regular Expression) had some odd errors and still didn't find the row.
Thanks!What do you define as a "row"? Is each row a single array element? Since your array elements are strings, each array element itself could be a multiline|multirow string itself that might need to be analyzed one row at a time.
To look for patterns:
If you have LabVIEW 8.0 or higher, you can use "Match regular expression". Else you can use "Match Pattern". It really depends how specific you need to be. Are there lines that start with "Date:" but don't contain a formatted date afterwards?
To search for array elements starting with simple string "Date:", use "match first string".
LabVIEW Champion . Do more with less code and in less time . -
"You have connected two terminals of different types" Index Array won't work
So I have a 3D array finally. Now I want to index that array and display the contents of a certain element on a new array. When I index a 2D array, this method works just fine. But when I change it to 3D array, Labview gives me the following error:
You have connected two terminals of different types. The type of the source is string. The of the sink is 1D array of string.
So I'm assuming the 1D arry it speaks of is referring to the indicator array that the index should spout out the contents of the element I'm looking for. And the source string is the 3D array. I've tried changing the dimensions of the 1D array to match that of the source 3D array, but nothing is working yet. I've attached a pic of the problem below.
Attachments:
LVerror.JPG 20 KBThis might be another problem of understanding what the data represents. You are telling the code that you have a 3D array, and you want to pull out a single element, a scalar string, by specifying the row, the column and the page to find the data. But then you are trying to display this single item into a indicator that is a 1D array. You are trying to display a single cell of data, into a column of data. Either replace your 1D array with a scalar string, or when you index your array specify a row or column to display.
Unofficial Forum Rules and Guidelines - Hooovahh - LabVIEW Overlord
If 10 out of 10 experts in any field say something is bad, you should probably take their opinion seriously. -
I have a 1-D array of double inside of a while loop. I would like to control the execution of the while loop based on one of the numeric values in that array (like I would stop the while loop if the numeric value in the array is less than or equal to 0). How should I go about doing this?
I cant link the array directly to the "less than or equal to 0" icon because it requires a single double. Any help would be much appreciated. Thanks.
Jerryqiora wrote:
I cant link the array directly to the "less than or equal to 0" icon because it requires a single double.
Of course you can connect an array to "less than or equal to 0". The output will be a boolean array that you can feed into a "OR array elements" or "AND array elements" to get a true if either (1) at least one array element matches or (2) all elements match, respectively.
qiora wrote:
I would like to control the execution of the while loop based on one of the numeric values in that array (like I would stop the while loop if the numeric value in the array is less than or equal to 0).
If it should be based on one specific element (e.g. element(0) or element(5)), you need to get that element using "index array" and do the comparison.
The implementation will depend on your exact requirement. Your question is quite ambiguous.
LabVIEW Champion . Do more with less code and in less time . -
How to use Labview to output the coordinates from Pattern Matching result
I tried to add some labview commands into the vi program created by IMAQ Pattern Matching scrip to output the coordinates of a target point found in Pattern Matching because i need to do some calculations for the point coordinates and I don't want just to read the values from the IMAQ results on the monitor. Does anyone can help me? Thank you.
Attachments:
PatternMatching1.vi 84 KBI have posted replies to your other postings with your same question, and continue to recomend that you look at some of the LabVIEW tutorials.
I modified the attched program such that it would index the arrays of match information returned and then unbundle the X and Y features of the match and add them to gether as an example of how to access the data programatically.
I hope this helps.
Regards,
Amaury Rolin
NI Applications Engineer
Attachments:
PatternMatching_mod.vi 88 KB -
hi all.
there is a request :
get user input string, and use it as string Pattern regular expression, to match the first string in the memory, and print it.
a JTextField to get user input, and to create regular expression :
//breg is user input string.
if( !breg.endsWith("*") ) breg += "*";
//only alow a-z, A-Z, 0-9, _ , -, . , :, , , \ , /
String reg = breg.replaceAll("\\*",
"[a-zA-Z0-9_ \\\\./\\\\:,\\\\-\\\\\\\\]*").
replaceAll("\\?", "[a-zA-Z0-9_ \\\\./\\\\:,\\\\-\\\\\\\\]");
then in a loop to check the string in an array tha match this regular expression.
But when input \ it will not match.
Is there any problem in my regular expression.
??????????And the base class is
public abstract class SearchInputLabel implements KeyListener{
JWindow dialog = null;
Component onComponent = null;
JPanel jPanel1 = new JPanel();
BorderLayout borderLayout1 = new BorderLayout();
JLabel jLabelS = new JLabel();
JTextField jTextField1 = new JTextField();
Border border1;
* @param onComponent : it should be a JTable, JTree or JList has been added into
* JViewport in JScrollPane
* else there if it is null, it should be setted after it has been
* added into JViewport in JScrollPane
protected SearchInputLabel(Component onComponent) {
this();
if( onComponent != null ){
this.onComponent = onComponent;
onComponent.addKeyListener(this);
protected SearchInputLabel(){
try {
jbInit();
jTextField1.addKeyListener(this);
catch(Exception e) {
e.printStackTrace();
* @param onComponent : if null, there will do nothing
public void setOnComponent(Component onComponent){
if (onComponent != null) {
this.onComponent = onComponent;
onComponent.addKeyListener(this);
private void cancel(){
dialog.setVisible(false);
onComponent.requestFocus();
private void initWin(){
Window w = (Window) ( (JViewport) onComponent.getParent()).getRootPane().
getParent();
dialog = new JWindow(w);
// dialog.getContentPane().setBackground(new Color(180, 215, 165));
dialog.getContentPane().setBackground(new Color(Color.white.getRed() - 50,
Color.white.getGreen() - 50,
Color.white.getBlue() - 50));
dialog.getContentPane().add(jPanel1, BorderLayout.CENTER);
dialog.addWindowFocusListener(new WindowAdapter(){
public void windowLostFocus(WindowEvent we){
cancel();
KeyStroke escape = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false);
Action escapeAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
cancel();
dialog.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escape,
"ESCAPE");
dialog.getRootPane().getActionMap().put("ESCAPE", escapeAction);
protected void showing(){
if( dialog == null )
initWin();
private void jbInit() throws Exception {
border1 = BorderFactory.createEmptyBorder(5,10,5,10);
Border border2 = BorderFactory.createCompoundBorder(
new LineBorder(Color.BLUE), border1);
border2 = BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(SystemColor.inactiveCaption,2),BorderFactory.createEmptyBorder(5,10,5,10));
// dialog.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
// dialog.setUndecorated(true);
jPanel1.setLayout(borderLayout1);
jLabelS.setRequestFocusEnabled(true);
jLabelS.setText(DBManager.getString("Search_for_label") + " : ");
jTextField1.setOpaque(false);
jTextField1.setBackground(Color.GRAY);
jPanel1.setOpaque(false);
jPanel1.setBorder(border2);
jPanel1.add(jLabelS, BorderLayout.WEST);
jPanel1.add(jTextField1, BorderLayout.CENTER);
jTextField1.setBorder(null);
// jTextField1.setFont(new Font("Dialog", Font.PLAIN, 14));
protected int getStringWidth(String str, Font f){
Rectangle2D rec = f.getStringBounds(str,
( (Graphics2D) dialog.getGraphics()).getFontRenderContext());
return (int) rec.getWidth();
}But if there is "\" in table object's value, it can not do well.
So some one can help me to make it response for "\" character
Thanks -
Format of /ByteRange array
I am trying to implement signing for pdf documents. As far as I understand - the digest must be calculated for everything except for the signature's /Content entry contents. The contents can be "isolated" by using /ByteRange array. I just wanted to confirm the format of said array. Is it [offset length offset length]? If so, can space for digest signature be longer that signature itself i.e. if signature is 40 bytes in length (sha1), can space for signature be more than 40 bytes?
Yes, that is correct for the ByteRange array.
The length in the array MUST match the length of the "hole" you leave for the Contents or the signature wont validate.
From: Adobe Forums <[email protected]<mailto:[email protected]>>
Reply-To: "[email protected]<mailto:[email protected]>" <[email protected]<mailto:[email protected]>>
Date: Thu, 22 Sep 2011 00:05:02 -0700
To: Leonard Rosenthol <[email protected]<mailto:[email protected]>>
Subject: Format of /ByteRange array
Format of /ByteRange array
created by Eimantas Vaiciunas<http://forums.adobe.com/people/Eimantas+Vaiciunas> in PDF Language and Specifications - View the full discussion<http://forums.adobe.com/message/3931182#3931182 -
Trouble extending java.util.Arrays
I have written some utility functions for dealing with arrays and I would like to bundle them into a class along with java's built-in array functions (java.util.Arrays). To do this, I tried to extends the class java.util.Arrays like this:
public class ArrayUtils extends java.util.Arrays
/* some static methods */
When I try to compile this with javac (even with no class body between the braces), I get an error "error:Cannot find constructor "Arrays" with matching parameters [JLS 15.12]". Does anyone know what's going on here? Why is the compiler looking for a constructor? And why can't it find one? I would very much appreciate your insight. Thanks. EliDoes anyone know what's
going on here? Why is the compiler looking for a
constructor? And why can't it find one?Conceputually....
Inheritance exists to allow one to inherit from an object. In java objects can be created by using a class. However classes in java do not have to be objects. And you are trying to inherit from something that is not an object.
One of the other uses for class in java is to group a number of convienent functions together. (Grouped functions do NOT represent a class.) That is what java.util.Arrays is.
Technically....
The class java.util.Arrays has a private constructor which means you can't derive anything from it. -
Reading Null Values From Request Object
For a proof-of-concept, I wrote a mini program that has 2 files. File #1 is main.html. There's a javascript function called addNewRowToThisTable that isn't displayed but it basically allows the user to create as many rows in the table as user desires. When the "Submit" button is clicked the file ReadIt.jsp is called and it's supposed to display on the first and last names of the people who had the checkbox for that row checked. The best way to illustrate the problem I'm having is through an example. Let's say there are 3 rows:
[x] Alan Anderson [Add New Row]
[ ] Bob Brady [Add New Row]
[x] Carl Chadwick [Add New Row]
[Submit]
Let's assume that only rows 1 and 3 are clicked. After the form is submitted the JSP will print...
firstNameArr .length = 3
lastNameArr .length = 3
isSelectedArr.length = 2
firstNameArr[0] = Alan
lastNameArr[0] = Anderson
firstNameArr[1] = Bob
lastNameArr[1] = Brady
Unfortunately firstNameArr[1] and lastNameArr[1] should be "Carl", and "Chadwick" respectively. I know the reason why it's failing is because my program relies on the array index of the "isSelected" field to perfectly match up with the "firstName" and "lastName" fields. It's unreliable because if the checkbox for a row is not checked then it won't show up in the JSP String array isSelectedArr. I'm not really sure how to get around this problem. I have 2 ideas at the beginning of solutions but I'm not sure how to follow through on either and I'm also not sure if either is the proper approach to take. My guesses are...
1) There's some way in JSP to use "getParameterValues('isSelected')" to retrieve the full array of "isSelected" items regardless of whether or not they're checked. That would guarantee that my arrays would match up correctly. Unfortunately, I haven't been able to find this.
2) Maybe I can put in some sort of ID in the "isSelected" field that would relate the checkbox to the rest of the data in the row. The problem with this is that I've got a dynamic # of rows due to my addNewRowToThisTable method.
So the bottom line is that I'm thoroughly stumped. If anyone can offer advice I'd be very grateful.
main.html
<html><head><title></title></head><body>
<form method="get" action="ReadIt.jsp">
<table>
<tr>
<td><input type="checkbox" name="isSelected" /></td>
<td><input type="text" name="firstName" /> </td>
<td><input type="text" name="lastName" /></td>
<td><input type="button" value="Add New Row" onClick="addNewRowToThisTable(this)" />
</tr>
<tr>
<td colspan=4><input type="submit" value="submit"></input></td>
</tr>
</table>
</form>
</body></html>
ReadIt.jsp
<%
String[] isSelectedArr = request.getParameterValues("isSelected");
String[] firstNameArr = request.getParameterValues("firstName");
String[] lastNameArr = request.getParameterValues("lastName");
if (firstNameArr != null) System.out.println("firstNameArr .length = " + firstNameArr .length);
if (lastNameArr != null) System.out.println("lastNameArr .length = " + lastNameArr .length);
if (isSelectedArr != null) {
System.out.println("isSelectedArr.length = " + isSelectedArr.length);
for (int i=0; i < isSelectedArr.length; i++) {
System.out.println("firstNameArr["+i+"] = " + firstNameArr);
System.out.println("lastNameArr["+i+"] = " + firstNameArr[i]);
%>it's sort of a kludge, but try this:
your javascript function adds new for fields that get submitted to the servlet. name the checkboxes uniquely with a patterm with said function, say isSelected-1, isSelected-2, isSelected-3... now also name the first and last name fields the same way. fname-1, fname-2, fname-3... lname-1,lname-2,lname-3.
when you get to the page that is supposed to match them up, go through all the request parameters looking for those that start with "isSelected-" take the last char (the index), convert it to an int, and then from your request do:
String first = request.getParameter("fname-" + indexThatWasFound);
String last = request.getParameter("lname-" + indexThatWasFound);in looping over the request for each index recovered from the searching of the request for the isSelected-n values, you will get the matching first and last name.
I TOLD you it was a kludge. -
Problem: Why does this only work for powers of 2?
I wrote this program to create a golf league schedule for, ideally, eight players. However I want it to be flexible enough to permit for other denominations, such as 10 or 12. When I run the program it works perfectly for any number that is a power of 2 (2,4,8,16,32,etc...) but it will not work for other even numbers such as 6,10, or 12. If anyone has any insights it would be most helpful.
*(This is my first post on this forum so if anything looks not quite right or if this post isn't worded exactly how it should be then I apologize in advance)*
Here's the three classes.
public class ScheduleDriver
public static void main(String[] args)
//instance variables
int max; //size of flight matches array
ScheduleMaster master;//instance of class
//get max number of players for flight
System.out.print("Max number of players in this flight:");
max = Keyboard.readInt();
master = new ScheduleMaster(max);
//create weekly schedules for season
master.createSchedule();
//display weekly schedules
master.displayWeekly();
}//end main
}//end ScheduleDriver
public class ScheduleMaster
//instance variables
int maxPlyrs;//maximum number of players in flight
Week[] weeklySchedule;//array of weekly matches
public ScheduleMaster(int plyrs)
//set up instance data and declare array size
maxPlyrs = plyrs;
weeklySchedule = new Week[plyrs];
//set up the size of each week's matches array
for (int pos = 0; pos < plyrs; pos++)
weeklySchedule[pos] = new Week(plyrs);
}//end for
}//end constructor
public void createSchedule()
int count = 0;//index of weeklySchedule array
final int QUIT = -1; //quit value for loop
int flag = 0; //value to continue or exit loop
//for each player A
for (int a = 1; a < maxPlyrs; a++)
//for each opponent of player A
for (int b = (a + 1); b <=maxPlyrs;b++)
//set count/index and reset flag to zero
count = (a - 1);
flag = 0;
//while still haven't found correct week for this match
while (flag != QUIT)
//if at least one of these players are already scheduled
//for a match this week
if (weeklySchedule[count].checkPlayers(a,b) == true)
//if last valid index of array has been reached
if (count == (maxPlyrs - 2))
//reset count/index to zero
count = 0;
else
//incriment count
count++;
}//end if
else
//assign this match to array of matches for week
//and then exit loop
weeklySchedule[count].setMatch(a,b);
flag = -1;
}//end else
}//end while
}//end for
}//end for
//fill in last week/position night
for (int pos = 0; pos < maxPlyrs;pos++)
//set up position match
weeklySchedule[maxPlyrs - 1].setMatch(pos + 1, pos + 2);
//incriment pos
pos++;
}//end for
}//end createSchedule
public void displayWeekly()
//for each week in schedule
for (int pos = 0; pos < maxPlyrs;pos++)
//display header
System.out.print("WEEK " + (pos + 1));
//if pos/index is 0 or even, flight plays front 9
if ((pos % 2) == 0)
System.out.println(" [FRONT 9]");
//else flight plays back 9
else
System.out.println(" [BACK 9]");
//display lines
System.out.println("----------------");
//display week's matches
weeklySchedule[pos].display();
//skip a line
System.out.println("\n");
}//end for
}//end displayWeekly
}//end ScheduleMaster
public class Week
int[] schedule; //array of players involved in matches for week
int max; //max number of players
int count = 0; //number of players currently involved in matches
public Week(int size)
//set up instance data and size of array
max = size;
schedule = new int[size];
}//end constructor
public boolean checkPlayers(int playerA, int playerB)
boolean flag = false; //flag to determine if at least one of
//the players to check are already playing
//this week
//for each element of array
for (int pos = 0; pos < max; pos++)
//if player A matches player already playing this week
if (schedule[pos] == playerA)
flag = true;
}//end for
//for each element of array
for (int pos = 0; pos < max; pos++)
//if player B matches player already playing this week
if (schedule[pos] == playerB)
flag = true;
}//end for
return flag;
}//end checkPlayers
public void setMatch(int playerA, int playerB)
//if array can take more matches
if (count <= (max - 2))
//insert players into array of active players for week
schedule[count] = playerA;
schedule[count + 1] = playerB;
//incriment count of players playing this week by 2
count = count + 2;
}//end if
else
System.out.print("No more matches can be entered!!!");
}//end setMatch
public void display()
//for every even numbered index starting at zero
for (int num = 0;num < max;num++)
//display the player at that position and the next consecutive
//player who will be his opponent for the week
System.out.println(schedule[num] + "VS" + schedule[num + 1] +
//incriment num
num++;
}//end for
}//end display
}//end WeekAh, I have discovered the problem. The reason for the infinite loop was because of the resetting of the counter/index after every successful match entry back to (a - 1). This was causing matches to be put into weeks where they didn't belong, which caused the program to infinitely loop because it couldn't find an appropriate week to place it's next match. The only time the count should be reset back to zero is when a new player A is being processed or the last valid array index has been referenced before an out of bounds exception would be thrown. I'm still not entirely sure why this doesn't occur on powers of 2 but theh again I haven't put too much thought into it having solved the initial problem! :)
Anyways thanks for the input all who posted, much appreciated.
Happy programming!!!!
Maybe you are looking for
-
Macbook pro will only start to windows I do not have bootcamp files.
I am new to mac but good with windows. I just bought my first mac a macbook pro 17. I do need to run windows on it too. I ran all the updates for the OS then started bootcamp. It did tell me to put in a DVD and i foolishly didnot it said it was copyi
-
How do i move a catalog to an new hard drive and keep all of the processed info and collections
Ive recently purchased a new external hard drive, and was wondering how to i move the files so that they retain my collections aswell as the processed info.?
-
What is the expansion for OSMB?
* Automatic Storage Management is a database service that allows efficient management of disk drives. * An ASM instance has two new background process types - one for coordinating the disk group rebalance activity and one for data extent movements (O
-
SCREEN OCCASIONALLY GOES BLACK
Hi: I have a Mini Intel, 512MB Ram. I use Safari and MS Word. Today, after having the Mini for about 9 months, the screen occasionally goes black, and stays that way for about 5-10 seconds. It occurs every so often, like about once every 10 minutes.
-
I went through the process of spec-ing the product, and got to the check-out page. None of the amounts would be listed. No quantity, no prices. I had to use Internet Explorer as my browser to complete my order.