Make a program wait

Hi, I am new to Java, hence the forum, I was hoping someone could help, I was hoping to find a method or a way to make a program wait for the return key to be pressed, similar to the getch() function in C++ I have messed around a little with System.in.read() but I get an exception and I have no idea how to handle exceptions, any help would be greatly appreciated.
Thanks in advance.
UnclePunker

you can simply do this by waiting in a while loop
you have to import java.io.*;
insert this into the main
boolean goon = true;
String answer = "";
while(goon)
//your code for number generation
System.out.println("Result of"+num1+" + "+num2+" ?");
BufferedReader in =  new BufferedReader(new InputStreamReader(System.in));
try{
answer = in.readLine();
catch(Exception e){
System.out.println("Error: "+e.toString());
//the string answer contains the input from the console
//if you want to compare it to an integer do this
int numnber = 0;
try{
number = Interger.parseInt(answer);
catch(Exception e){
System.out.println("Error: "+e.toString());
//code to compare the answer to the result

Similar Messages

  • How do I make a program wait for a set amount of time?

    Basically, I want there to be some amount of lag after a repaint, so how do I do that? I want it to wait a fifth of a second, basically. Is there a quick way to do this?
    By the way, the program is not running on a timer, so I can't just have the timer stop.

    didn't see that:
    you need to use a thread
    public class Something implements Runnable
    Thread t;
    public Something()
    t = new Thread(this);
    t.start();
    public void run()
    while(true)
    //your stuff goes here
    try
    t.sleep(200);
    } catch(InterruptedException exc) { ; }

  • How do I make my program wait for tasks to execute

    I want to write a few java classes to do things for me, namely:
    1) Create a directory on a local machine which is named to the current date - that I can do with Calendar and String
    2) Download the latest committed code from SVN - I suppose I will have to use a process to call SVN from command line. Does Java have a local process caller? I'm familiar with Qt's QProcess, but I'd like to do this with Java.
    3) email confirmation that the tasks have executed - I can use javax.mail for that.
    If anyone has comments on 2, I'd like to know, please. My greatest concern is how to make sure that steps 1-3 execute sequentially. How do I get that right?

    System.exec(...)
    ProcessBuilderAlso read [When Runtime.exec() wont|http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html]
    It's equally applicable to processes launched by ProcessBuilder.
    db

  • Best way to make program wait for input from NI USB 9162?

    Hi, I'm somewhat new to Labview, but through all the tutorials and online help I'm still having trouble getting this to function properly.
    The USB adapter is hooked up to a network cable split into single wires reading in a voltage coming through several seperate oscillators.  
    Testing in the lab, the program included below works fine when I run the program, then quickly administer a shock to the table.  In the real world scenario though, I'm trying to make the program wait to record data until the first shock reaches the first oscillator before recording data, but I just can't seem to find an easy way to make this work.
    Attatched is an example of the program.  Any help would be greatly appreciated.  Thank you. 
    Attachments:
    Acq&Graph Voltage-Int Clk-rh-tt-1.vi ‏56 KB

      Hi,
    I think I have the answer you're looking for! Please see the attached VI.
    I moved the graph indicator inside the "true" case of the case structure. Before, your VI was sending data  to the graph from an empty timestamp constant with each iteration of the "false" case. Now the VI only sends data to the graph if a true is read.
    If you're wondering why it takes a bit of time for your graph to stop updating before it stops writing new data, it's because you're filling up a buffer of sampled data by using a queue. If you're writing to the buffer faster than you're reading from the buffer, you may encounter an "overflow" situation when the queue gets full. To avoid this, you might consider using a notifier rather than a queue. It's the exact same thing as a queue, but it gives you only the most recent value, allowing new values to overwrite old values.
    Hope this helps.
    Regards,
    Dan Richards
    Certified LabVIEW Developer
    Attachments:
    producer consumer DAQmx threshold.vi ‏57 KB

  • How do i make the program hold after it has created a JFrame

    I have created a JFrame with which the user shall login to a server. I call this JFrame from my main method (the JFrame-class is in a separate file). My problem is that after the login-window is created and set visible, my main method continues, i would like it to wait until the user have logged in before running the rest of the code.
    this i my main method:
    new LoginWindow();
    System.out.println("Logged in: "+Session.isLoggedin()+
                    "\nUsername: "+Session.getUsername());Session.isLoggedin() returns a boolean, true if user is logged in and otherwise false. class LoginWindow extends JFrame.
    i have tried to use a while-loop to solve my problem:
    while(!Session.isLoggedin()) { }and also
    whiel(true){
        if(Session.isLoggedin())
            break;
    }these while-loops never breaks, i have waited for about 3 min after successful login.It isn't because Session.isLoggedin() returns false, it does return true after a successful login (i've checked).
    the funny thing however is if i print something in the while-loop i does break when login is finished
    example:
    whiel(true){
        System.out.println(Session.isLoggedin());
        if(Session.isLoggedin())
            break;
    }this code makes the program wait until the login-phase is complete but i don't want it to print "text" a few thousand times while the user is logging in. (i've used "hej" as output aswell)
    Since i have no idea how long it will take for a user to log in i can't use the System.sleep(value) method.
    I would really appreciate any help
    Thanks in advance
    //Oscar

    SnuShogge wrote:
    I am still curious about why the while-loop only breaks if i print something using System.out.println(""), i didn't think that would make a difference since the break-statement remains the same.In general you should avoid trying to use while (true) or its variants in a Swing GUI as it often messes with the EDT, the main thread that renders the GUI graphics and interacts with the user.
    My problem i however partially solved by using a JDialog instead of a JFrame. I am planning on using JFrame later in the program so the problem might come back to haunt me if it isn't solved.This may not be a great idea. Usually an application has one single JFrame. Most other distinct windows a dialogs of one sort or another and should be JDialogs, not JFrames. Often better still is to use a CardLayout to swap JPanels or other components.

  • How do you make the program repeat itself?

    How would I make it so that when the if statement at the end of the code the program starts over from the begining?
    Any help appreciated. Here is the code if you wanna see it.
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    class SuperTester{
         public static void main ( String[] args ){
         // Create array that will hold deck
         Deck[] decko = new Deck[52];     
         // Fill the array with a deck
         decko = Deck.makeDeck();
         // Print new deck
         System.out.println( "PRINT NEW DECK" );
         System.out.println( "" );
         Deck.printDeck( decko );
         // Shuffle the deck ( simulated riffle shuffling )!
         decko = Deck.shuffleDeck( decko );
         // Print the shuffled deck
         System.out.println( "" );
         System.out.println( "PRINT SHUFFLED DECK" );
         System.out.println( "" );
         Deck.printDeck( decko );
         // Print first 5
         System.out.println( "" );
         System.out.println( "PRINT TOP 5" );
         System.out.println( "" );
         Deck.printFirstFive( decko );
         // Print single card
         System.out.println( "" );
         System.out.println( "PRINT SINGLE CARD" );
         System.out.println( "" );
         Deck.printCard ( decko [2] );
         System.out.println( "" );     
         BufferedReader in = new BufferedReader( new InputStreamReader (System.in));
         int input;
         System.out.println( " Do you want to re-run program? " );
         System.out.println( " Push 1 for yes " );
         System.out.println( " Push 2 for no " );
         System.out.println( "" );
    try
         input = Integer.parseInt( in.readLine() );
    catch( Exception e ){
    if ( input == 1 ){
    //WHAT DO I PUT HERE TO MAKE THE PROGRAM REPEAT ITSELF?
         } // end method
    } // end class

    So i should just do something like?
    int x = 0;
    while (x == 0){
    //code
    if (inpu == 1) {
        x == 0;
    }else{ x == 1; }                                                                                                                                                                                                                                                       

  • How to make my program case - in sensitive?

    Hi,
    Iam writing a SELECT query in report for retrieving the address number by giving address details like street, city and post code.But my program is case sensitive such that if the user inputs either in Upper Case or Lower Case, it will not work.
    For eg: suppose the city is Cape Town. If the user inputs like CAPE TOWN or cape town ( via Selection Screen ), then it won't work.
    How can i  make my program case- in sensitive?? please suggest..

    This is possible. I have done something similar to it in my search programs.
    For this we need to make a subroutine. In this subroutine we first need to convert the case into upper case using
    TRANSLATE string TO UPPER CASE.
    then prefix and postfix this string with &,
    _and if this does not work then we have to break the srting entered by the user on basis of spaces and prefix and postfix it with &. _
    Now pass this string to the query and it will definitely get the result.

  • How to make my program faster?

    I have a program which produces two elements array. In normally the program ends in microseconds, however when I organize my program to send the array as a data to DAQ.mx write and the array will be the voltage output from my NI USB-6012 DAQ, my program ens in 40 seconds. How can I make my program faster? Is there any solution?
    I have attached the normal program and with DAQ.vis.
    Attachments:
    step step 1.vi ‏15 KB
    step step 2.vi ‏34 KB

    Program 1 runs 5 times and program 2 runs 41 times per loop. the total number of inner iterations is 25 vs. 1681 for a 67x difference.
    Program 1 and program 2 have no timing information, thus spin at a undefined rate.
    Program 2 does single point hardware IO and also has no timing information. The speed will depend on the hardware.
    Running at a hardware dependent rate is not a good idea in general, because the speed will vary with every change in hardware and is not deterministic. You don't even know what occurs first at each iteration: the input or the output.
    If speed is important, what you should do is use an improved variation (Yes, use FOR loops and ramps!) of program 1 to generate the final data array, then do a single "Nchan,Nsamp" IO, running input and output synchronized hardware timed off the same clock. This way you can select any acquisition speed up the the maximum supported by your DAQ hardware. It will be fast and at an exactly defined rate as it should be!
    Try it!
    I am not familiar with your hardware: USB-6012. can you give a link to the product page?
    LabVIEW Champion . Do more with less code and in less time .

  • How TO Make my program executable?

    please list steps to make my program executable jar ??
    please write steps from 0 ot the end?
    thank u

    jar cvfm MyJar.jar MyManifest.txt -C . *.javawhere do you type that? I tried in a command console
    but it didnt work...Make sure jar.exe is in your path.
    and what do u mean by com.acme.MyMainClass? do I have to put the com.acme?No, you would replace it with the fully qualified name of your own class of course. You are allowed to use your own brains too.

  • How to make my program forcefully errror

    hi 2 all
    how to make my program forcefully error out even i have to get data
    regards
    siva

    Hi Mate,
    Just remove the quries which you execute
    Thanks
    Kash
    www.mkashu.blogspot.com

  • How do I make this program generate a new problem once the button is hit

    Here is the code... appreciate any help given
    How do I make this program generate a new set of problem when the "NEXT" button is clicked and continue until the END button is hit
    package javaapplication3;
    import java.awt.GridLayout;
    import java.awt.Window;
    import javax.swing.*;
    import java.awt.event.*;
    * @author Sylvester Saulabiu
    class Grid extends JFrame{
        final int score = 0;
        final int total = 0;
        Grid(){
            //Set Layout of Flashcard
            setLayout(new GridLayout(4, 4, 2 , 2));
            //Create Panels
            JPanel p2 = new JPanel();
            JPanel p3 = new JPanel();
            final JPanel p1 = new JPanel();
            //Create Radio buttons & group them
            ButtonGroup group = new ButtonGroup();
            final JRadioButton ADD = new JRadioButton("Addition");
            final JRadioButton SUB = new JRadioButton("Subtraction");
            final JRadioButton MUL = new JRadioButton("Multiplication");
            final JRadioButton DIV = new JRadioButton("Division");
            p2.add(ADD);
            p2.add(SUB);
            group.add(ADD);
            group.add(SUB);
            group.add(MUL);
            group.add(DIV);
            p2.add(ADD);
            p2.add(SUB);
            p2.add(DIV);
            p2.add(MUL);
            //Create buttons
            JButton NEXT = new JButton("NEXT");
            JButton END = new JButton("End");
            //Create Labels
            JLabel l1 = new JLabel("First num");
            JLabel l2 = new JLabel("Second num");
            JLabel l3 = new JLabel("Answer:");
            JLabel l4 = new JLabel("Score:");
            final JLabel l5 = new JLabel("");
            JLabel l6 = new JLabel("/");
            final JLabel l7 = new JLabel("");
            //Create Textfields
            final JTextField number = new JTextField(Generator1());
            final JTextField number2 = new JTextField(Generator1());
            final JTextField answer = new JTextField(5);
            //Add to panels
            p1.add(l1);
            p1.add(number);
            p1.add(l2);
            p1.add(number2);
            p1.add(l3);
            p1.add(answer);
            p1.add(l4);
            p1.add(l5);
            p1.add(l6);
            p1.add(l7);
            p3.add(NEXT);
            p3.add(END);
            //Add panels
            add(p2);
            add(p1);
            add(p3);
            //Create Listners
      NEXT.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
             int answer1 = 0;
             //Grab the numbers entered
             int numm1 = Integer.parseInt(number.getText());
             int numm2 = Integer.parseInt(number2.getText());
             int nummsanswer = Integer.parseInt(answer.getText());
             //Set the score and total into new variabls
             int nummscore = score;
             int nummtotal = total;
             //Check if the add radio button is selected if so add
             if (ADD.isSelected() == true){
                 answer1 = numm1 + numm2;
             //otherwise check if the subtract button is selected if so subtract
             else if (SUB.isSelected() == true){
                 answer1 = numm1 - numm2;
             //check if the multiplication button is selected if so multiply
             else if (MUL.isSelected() == true){
                 answer1 = numm1 * numm2;
             //check if the division button is selected if so divide
             else if (DIV.isSelected() == true){
                 answer1 = numm1 / numm2;
             //If the answer user entered is the same with th true answer
             if (nummsanswer == answer1){
                 //add to the total and score
                 nummtotal += 1;
                 nummscore += 1;
                 //Convert the input back to String
                 String newscore = String.valueOf(nummscore);
                 String newtotal = String.valueOf(nummtotal);
                 //Set the text
                 l5.setText(newscore);
                 l7.setText(newtotal);
             //Otherwise just increase the total counter
             else {
                 nummtotal += 1;
                 String newtotal = String.valueOf(nummtotal);
                 l7.setText(newtotal);
      //Create End listener
    END.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            // get the root window and call dispose on it
            Window win = SwingUtilities.getWindowAncestor(p1);
            win.dispose();
    String Generator1(){
         int randomnum;
         randomnum = (1 + (int)(Math.random() * 20));
         String randomnumm = String.valueOf(randomnum);
         return randomnumm;
    public class Main {
         * @param args the command line arguments
        public static void main(String[] args) {
            // TODO code application logic here
            JFrame frame = new Grid();
            frame.setTitle("Flashcard Testing");
            frame.setSize(500, 200);
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
    }Edited by: SirSaula on Dec 5, 2009 4:39 PM

    Extract code into methods, so that when an action is performed a method is called. That way you can reuse the method for purposes such as resetting textfields to their default values, scores to default values, etc.
    You can go one step further and seperate the GUI layer from the processing layer, by deriving classes that for example maintain and calculate a score.
    Mel

  • Jow to make a program?

    How can i make a program that makes FTP Server with a tree that explore it files

    How can i make a program that makes FTP Server with a
    tree that explore it filesBy learning how to program in Java:
    http://java.sun.com/docs/books/tutorial/reallybigindex.html
    Good luck.

  • How to make labview program to get average value of 200 reading from multimeter (by using loop)

    Hello
    How to make labview program to get average value of 200 reading from multimeter (I using using loop) to read voltage from mulmeter  but I like to get average value of all of 200 reding how can I do that?
    Thanks
    Wee
    Solved!
    Go to Solution.

    Another idea with less programming - take advantage of the "free" array that comes with a Chart - i.e. the  History Data.
    1) Wire your DMM data to a Chart. (You can set the chart to invisible if you don't plan on using it in the GUI).
    2) Set the Chart History Length to 200 (right click on the chart, click on Chart History Length...)
    3) On the block diagram, use the History Data Property Node, wire it to Mean.vi, and you're done.
    Easiest running average ever.
    Message Edited by Broken Arrow on 04-07-2010 11:36 AM
    Richard
    Attachments:
    EasyAvg.jpg ‏8 KB

  • Help on how to make a program on Calendar of the year

    I'm new to java programming.
    Our teacher assigned me to make a program for a calendar of the year.
    I'm confused on what to do. Could you give me some tips on how to
    make a successful calendar of the year program?
    What shall I study first to create an output like this....?
    The program should run like this!!!!
    Enter the year from 1990 to year 2050.
    Enter the month of the year entered.
    Then displays the calendar.
    Ex.
    SEPTEMBER 2002
    Sun Mon Tue Wed Thu Fri Sat
    1 2 3 4 5 6 7
    8 9 10 11 12 13 14
    15 16 17 18 19 20 21
    22 23 24 25 26 27 28
    29 30
    Hoping that you would reply.
    Thank you very much!!!

    Don't want to do your homework. You should think about how you might do it yourself first.
    However, the class java.util.Calendar will be useful to you. Read up on that in the API docs.

  • How to make a program that will ask for a name the first time the program is used and if is not the first time will not ask the name?

    I want to make a program that will ask for the ID of the testing machine the first time the program is running, then will never ask for it. I'm using Labview 6.0

    Hi
    There are a Couple of methods you can use for this.
    Method 1 -
    You can create an ini file and save a boolean Key "First Instance" as True. Now In your Program you read this Key, If it is True then you can show your ID Dialog VI.If False do not run the VI. At the Conclusion of Id Dialog you can update this registry enrty to False. So In effect you have created One time Event. In fact you can save ID as another Config entry.
    The Drawback and advantage is that such an INI file can be edited by someone moderately knowledgeable about the Program
    Method 2
    Use Unitialized Shift Register in A while Loop. Please see LV2 style Globals entry under this forum. You can read and write to this Variable and it retains the Value it last had within it.
    You can read
    this Global the Very first time and say if it true you display your ID Vi. If False you dont. When you display your ID Vi you can Update your Global Like Before.
    If you need Example Let me Know.
    Good Luck
    Mache!!
    Good Luck!
    Mache

Maybe you are looking for