Printing "for" loop interations
Currently I'm stuck. I can't get more than the first interation of the two loops to print out on the same line. I can get the code to print all the interations if I run the loops seperately. But I'm trying to get the output of the two loops to print out side by side.
public class Project
public static void main(String[ ] args)
final double CELSIUS_TABLE_BEGIN = 40.0; // The table's first Celsius temperature
final double CELSIUS_TABLE_END = 31.0; // The table's final Celsius temperature
final double CELSIUS_TABLE_STEP = 1.0; // Increment between temperatures in table
final double FAHRENHEIT_TABLE_BEGIN = 120.0; // The table's first fahrenheit temperature
final double FAHRENHEIT_TABLE_END = 30.0; // The table's final fahrenheit temperature
final double FAHRENHEIT_TABLE_STEP = 10.0; // Increment between temperatures in table
double celsius; // A Celsius temperature
double fahrenheit; // The equivalent Fahrenheit temperature
double celsius1; // The equivalent Celsius temperature
double fahrenheit1; // A fahrenheit temperature
System.out.println(" TEMPERATURE CONVERSION ");
System.out.println("---------------------------------------------");
System.out.println("Celsius Fahrenheit Fahrenheit Celsius");
for (celsius = CELSIUS_TABLE_BEGIN; celsius <= CELSIUS_TABLE_END; celsius -= CELSIUS_TABLE_STEP)
for (fahrenheit1 = FAHRENHEIT_TABLE_BEGIN; fahrenheit1 <= FAHRENHEIT_TABLE_END; fahrenheit1 -= FAHRENHEIT_TABLE_STEP)
fahrenheit = celsiusToFahrenheit(celsius);
celsius1 = fahrenheitToCelsius(fahrenheit1);
System.out.printf( "%6.2fC %9.2fF %12.2fF %10.2fC \n", celsius, fahrenheit, fahrenheit1, celsius1);
System.out.println("---------------------------------------------");
public static double celsiusToFahrenheit(double c)
return (9.0/5.0)*c + 32;
} //end method
public static double fahrenheitToCelsius(double f1)
return (5.0/9.0)*(f1 - 32);
} //end method
} //end class <Project>
Heres an example of how to loop in parallel:
public static void main (String[] args) {
int j = 5;
int k = 10;
for(int m = j, n = k; m > 0 || n > 0; m--, n--) {
//Print m and n
if(m > 0 && n > 0) {
System.out.printf("m := %5d%10sn := %5d", m,"", n);
//Print m
else if (m > 0) {
System.out.printf("m := %5d", m);
//Print n
else {
System.out.printf("%20sn := %5d", "", n);
System.out.println();
}Output:
m := 5 n := 10
m := 4 n := 9
m := 3 n := 8
m := 2 n := 7
m := 1 n := 6
n := 5
n := 4
n := 3
n := 2
n := 1Mel
Similar Messages
-
Strange System.out.print behavior inside a for loop
I'm trying to create a simple ASCII progress bar in the console that would display like this:
|--------------------------------------------|
============================More equal signs would appear as time goes on. At least this is what I want to happen.
Instead, what happens is, none of the equal signs are printed until the very end, after the for loop in which the System.out.print("=") statement is in, has exited.
This is my code (probably more than necessary is shown, but the important part is the for loop):
public void addSomeDiffys(int numOfDiffys, int minInt, int maxInt) {
Diffy currentDiffy;
System.out.println("\nCreating Diffys.");
System.out.println("|--------------------------------------------|");
for (int i=0; i < numOfDiffys; i++) {
currentDiffy = new Diffy(minInt, maxInt);
if ((i/(double)numOfDiffys)*100 % 2 == 0)
System.out.print("=");
diffyList.add(currentDiffy);
System.out.println("\n" + diffyList.size() + " Diffys created.\n");
System.out.println("Sorting according to highest rating...");
Collections.sort(diffyList,Diffy.HIGHEST_RATING_ORDER);
System.out.println("Done.\n");
}I also tried changing the System.out.print("="); to System.out.println("="); This time it works as expected, its just not very pretty...
I get something like this:
|--------------------------------------------|
=
=
=
=
=
=
=
=
=
=
=
=So again, when I use println, rather than print, the equal signs are printed over time, slowly, as the progress increases. When using print, Nothing happens for a long time, and then suddenly they all appear after the for loop has terminated, which makes no sense.
Thanks for any help.When using print, Nothing happens
for a long time, and then suddenly they all appear
after the for loop has terminated, which makes no
sense.
Yes it does make sense! The characters are buffered inside the PrintStream and written when there is a full line to write. You could try a flush() after each = is written but I have no confidence that it will make any difference. -
Editing a for loop to print correctly
I have the following code
public void printReceipts(){
JOptionPane frame = new JOptionPane();
for(int i = 0; i < borrowersList.size();i++){
for(int j = 0; j < books.size();j++){
if(borrowersList.get(i).getLibraryNumber().equals(books.get(j).getLibraryCardNumber())){
milliLate = (tempDate.getTime() - books.get(j).getReturnDate().getTime());
daysLate = (milliLate/ 86400000);
bookDebt = (daysLate * 2);
borrowersList.get(i).setDebt(bookDebt);
JOptionPane.showMessageDialog(frame, borrowersList.get(i).getName() + "\n"
+ borrowersList.get(i).getStreetAddress() + "\n"
+ borrowersList.get(i).getPostalCode() + " "
+ borrowersList.get(i).getCity() + " \n"
+ "\n" + "As of today " + tempDate + " you owe \"The little library \"" +borrowersList.get(i).getDebt() + " kr for the books." + "\n"
+ "\n" + books.get(j).getAuthor() + " " + books.get(j).getTitle() + ", amount due "+ bookDebt +
}which prints borrowers that owe the library money.
The problem is that if a borrower has 2 books, it will print the loop each time with the different book.
i.e
Wile E. Coyote
The Second Valley from the Left
987 65 The Desert
As of today 2007 09 20 you owe "The little library" 300 kr for the books
James Joyces Ulysses, amount due 96:-
Wile E. Coyote
The Second Valley from the Left
987 65 The Desert
As of today 2007 09 20 you owe "The little library" 230 kr for the books
Fyodor Dostoyevsky Crime and Punishment, amount due 134:-
I would like it to print out only once for each borrower
i.e.
Wile E. Coyote
The Second Valley from the Left
987 65 The Desert
As of today 2007 09 20 you owe "The little library" 300 kr for the books
James Joyces Ulysses, amount due 96:- (book line)
Fyodor Dostoyevsky Crime and Punishment, amount due 134:-
Aldous Huxley Brave New World, amount due 70:-
So I need to store all the book lines of each borrower and then call them once all the borrowed books debts have been assigned.Implode wrote:
CeciNEstPasUnProgrammeur wrote:
You could have a method that takes the list of books (or even the borrower) and provides you with a String containting all you want to print... then you'd call this method only once and print out what you want.I thought of this, but I would need each book line to be on a separate line?
public void setPrintDetails(String row){
this.row = row + this.row
Use a StringBuilder/StringBuffer:
private StringBuilder details;
public void setPrintDetails(String row) {
details.append(row).append("\n");
}You could also use the line.separator property instead. -
Print a value outside the for loop.
for (int j=0; j< 4; j++)
String name = "AAAA";
String add="BBBB";
LogManager.logStatus(" NAMe.. ............ "+name);
LogManager.logStatus(" Name ;;;;;;;;;;; "+name);I want to how to print the "Name ;;;;;;;;;;; ". after the for loop.If i declared as
private static String name;
then the output is coming null in 2nd log statement.
But i need the the print of 2nd log should be same as log in 1st . -
Getting the label of a JButton in a for loop
hi,
I doing a project for my course at the minute and im in need of a bit of help. I have set up 1-d array of buttons and i have layed them out using a for loop. I have also added an annoymous action listener to each button in the loop. It looks something lke this:
b = new JButton[43];
for (int i=1; i<43; i++)
b[i] = new JButton(" ");
b.addActionListener(
new ActionListener()
public void actionPerformed(ActionEvent e)
System.out.println("..........");
}); // addActionListener
} // for
I want the "System.out.println( ..." line, to print out the "i" number of the button that was pressed but i cannot figure out how to do it. I cannot put "System.out.println(" "+i);" as it wont recognise i as it is not inside the for loop. Does anyone have any suggestions?
Thanks!!class ButtonExample extends JFrame implements ActionListener{The OP wanted to have anonymous listeners, not a subclassed JFrame
listening to the buttons. I don't know if the following is the best design,
since the poster has revealed so little, but here is how to pass the
loop index to an anonymous class.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonExample {
private JButton[] buttons = new JButton[24];
public JPanel createGUI() {
JPanel gui = new JPanel(new GridLayout(6, 4));
for(int i=0; i<buttons.length; i++) {
final int ii = i; //!! !
buttons[i] = new JButton("button #" + i);
buttons.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt) {
System.out.println("number " + ii);
gui.add(buttons[i]);
return gui;
public static void main(String[] args) {
ButtonExample app = new ButtonExample();
JPanel gui = app.createGUI();
JFrame f = new JFrame("ButtonExample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(gui);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true); -
How to terminate or exit a for loop when the user clicks on stop button
Actually my problem is to stop a loop when i click on stop button.
example:i have two buttons 'start' and 'stop'
in start buttom i wrote a for loop as
dim i as integer
For i=1 To 100000
print i
Next
when i click on start buuton it prints 'i' value up tp 100000.
my question is when i click on 'Stop' button the for loop has to terminate or Exit from the loop and should stops the execution.
Is it possible to termianate or Exit the 'for loop'
PS.Shakeer Hussain
HyderabadI am unable to stop the loop and application not at all allowing to Press the Stop button.
It seems like Hung, any advise ?
Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
btnStop.Enabled = True
btnSelectFile.Enabled = False
btnStart.Enabled = False
btnStop.Focus()
Dim strFileName As String = txtFileName.Text.ToString
Dim strLineText As String
If System.IO.File.Exists(strFileName) = True Then
Dim objReader As New System.IO.StreamReader(strFileName)
While objReader.Peek() <> -1 And stopclick = False
strLineText = objReader.ReadLine()
MsgBox(strLineText, MsgBoxStyle.Information)
Application.DoEvents()
Thread.Sleep(My.Settings("strDelay") * 1000)
'System.Diagnostics.Process.Start(My.Settings("strFireFoxLocation"), strLineText)
End While
End If
End Sub
Private Sub btnStop_Click(sender As Object, e As EventArgs) Handles btnStop.Click
stopclick = True
btnSelectFile.Enabled = True
btnStart.Enabled = True
btnStop.Enabled = False
End Sub
Raman Katwal
Please remember to mark the replies as answers if they help and unmark them if they provide no help -
Excise invoice Print for multiple invoices
Hi All ,
i have developed a z smartform and attached to standard tcode J1IP o/p type J1I0 . The o/p is comming fine when i select one excise no after excecuting tcode J1IP But if selected multiple invoices by checking the checkbox and press print preview or print
button each time it is giving print preview/print diaog. i.e i need to execute print for first invoice and again i have to come back and again it will ask print prview/print dialog for second like wise n times for n no of selected documents .
my requirement is like when i execute tcode J1Ip and when i select multiple invoice i should get only one print preview or print dialog for all documents . how to achieve thisHI friend,
Its simple.
Put all the invoices in a single loop. I think you will be calling the smartform function module for each and every invoice. Don't do like that. Just collect all the invoices in the final table first and after that display the invoices.
I think you can understand what i am saying.
Please try and let me know if you have any queries i will help you.
Thanks,
Sri Hari -
For loop- seems to be just going to last value
Hi guys, carrying on from the thread I created yesterday I have managed to get the socket working between my server and my client, but I am having an issue when re-constructing a string that is being sent from the client to the server. I am talking about the for loop in line 151, which seems to just going straight to the last value of the for loop and thus the board isn't being reconstructed properly.
I'm including both the server and client code which just needs to compiled (host is set to localhost on port 4500) and you will see what I mean after inputting a move from the client. Can anyone spot the problem?
Server code
import java.io.*;
import java.net.*;
import javax.swing.JOptionPane;
class Server
public static void main (String []args) throws IOException
try
Server();
catch (IOException ex)
public static void Server () throws IOException
ServerSocket serverSocket=null;
int portNo=4500;
System.out.println("Starting");
try
serverSocket=new ServerSocket(portNo);
catch (IOException ex)
System.err.println("Could not create socket on port" +portNo);
System.exit(1);
System.out.println("Socket listening");
Socket clientSocket=null;
try
clientSocket=serverSocket.accept();
catch (IOException ex)
System.out.println("Accept failed");
System.exit(1);
PrintWriter out= new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
//coordinates
String coordinates[] [] = new String [8] [8];
for (int i=0;i<8;i++)
for (int j=0;j<8;j++)
if ((i%2!=0)&&(j%2!=0))
coordinates[i] [j]="#";
else if ((i%2!=0)&&(j%2==0))
coordinates[i] [j]=" ";
else if ((i%2==0)&&(j%2!=0))
coordinates[i] [j]=" ";
else
coordinates[i] [j]="#";
coordinates[0][0]="R";
coordinates[0][1]="N";
coordinates[0][2]="B";
coordinates[0][3]="Q";
coordinates[0][4]="K";
coordinates[0][5]="B";
coordinates[0][6]="N";
coordinates[0][7]="R";
for (int i=0;i<8;i++)
coordinates[1]="P";
coordinates[7][0]="r";
coordinates[7][1]="n";
coordinates[7][2]="b";
coordinates[7][3]="q";
coordinates[7][4]="k";
coordinates[7][5]="b";
coordinates[7][6]="n";
coordinates[7][7]="r";
for (int i=0;i<8;i++)
coordinates[6][i]="p";
Board board1=new Board(coordinates);
boolean gameStart=true;
String coord="";
String originX="";
String originY="";
String destinationX="";
String destinationY;
while (gameStart)
System.out.println("trying to read from client");
String input="";
try
input=in.readLine();
System.out.println(input);
catch (IOException ex)
System.out.println("Read failed");
System.exit(1);
originX=input.substring(65);
originY=input.substring(66);
destinationX=input.substring(67);
destinationY=input.substring(68);
coord=input.substring(0,64);
System.out.println(coord);
for (int p=0;p<64;p++)
System.out.println(p);
for (int i=0;i<8;i++)
for (int j=0;j<8;j++)
coordinates [i] [j]=coord.substring(p);
if (i==(Integer.parseInt(originX))&&(j==(Integer.parseInt(originY))))
String piece="";
piece=coordinates [i] [j];
if ((i%2!=0)&&(j%2!=0))
coordinates[i] [j]="#";
else if ((i%2!=0)&&(j%2==0))
coordinates[i] [j]=" ";
else if ((i%2==0)&&(j%2!=0))
coordinates[i] [j]=" ";
else
coordinates[i] [j]="#";
for (int s=0;s<8;s++)
for (int t=0;t<8;t++)
if (s==(Integer.parseInt(destinationX))&&(t==(Integer.parseInt(destinationY))))
coordinates [s] [t]=piece;
board1.printBoard(coordinates);
out.close();
in.close();
clientSocket.close();
serverSocket.close();
class Board
boolean gameStart=true;
public Board()
public Board(String [] [] coordinates)
printBoard(coordinates);
String [] [] getCoOrdinates(String [] [] coordinates)
return coordinates;
public static void update (String coordinates [] [])
printBoard(coordinates);
public static void printBoard(String coordinates[] [])
for (int i=0;i<8;i++)
for (int j=0;j<8;j++)
System.out.print(coordinates[i][j]);
System.out.println();
}Client code:import java.io.*;
import java.net.*;
import javax.swing.JOptionPane;
class Client
public static void main (String [] args) throws IOException
Socket socket=null;
PrintWriter out=null;
BufferedReader in=null;
String serverLocation="localhost";
int portNo=4500;
System.out.println("Starting");
try
socket= new Socket (serverLocation,portNo);
out= new PrintWriter(socket.getOutputStream(),true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
catch (UnknownHostException ex)
System.out.println("Cannot find" + serverLocation);
System.exit(1);
catch (IOException ex1)
System.out.println("IO problem");
System.exit(1);
System.out.println("Connected");
//coordinates
String coordinates[] [] = new String [8] [8];
for (int i=0;i<8;i++)
for (int j=0;j<8;j++)
if ((i%2!=0)&&(j%2!=0))
coordinates[i] [j]="#";
else if ((i%2!=0)&&(j%2==0))
coordinates[i] [j]=" ";
else if ((i%2==0)&&(j%2!=0))
coordinates[i] [j]=" ";
else
coordinates[i] [j]="#";
coordinates[0][0]="R";
coordinates[0][1]="N";
coordinates[0][2]="B";
coordinates[0][3]="Q";
coordinates[0][4]="K";
coordinates[0][5]="B";
coordinates[0][6]="N";
coordinates[0][7]="R";
for (int i=0;i<8;i++)
coordinates[1][i]="P";
coordinates[7][0]="r";
coordinates[7][1]="n";
coordinates[7][2]="b";
coordinates[7][3]="q";
coordinates[7][4]="k";
coordinates[7][5]="b";
coordinates[7][6]="n";
coordinates[7][7]="r";
for (int i=0;i<8;i++)
coordinates[6][i]="p";
Board board1=new Board(coordinates);
boolean gameStart=true;
String coord="";
while (gameStart)
String originMove=JOptionPane.showInputDialog(null,"Client Origin Move","Enter in origin of piece",JOptionPane.QUESTION_MESSAGE);
String destinationMove=JOptionPane.showInputDialog(null,"Client Destination Move","Enter in destination of piece",JOptionPane.QUESTION_MESSAGE);
for (int i=0;i<8;i++)
for (int j=0;j<8;j++)
coord=coord+coordinates[i][j];
System.out.println(coord);
out.println(coord+originMove+destinationMove);
System.out.println("passed");
out.close();
in.close();
socket.close();
class Board
boolean gameStart=true;
public Board()
public Board(String [] [] coordinates)
printBoard(coordinates);
String [] [] getCoOrdinates(String [] [] coordinates)
return coordinates;
public static void update (String coordinates [] [])
printBoard(coordinates);
public static void printBoard(String coordinates[] [])
for (int i=0;i<8;i++)
for (int j=0;j<8;j++)
System.out.print(coordinates[i][j]);
System.out.println();
}Cheers,
Benjverd wrote:
p595659 wrote:
1) I don't think that even compiles. Since you're catching IOException, your throws clause is bogus--that method can never throw IOE.I have removed the try and catch statements in the main method. I cannot, however get rid of the throws IOException in the main method other my program won't compile.Right. Don't catch it, since you're not handling it. Just declare that it throws it.
Indeed, this is what I have done :)
>
3) Don't name methods the same as your class name.See answer to 4.
4) Start method names with lowercase letters.
try
serverSocket=new ServerSocket(portNo);
catch (IOException ex)
System.err.println("Could not create socket on port" +portNo);
System.exit(1);
ServerSocket is a part of the java.net package. I am just creating an instance of it. http://java.sun.com/j2se/1.4.2/docs/api/java/net/ServerSocket.html
I don't know what you're talking about. You had a class named Server and a method named Server. That's confusing.Changed- I didn't spot it, so I have named it startServer now.
>
5) There's almost no point to ever calling System.exit. Here, again, since you're not
actually handling the exception, don't bother catcing it.Sorry, but this was how I was taught when I started java. My understanding is that System.exit properly terminated applications so this freed up memory so it's abit of a habit of mine, is this wrong to do in this instance?Calling it in response to an exception is wrong. It's not that method's job to decide to shut down the VM. Just let the exception bubble up (or else handle it properly). You do not need to call System.exit to free up memory. It's freed up automatically when the VM exits. The OS takes care of that, without any help from you.Removed- thanks for clearing that up for me :)
JacobsB wrote:
line 151 of the server code or client code?Line 151 of my server code. My client is working fine up to this step of the programming I have done- it's just the server part I'm having issues with. You can compile and run the client fine- you can compile the server but as explained in the original post, I'm having a logical error when redrawing the board when it gets the 68 charecter string from the client (first 64 charecters are for the board, then the original position (x and y respectively), followed up the new position (x and y respectively again).
I'm including an updated version of the code, after all the comments above so we have an updated version for trying to solve the problem I'm having. The client code does not need to be updated as it has not changed yet, so you can use the code in the original post.
import java.io.*;
import java.net.*;
import javax.swing.JOptionPane;
class Server
public static void main (String []args) throws IOException
startServer();
public static void startServer () throws IOException
ServerSocket serverSocket=null;
int portNo=4500;
System.out.println("Starting");
try
serverSocket=new ServerSocket(portNo);
catch (IOException ex)
System.err.println("Could not create socket on port" +portNo);
ex.printStackTrace();
System.out.println("Socket listening");
Socket clientSocket=null;
try
clientSocket=serverSocket.accept();
catch (IOException ex)
System.out.println("Accept failed");
ex.printStackTrace();
PrintWriter out= new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
//coordinates
String coordinates[] [] = new String [8] [8];
for (int i=0;i<8;i++)
for (int j=0;j<8;j++)
if ((i%2!=0)&&(j%2!=0))
coordinates[i] [j]="#";
else if ((i%2!=0)&&(j%2==0))
coordinates[i] [j]=" ";
else if ((i%2==0)&&(j%2!=0))
coordinates[i] [j]=" ";
else
coordinates[i] [j]="#";
coordinates[0][0]="R";
coordinates[0][1]="N";
coordinates[0][2]="B";
coordinates[0][3]="Q";
coordinates[0][4]="K";
coordinates[0][5]="B";
coordinates[0][6]="N";
coordinates[0][7]="R";
for (int i=0;i<8;i++)
coordinates[1]="P";
coordinates[7][0]="r";
coordinates[7][1]="n";
coordinates[7][2]="b";
coordinates[7][3]="q";
coordinates[7][4]="k";
coordinates[7][5]="b";
coordinates[7][6]="n";
coordinates[7][7]="r";
for (int i=0;i<8;i++)
coordinates[6][i]="p";
Board board1=new Board(coordinates);
boolean gameStart=true;
String coord="";
String originX="";
String originY="";
String destinationX="";
String destinationY;
while (gameStart)
System.out.println("trying to read from client");
String input="";
try
input=in.readLine();
System.out.println(input);
catch (IOException ex)
System.out.println("Read failed");
ex.printStackTrace();
coord=input.substring(0,64);
originX=input.substring(64,65);
originY=input.substring(65,66);
destinationX=input.substring(66,67);
destinationY=input.substring(67,68);
System.out.println(coord);
for (int p=0;p<64;p++)
System.out.println(p);
for (int i=0;i<8;i++)
for (int j=0;j<8;j++)
coordinates [i] [j]=coord.substring(p);
if (i==Integer.parseInt(originX)&&(j==(Integer.parseInt(originY))))
String piece="";
piece=coordinates [i] [j];
if ((i%2!=0)&&(j%2!=0))
coordinates[i] [j]="#";
else if ((i%2!=0)&&(j%2==0))
coordinates[i] [j]=" ";
else if ((i%2==0)&&(j%2!=0))
coordinates[i] [j]=" ";
else
coordinates[i] [j]="#";
for (int s=0;s<8;s++)
for (int t=0;t<8;t++)
if (s==(Integer.parseInt(destinationX))&&(t==(Integer.parseInt(destinationY))))
coordinates [s] [t]=piece;
board1.printBoard(coordinates);
out.close();
in.close();
clientSocket.close();
serverSocket.close();
class Board
boolean gameStart=true;
public Board()
public Board(String [] [] coordinates)
printBoard(coordinates);
String [] [] getCoOrdinates(String [] [] coordinates)
return coordinates;
public static void update (String coordinates [] [])
printBoard(coordinates);
public static void printBoard(String coordinates[] [])
for (int i=0;i<8;i++)
for (int j=0;j<8;j++)
System.out.print(coordinates[i][j]);
System.out.println();
}Ben -
Hello,
I'm using the Pass/Fail count set to one Pass to capture an event generated by my DUT. I originally used a numerical compare step with the Looping type of Pass/Fail count to accomplish this. Unfortunately the implementation changed and now I need to execute a few steps that can not be combined within one code module as before. Nor can these steps be put into a subroutine. One of the steps executes a .NET asembly and I haven't figured out how to pass the reference to the subroutine. When the subroutine is intered the reference is lost and the methode does not execute correctly.
I have an evaluation function the exits the loop when the expected conditions are met. Everything works except for the Overall Pass/Fail result of the For loop. If the loop exits due to the first numerical compare test passing, I want the loop overall execution to report as "Passed". If the loop reaches it's predetermined number of iterations, the overall result needs to report as "Failed". It would also be nice to have the radio button functionality of "Record Result of Each iteration". Some conditions require a wait over a minute for the event to occur and I don't want to generate needless data for the report.
Currently I get the pass/fail status for each For loop iteration, but only "Done" for each loop iteration. I don't want the initial few failures to cause the test to fail.
Does anyone know how to do this? Suggestions?
Thanks,I have 2 steps in the loop that can not be combined into one step. This forces me to implement the behavior in some form of loop. A While Loop could be an option. I would need to pass the Step.Result.Status from the Multiple Numerical compaire step to the condition of the While Loop. I tried to use the Step.TS.ID without success. Some form of reference to the numerical compare step would be needed. I'm using a For Loop as I do want to limit the number of iterations of the loop. In the case where the loop iterations are reached, the event I am trying to detect did not occur at the correct time and a failure needs to be reported.
I came up with something based on my comments in the second post:
1) To start with I configured a Locals.ForLoop_5 variable. This is used to set the limit on the loop iterations and for comparison after the loop has finished executing. More on that later.
2) The first step inside the loop invokes a method within a .NET assembly that has been packed in a DLL This method gets the required data from the DUT and stores it to a text file.
3) The next step is the Multiple Numeric Limit step. This step invokes a VI that extracts the data from the text file. This step has been customized in several ways.
i) In Run Options, the Results Recording Option was disabled. This prevents recording of "Failed" while the loop executes when waiting for the event to happen.
ii) In Run Options, the Step Failure Causes Sequence Failure is unchecked. Same reasoning as i) These steps are not true failures.
iii) A Post Action is configured to go to the nexxt step after the For Loop End step On Condition True with the logic of Step.Result.Status == "Passed". This causes the loop to exit when the first "Passed" is encountered which corrolates with the event I'm trying to detect. On Conditon Fail remains set to default.
4) The step after the For Loop End is an expression step with everythin set to default except for the Status Expression logic set to: Locals.Loopindex < Locals.ForLoop_5 ? (Step.Result.Status = "Passed") : (Step.Result.Status = "Failed"). This step performs the overall Pass/Fail reporting for the For Loop. If the number of loop iterations is less than the maximum it could have only gotten there by the previous logic triggered by the numerical compare passing, therefore "Passed". If the loop index has reached the limit, then the event was not detected, therefore Failed.
I have tested this work around with success, it just a pain to now have to implement this on my 40 some odd For Loops.
If there is a better way, I'd still like to hear it. -
Getting a for loop inside a while loop
I've been having problems with the code below. I'm trying to get the 'while' loop to work so that the program will continue to run after a user types in a sentence. This is supposed to print out how many times a letter has been typed when a sentence has been put in, but it's not working right. It just keeps adding the first sentences numbers together even when a new sentence is typed out. I don't know what I'm doing wrong with this 'while' loop.
import java.util.Scanner;
import java.util.*;
public class Count
public static void main (String[] args)
String phrase; // a string of characters
int countBlank; // the number of blanks (spaces) in the phrase
int length; // the length of the phrase
int countA = 0; // the number of a's in the phrase
int countT = 0; // the number of t's in the phrase
int countE = 0;
int countS = 0;
char ch; // an individual character in the string
Scanner scan = new Scanner(System.in);
// Print a program header
System.out.println ();
System.out.println ("Character Counter");
System.out.println ();
// Read in a string and find its length
System.out.println ("Enter a sentence or phrase ('quit' to quit): ");
phrase = scan.nextLine();
length = phrase.length();
// Initialize counts
countBlank = 0;
// a while loop to allow user to keep entering phrases
while (true)
String line=scan.nextLine();
System.out.println("Type quit to quit or enter a new phrase.");
if(line.equals("quit"))
break;
// a for loop to go through the string character by character
// and count the blank spaces
for(int i = 0; i < phrase.length(); i++)
ch = phrase.charAt(i);
switch (ch)
case ' ': countBlank++;
break;
case 'a':
case 'A': countA++;
break;
case 't':
case 'T': countT++;
break;
case 'e':
case 'E': countE++;
break;
case 's':
case 'S': countS++;
break;
// Print the results
System.out.println ();
System.out.println ("Number of blank spaces: " + countBlank);
System.out.println ("Number of A's: " + countA);
System.out.println ("Number of T's: " + countT);
System.out.println ("Number of E's: " + countE);
System.out.println ("Number of S's: " + countS);
System.out.println ();
}Ok well I don't really understand what you're saying, but here's an improved version of my code and I can get it to work, but I don't know how to turn the "do while" loop into just a "while" loop.
import java.util.Scanner;
public class Count3
public static void main (String[] args) {
String phrase; // a string of characters
int countBlank=0; // the number of blanks (spaces) in the phrase
int length; // the length of the phrase
char ch; // an individual character in the string
int countA=0;
int countE=0;
int countS=0;
int countT=0;
String quit = new String("quit"); //String wasn't initialized
Scanner scan = new Scanner(System.in);
// Print a program header
System.out.println ();
System.out.println ("Character Counter");
System.out.println ();
do { //do-while loop
// Read in a string and find its length
System.out.println("Enter a sentence or phrase, or type \"quit\" to quit: ");
phrase = scan.nextLine();
length = phrase.length();
// a for loop to go through the string character by character
// and count the blank spaces, a's, e's, s', and t's
for (int i = 0; i <= length-1; i++) {
ch = phrase.charAt(i);
switch (ch) {
case ' ': countBlank++;
break;
case 'a':
case 'A': countA++;
break;
case 'e':
case 'E': countE++;
break;
case 's':
case 'S': countS++;
break;
case 't':
case 'T': countT++;
break;
// Print the results
System.out.println ();
System.out.println ("Number of blank spaces: " + countBlank);
System.out.println ("Number of a's: " + countA);
System.out.println ("Number of e's: " + countE);
System.out.println ("Number of s's: " + countS);
System.out.println ("Number of t's: " + countT);
System.out.println ();
countA=0; countE=0; countS=0; countT=0; countBlank=0;
}while (!(phrase.equalsIgnoreCase(quit)));
}//end main
}//end class Count -
Closing a serial port after executing a for loop of write and reads.
Hello,
Labview is opening and then closing each write to the port. I have tried to leave the close outside of the for loop, but labview wont allow it. What do I need to change to make all the writes and reads execute on 1 open and close of the serial port.?
Thanks.
Attachments:
Controller.vi 27 KBJ_es--
The program that you posted looks to be ok for the most part, you might consider putting an open after your configure (but that's trivial). The other thing that is a minor issue is the loop tunnel coming out of your for loop is currently being auto-indexed. This function is used to index data for each interation of the loop. You are using a static address (not an array) and so you don't need this. If you right-click and remove the auto-index the broken wire will go away. Other than that it should be ok.
I would suggest looking at one of the shipping examples that come with LabVIEW. "Basic Serial Read and Write" is essentially the same thing that you are doing and is tested here and might save you a bit of time. Anyway, take a look if you have a second. Best of luck with your application!
John H.
Applications Engineer
National Instruments
http://www.ni.com/support -
How to use for loops with Multiple Initializers and Incrementers
I found that my for loop is printing out wrong, because I am using two for loops. I have searched but all I can find out is you can't use multiple inializers and increments, does anyone know how to get around this? How would I use an array for this?
Thanks very much for your help.
import java.util.Random;
import java.util.Arrays;
/** Generate numnodes value for random integers in the range 0..499. */
public final class RandomInteger {
public static final void main(String... aArgs){
log("Generating 6 random integers in range 0..499.");
int numnodes = 6;
//Randomly generate a number between 0 and 499 for the x and y coordinates for the nodes
Random randomGenerator = new Random();
for (int x = 0; x < numnodes; ++x) {
int randomInt = randomGenerator.nextInt(500);
Random randomGenerator2 = new Random();
for (int y = 0;y < numnodes; ++y) {
int randomInt2 = randomGenerator2.nextInt(500);
log("Generated : " + randomInt + " " + randomInt2);
log("Done.");
}Sorry that code works, but I want to use both my x and y coordinates to get a random number from 0 to 499 in both of them, then I want to do some comparisons of the values, then return it to another function. As it stands now, I get the wrong results when I run it, as you can see at the bottom.
Thanks very much for your help. I have been stumped all mornign on this and have looked everywhere trying to find an example. I don't won't to use math random. I am on a tight deadline to finish and at the rate I am going, I will not complete it.
/** Generate numnodes value for random integers in
the range 0..499. */
public final class RandomInteger {
public static final void main(String... aArgs){
log("Generating 6 random integers in range
0..499.");
int numnodes = 6;
//Randomly generate a number between 0 and 499 for
the x and y coordinates for the nodes
Random randomGenerator = new Random();
for (int x = 0; x < numnodes; ++x) {
int randomInt = randomGenerator.nextInt(500);
Random randomGenerator2 = new Random();
for (int y = 0;y < numnodes; ++y) {
int randomInt2 = randomGenerator2.nextInt(500);
log("Generated : " + randomInt + " " + randomInt2);
log("Done.");
private static void log(String aMessage){
System.out.println(aMessage);
Output:
--------------------Configuration:
<Default>--------------------
Generating 6 random integers in range 0..499.
Generated : 98 254
Generated : 98 347
Generated : 98 359
Generated : 98 25
Generated : 98 277
Generated : 98 148
Generated : 416 401
Generated : 416 165
Generated : 416 354
Generated : 416 169
Generated : 416 144
Generated : 416 354
Generated : 295 158
Generated : 295 138
Generated : 295 349
Generated : 295 324
Generated : 295 18
Generated : 295 193
Generated : 197 451
Generated : 197 416
Generated : 197 480
Generated : 197 33
Generated : 197 490
Generated : 197 494
Generated : 324 412
Generated : 324 490
Generated : 324 213
Generated : 324 386
Generated : 324 467
Generated : 324 163
Generated : 379 180
Generated : 379 446
Generated : 379 314
Generated : 379 52
Generated : 379 113
Generated : 379 271
Done.
Process completed. -
For loop in a scriptlet tag style
For loops in a a XML style JSP tags won't work.
Please have a look at the following code snippets:
Works:
<%
for (int i = 0; i < 5; i++) {
out.print(i);
%>
Works:
<jsp:scriptlet>
int i = true;
while (i) {
out.print(i);
i = false;
</jsp:scriptlet>
Won't work
<jsp:scriptlet>
for (int i = 0; i < 5; i++) {
out.print(i);
</jsp:scriptlet>I am using tomcat-5.5.17
error:
org.apache.jasper.JasperException: /test/index.jsp(7,15) Unterminated <jsp:scriptlet> tagThank you,
Although not entirely right, but you sure put me in the right direction, if anybody wants to know the (best) solution:
<jsp:scriptlet>
<![CDATA[
for (int i = 0; i < 5; i++) {
out.print(i);
]]>
</jsp:scriptlet> -
Hi here is a segment of my code:
public void vietaLoop(){
int loopParameter;
final int START_CONDITION=0;
final long END_CONDITION=no_Terms;
double initialTerm = Math.sqrt(2)/2;
double newTerm;
double previousTerm;
/* calculate the next PI term */
newTerm = Math.sqrt(2+previousTerm);
/* assign new term to previous */
previousTerm = newTerm;
for (loopParameter = START_CONDITION; loopParameter < END_CONDITION;
loopParameter++)
/* Prints the new PI approximation */
System.out.println(+ newTerm);
im having loads of trouble, above is how far I have got but I'm unable to 'call' the previous calculation to be included in the next calculation to calculate the new term of PI. as a result all my output is the same..... ie = 1.645.......
If anyone could point me in the right direct... its really getting to me. Thanks.Hi there,
Is this what you want?
import java.awt.*;
class vietaLoop
public static void main(String[] args)
int loopParameter;
int no_Terms=10;
int START_CONDITION=0;
int END_CONDITION=no_Terms;
double initialTerm=Math.sqrt(2)/2;
double newTerm;
double previousTerm;
previousTerm=initialTerm;
for (loopParameter=0; loopParameter<END_CONDITION;loopParameter++)
newTerm = Math.sqrt(2+previousTerm);
previousTerm = newTerm;
System.out.println(newTerm);
}If you use it as a function, set it as
public double vietaLoop(int noTerm)
Then you can change no of term for looping.
Regards
John -
Need help with basic "for" loops!
Here is my prompt for class:
Write a program that prompts the user to enter a sentence from the keyboard using JOptionPane.showInputDialog.
The program will print the characters back with the first letter of each word changed from lower case into upper case. If you have a capital letter in the original line and it is not the first letter of a word, then this letter should be switched from upper case to lower case. The only capital letters that should appear in the line must be the beginning letter of every word in the line. All other characters will remain the same.
I figured everything out except for one part. How do I make the first letter of each word change from lower case into uppercase? How do I switch a letter that is uppercase in the middle of a word to lowercase? Last but not least, how do I make sure that the only capital letters in the sentence are the first letter of each word?
I need to do this using for Loops, charAt(), and if/else statements because this is just an intro class. I just can't figure this last part out! Help please!String words = ...;
StringBuilder builder = new StringBuilder();
for (int i = 0; i < words.length; i++) {
char c = words.charAt(i);
boolean isUpper = Character.?(look up the methods in java.lang.Character)
boolean isLetter = ? (there are actually 2 ways to do this. Hint: you can use <= and >= and && to solve this)
if (!isLetter) {
continue;
} else {
// check if this is the start of the word. How do you know that you are at the start of a word?
if (!isUpper && isStartOfTheWord) c = Character.toUpperCase(c); //Hint: there is a way you can do this with x + y
else if (isUpper) //make c lower case
builder.append(c);
return builder.toString();
Maybe you are looking for
-
How do I change the phone number associated with my iPad Air?
During initial setup of my iPhone 5S, I mistakenly assigned that phone number to my iPad Air. How do I change that number to another iPhone my wife has for iMessaging purposes?
-
Hp photosmart c6180 not printing from new imac? not sure what the problem is?
Just got a new iMac and unable to print to my HP Photosmart C6180 All - in - one. Its recognising the printer but saying its not connected? And offline? Not a clue!
-
Is there a way to upload Photos to iCloud in small groups
The new Photos app is causing havoc with our home Internet. It seems to be hanging up and working, if at all, very slowly. Apple Support didn't seem to see a problem. But when the upload to iCloud option is turned on, our home Internet speed goes fro
-
How do I get a download since I don't have my start up disc for AirPort Extreme 802.11n
How do I download to start using AirPort Extreme 802.11n. I can't find my start up disc. and don't see any downloads on Apples website. Then how do I hook it up to work with my Westell modem?
-
Dear All , kindly help me out in this issue as i have done the I,V for a P.O but IV is still tobe done for freight as Rs2000/- is to be paid through MIRO, But in invoice The actual freight is Rs 4000/- Kindly guide me tha