Getting input from a file(user I/O redirection)

alright i am stuck on this program. Heres what i have to do
I have to write a program usinbg arrays and looping. The program should get its input from a file (user I/O redirection). The first number in the file will be the number of numbers that follow to find the average of (maximum of 100) and print if they are above or below the average.
I have called the program lab9.java. I already made a file called lab9.dat. This is whats inside the lab9.dat file.
16
15
751
24
-56
81
227
54
99
0
102
57
58
43
245
47
73
16 is how many numbers i am using.
I am just stuck on how i should do this.
I have to have the program look at those numbers from that file and then calculates the average and then it has to look at each individual number and print out if that number is above or below average. First off im getting an error when i put in java lab9 < lab9.dat. Am i messing up somewhere.
I also have the loop:
int numnums = cisio.GetInt();
double nums[] = new double[numnums];
int k;
for(k=0;k<numnums;k++)
nums[k]=cisio.GetInt();
This is where im stuck. I need the program to get the average of the numbers and then compare each number to the average and say if its above or below average. I dont know how to do that. If someone can help me out that would be great.

Yes, you would need three loops: one to get the input, other the calculate the sum, and a third to print out what numbers are less than and what more than the average. That is the easiest thing to do. It's possible to combine getting the input and calculating the sum in one single loop though. I'm glad you got it working! :)

Similar Messages

  • How can i get input from user in Workflows

    Hello professionals,
    I'm new to SAP B1 Workflow, i have created some workflows and they all worked fine.
    But, I am wondering, How can i get input from user?. For example, i want to display list of options to choose between them and route the workflow based on the selected option. I don't want to use the exclusive gateway and check for some conditions, i want to get input from user.
    How can i do that?
    Thanks in advance,
    Kareem Naguib

    Hi,
    Please refer SAP help file:
    http://help.sap.com/saphelp_sbo900/helpdata/en/b8/1f9a1197214254b79bcf8f93f9fff9/content.htm?frameset=/en/44/c4c1cd7ca22…
    Thanks & Regards,
    Nagarajan

  • How do i get input from the user?

    For example if i wanted to ask "Whats your favorite number" and then get the input from the user and assign it to a variable how would i go about doing that?

    hi,
    if you want to get input from your console your should work with io(input and output).The BufferedReader class, InputStreamReader class
    you should import "java.io.BufferedReader" and "java.io.InputStreamReader" package, and do something like this:
    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    String favoriteNumber;
    System.out.println("Whats your favorite number ");
    favoriteNumber = input.readLine();
    System.out.println ("Your favorite Number Is " + favoriteNumber);
    if its a gui you should import "javax.swing.JOptionPane" and do the following
    String favoriteNumber = JOptionPane.showInputDialog(null, "Enter your favorite Number", "Favorite Number", JOptionPane.INFORMATION_MESSAGE);
    anjiie([email protected]).

  • Getting input from textbox as "console"

    Hi all. I am learning C# and have a Windows forms project that I am working on to learn various techniques. Basically it has a text box that I use to mimic a console. The user enters a command followed by the Enter key and the program reads that in and interprets
    it. I also have some rudimentary "batch" commands, such as IF/THEN, INPUT and PRINT.
    The application has two main components: The form and a class. The form takes care of interpreting the commands that the user enters and the class implements the three batch commands (more to follow in the near future). The issue that I am having is that
    sometimes (maybe 2%) the INPUT functionality does not work. When I enter a string and press Enter an empty string is returned. I have tried to debug this as much as I can, but it is difficult since this problem only happens once in a while.
    I have extracted the INPUT functionality and duplicated it in a simple app which I present here. The test app contains one button called btnConRead and a multi line text box called txtConsole. Clicking the button "forces" the app into "run"
    mode where the batch commands are interpreted. For this example I run the code that runs when an INPUT command is being processed. The app prompts with "OK" and waits for the user to type something in. When the user presses the Enter key the entered
    string is echoed on the console. The form module contains this code:
    string sKBBuf = ""; //App wide KB buffer when form Key preview is enabled.
    bool bEnter;
    private delegate void DisplayMsgDelegate(string sMsg);
    private void cEventPrint(object sender, PrintDataEventArgs e)
    Display(txtConsole, e.sPrintLine);
    private void cEventRead(object sender, ReadDataEventArgs e)
    //Event that reads text from the console and returns it.
    //This event requires input from the user. It traps the program here until the user
    //presses Enter.
    //Clear the KB buffer.
    sKBBuf = "";
    //Loop incessantly until user presses Enter key or Stop key (s).
    do
    //Braindead.
    } while (!bEnter);
    if (bEnter)
    //User pressed the Enter key, return the KB buffer.
    e.sReadLine = sKBBuf;
    //Empty buffer.
    sKBBuf = "";
    //Reset Enter key flag.
    bEnter = false;
    //Push CRLF to console.
    Display(txtConsole, Environment.NewLine);
    private void DisplayMsg(string sMsg)
    txtConsole.AppendText(sMsg);
    private void Display(TextBox txtOutput, string sMsg, bool bToCon = true)
    //Check output to console flag.
    if (bToCon)
    if (txtOutput.InvokeRequired)
    txtOutput.Invoke(new DisplayMsgDelegate(DisplayMsg), sMsg);
    else
    txtOutput.AppendText(sMsg);
    private void GetConInput()
    clsExample cEx = new clsExample();
    cEx.ReadData += cEventRead;
    cEx.PrintData += cEventPrint;
    System.Threading.Thread runThread = new System.Threading.Thread(() =>
    cEx.Process();
    this.KeyPreview = false;
    this.KeyPreview = true;
    runThread.Start();
    private void btnReadCon_Click(object sender, EventArgs e)
    //Prep stuff
    sKBBuf = "";
    txtConsole.Focus();
    Display(txtConsole, "OK" + Environment.NewLine);
    //Read console textbox
    GetConInput();
    private void Form1_KeyPress(object sender, KeyPressEventArgs e)
    bEnter = e.KeyChar == 13;
    //Save to buffer. At this time I am not distinguishing from letter or digits.
    //But I do need to check for a BS.
    if (e.KeyChar == 8)
    //Yeah, BS, remove the last char, if any.
    if (sKBBuf.Length > 0)
    sKBBuf = sKBBuf.Substring(0, sKBBuf.Length - 1);
    else
    sKBBuf += e.KeyChar;
    The class is called clsExample and contains the following code:
    //Event raised when data needs to be printed to console.
    public event EventHandler<PrintDataEventArgs> PrintData;
    //Event raised when data needs to be read from console.
    public event EventHandler<ReadDataEventArgs> ReadData;
    protected virtual void OnReadData(ReadDataEventArgs e)
    EventHandler<ReadDataEventArgs> handler = ReadData;
    if (handler != null)
    handler(this, e);
    protected virtual void OnPrintData(PrintDataEventArgs e)
    EventHandler<PrintDataEventArgs> handler = PrintData;
    if (handler != null)
    handler(this, e);
    public void Process()
    ReadDataEventArgs argsRead = new ReadDataEventArgs();
    PrintDataEventArgs args = new PrintDataEventArgs();
    string sMsg = "";
    //Get input from user.
    OnReadData(argsRead);
    if (argsRead.sReadLine.Length > 0)
    //I have something
    sMsg = argsRead.sReadLine;
    else
    //No data
    sMsg = "*";
    args.sPrintLine = sMsg + Environment.NewLine;
    OnPrintData(args);
    Plus two more support classes for the Print and Read events:
    public class PrintDataEventArgs : EventArgs
    public string sPrintLine { get; set; }
    public class ReadDataEventArgs : EventArgs
    public string sReadLine { get; set; }
     All the above was necessary so that the Process procedure running in a different thread could interact with the UI elements in the main form. The above mostly works, but I wonder if I am doing it the right way. I don't particularly like the use of
    global flags, such as bEnter or having empty loops to just "kill" time, such as the one found in the cEventRead procedure.
    In the cEventRead procedure I had the if() block immediately following the empty loop inside
    the loop and moved it out of there to see if this made any difference, but apparently it did not. Can anyone provide any feedback or suggestions of what I could change to make it work 100% of the time? I appreciate your time and effort. Thank you, Saga
    You can't take the sky from me

    Hi all. I am learning C# and have a Windows forms project that I am working on to learn various techniques. Basically it has a text box that I use to mimic a console. The user enters a command followed by the Enter key and the program reads that in and interprets
    it. I also have some rudimentary "batch" commands, such as IF/THEN, INPUT and PRINT.
    //Loop incessantly until user presses Enter key or Stop key (s).
    do
    //Braindead.
    } while (!bEnter);
    Hi Saga,
    Please don't use such kind of loop in your code, if you want to monitor the user input, just use the KeyPress event provided by the TextBox control.
    Control.KeyPress
    Event
    If you just want to execute some standard commands, I recommend that you use
    Process to start cmd.exe to execute the command, for example:
    void ExecuteCommand(string command)
    int exitCode;
    ProcessStartInfo processInfo;
    Process process;
    processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
    processInfo.CreateNoWindow = true;
    processInfo.UseShellExecute = false;
    // *** Redirect the output ***
    processInfo.RedirectStandardError = true;
    processInfo.RedirectStandardOutput = true;
    process = Process.Start(processInfo);
    process.WaitForExit();
    // *** Read the streams ***
    string output = process.StandardOutput.ReadToEnd();
    string error = process.StandardError.ReadToEnd();
    exitCode = process.ExitCode;
    Console.WriteLine("output>>" + (String.IsNullOrEmpty(output) ? "(none)" : output));
    Console.WriteLine("error>>" + (String.IsNullOrEmpty(error) ? "(none)" : error));
    Console.WriteLine("ExitCode: " + exitCode.ToString(), "ExecuteCommand");
    process.Close();
    If it's powershell script, you can also use the existing library to execute it, check this blogpost:
    Executing PowerShell scripts from C#
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • How to Get Input from Command Prompt?

    How can i get input from command prompt like
    C:\
    or linux ?
    (Here's what I use now)
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String line;
    Whlie((line=in.readLine())!= null)
    { System.out.prinln( line) ; }
    IS THERE A BETTER WAY?

    The main method within a java class accepts command line input through a String array.
    In this example args is the String array. You can access the parameters as args[0] for the first parameter, args[1] for the second parameter, etc....
    The usage for the example below would be :
    c:\EDIFormat file1 file2
    Where args[0] would equal file1 and args[1] would equal file2.
    public class EDIFormat {
    public static void main(String[] args) {
              if (args.length < 0) {
                   System.out.println("No Parameters supplied. Exiting....");
                   // open input and output files
                   EDIFiles(args[0], args[1]);
    Hope that helps!

  • Cant get data from text file to print into Jtable

    Instead of doing JDBC i am using text file as database. I cant get data from text file to print into JTable when i click find button. Goal is to find a record and print that record only, but for now i am trying to print all the records. Once i get that i will change my code to search desired record and print it. when i click the find button nothing happens. Can you please take a look at my code, dbTest() method. thanks.
    void dbTest() {
    DataInputStream dis = null;
    String dbRecord = null;
    String hold;
    try {
    File f = new File("customer.txt");
    FileInputStream fis = new FileInputStream(f);
    BufferedInputStream bis = new BufferedInputStream(fis);
    dis = new DataInputStream(bis);
    Vector dataVector = new Vector();
    Vector headVector = new Vector(2);
    Vector row = new Vector();
    // read the record of the text database
    while ( (dbRecord = dis.readLine()) != null) {
    StringTokenizer st = new StringTokenizer(dbRecord, ",");
    while (st.hasMoreTokens()) {
    row.addElement(st.nextToken());
    System.out.println("Inside nested loop: " + row);
    System.out.println("inside loop: " + row);
    dataVector.addElement(row);
    System.out.println("outside loop: " + row);
    headVector.addElement("Title");
    headVector.addElement("Type");
    dataTable = new JTable(dataVector, headVector);
    dataTableScrollPane.setViewportView(dataTable);
    } catch (IOException e) {
    // catch io errors from FileInputStream or readLine()
    System.out.println("Uh oh, got an IOException error!" + e.getMessage());
    } finally {
    // if the file opened okay, make sure we close it
    if (dis != null) {
    try {
    dis.close();
    } catch (IOException ioe) {
    } // end if
    } // end finally
    } // end dbTest

    Here's a thread that loads a text file into a JTable:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=315172
    And my reply in this thread shows how you can use a text file as a simple database:
    http://forum.java.sun.com/thread.jsp?forum=31&thread=342380

  • How to get data from a file?

    Hello everyone, i'm new to this forum and to java too. Ok, so here is what i want to do:
    I want to get data from a file containing words and numbers and store them into variables that i will use them after to insert into a database table. For example i have a file called employees.txt in this form:
    eid ename zipcode Hire_date
    1000 "Jones" 67226 "12-DEC-95"
    In C++ i declare variables for each data and store them, for example in this case:
    ifstream in("somefile");
    string name, hdate;
    int eid, zip;
    in >> eid >> ename >> zip >> hdate;
    So i want to do the same thing in JAVA but i can't make it work. So, i would appreciate if someone could give me a simple example how to do it. Thank you.

    [http://java.sun.com/docs/books/tutorial/essential/io/index.html]

  • How to get input from card reader

    hi, everyone,
    I have a project, which needs me to get input from card reader. My terminal input is IBM POS system, but it didnot provide the API to get the input. How can I get the input? Need your help so much! and thanks a lot

    Now this is a wild idea.... how about searching the IBM site for technical information ?

  • Switching from Iphone 4 to Android, now i cant get txts from other Iphone users... any suggestions?

    switching from Iphone 4 to Android, now i cant get txts from other Iphone users... any suggestions?

    http://support.apple.com/kb/TS5185

  • I changed to an android and now cant get text from some iphone users any suggestions??

    I have just switched to an android and now am having problems getting text from some iphone users, and suggestions as to how I can fix this?

    Hi mango72860,
    Thanks for visiting Apple Support Communities.
    If you're not receiving text messages from iPhone users, see this article for help:
    iOS: Deactivating iMessage
    http://support.apple.com/kb/TS5185
    Best Regards,
    Jeremy

  • How to get Text from (.txt) file to display in the JTextArea ?

    How to get Text from (.txt) file to display in the JTextArea ?
    is there any code please tell me i am begginer and trying to get data from a text file to display in the JTextArea /... please help...

    public static void readText() {
      try {
        File testFile = new File(WorkingDirectory + "ctrlFile.txt");
        if (testFile.exists()){
          BufferedReader br = new BufferedReader(new FileReader("ctrlFile.txt"));
          String s = br.readLine();
          while (s != null)  {
            System.out.println(s);
            s = br.readLine();
          br.close();
      catch (IOException ex){ex.printStackTrace();}
    }rykk

  • TS3771 Why can't I select "get info" from the file area so I can change the setting to "open in 32-bit mode" ?

    Why can't I select "get info" from the file area so I can change the setting to "open in 32-bit mode" ?

    It may be because of your settings. You can modify that setting in System Preferences > Trackpad. Another way of making right-click is to click the app icon while holding the Control key

  • Had iPhone and now have droid..cannot get texts from other iPhone users?

    Had iPhone and now have droid..cannot get texts from other iPhone users?

    barbara, a friend of mine give me her old iphone 4 and she get the an android phone so when i typing a text message still shows me she have a iphone, she did turning off iMessage but after she contact her cellphone carrier and unlock the old iphone 4 her number get unlicked from IOS so, trying turning off iMessage is not the solution ebcause we tried and did not work , the best solution is go to ur cellphone carrier and do the request to unlock ur previews iphone then you will see the change it

  • Get input from user and create a file and run a script in command line.

    Hi all,
    i'm trying to get a input from user and write it into a file named alpe.jacl
    To get multiple userinputs like address and jobtitle etc etc in the same single window.
    and the code will save the inputs in alpe.jacl one by one in a new line like
    nameis name
    address russia
    jobtitle dev
    So i coded like below.
    Though GUI for user input looks dull Its working fine.
    Now I want this code to perform one more task which is the GUI will contain one more button INSTALL with OK and CALCEL .
    and when after putting all inputs and creating the alpe.jacl file if someone clicks INSTALL it should start ./install.sh script present at the same folder which contains some unix shell commands.
    Here am not able to figure out how to go further...
    One more thing after all the inputs given when I am clicking on the OK button its closing the window instantly which i dont want. I want it like it should wait till someone press CANCEL to exit.
    Please some one help me.
    import javax.swing.*;
    import java.io.*;
    public class file
    public static void main(String []args)throws IOException
    FileWriter ryt=new FileWriter("alpe.jacl");
    BufferedWriter out=new BufferedWriter(ryt);
    JTextField wsName = new JTextField();
    JTextField sName = new JTextField();
    JTextField cName = new JTextField();
    Object[] message = {    "Web Server Name:", wsName,"Server Name:", sName,"Cluster Name:", cName};
    int answer = JOptionPane.showConfirmDialog(    null, message, "Enter values", JOptionPane.OK_CANCEL_OPTION);
    if (answer == JOptionPane.OK_OPTION){    String webserver = wsName.getText();
    String server = sName.getText();
    String cluster = cName.getText();
    out.write("set webservername " +wsName.getText()+"\n");
    out.write("set ClusterName " +cName.getText()+"\n");
    out.write("set ServerName " +sName.getText()+"\n");
    out.close();
    }}Thanks,
    Ricky

    Thanks a lot.
    Is there any way through which i can assign a scroll bar to my panel.
    As when the number of user inputs grows the GUI becomes more bulky and some of the fields are not showing up.
    Cheers
    _Ricky                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • User Input from Text File

    Hello
    I would like to incorporate code into this to allow the script I found on the internet to pull input from a txt file and then wait for the script to end before using the next entry in the text file and run until all entries in the text file have been used.
    Any help would be great thx.
    Jason
    ' Get Options from user
    GetOptions
    If (bInvalidArgument) Then
        WScript.Echo "Invalid Arguments" & VbCrLf
        bDisplayHelp = True
    End If
    If (bDisplayHelp) Then
        DisplayHelp
    Else
        If (bCheckVersion) Then
            CheckVersion
        End If
        If (strComputer = "") Then
            strComputer = InputBox("What Computer do you want to document (default=localhost)","Select Target",".")
        End If
        If (strComputer <> "") Then
            ' Run the GatherWMIInformation() function and return the status
            ' to errGatherInformation, if the function fails then the
            ' rest is skipped. The same applies to GatherRegInformation
            ' if it is successful we place the information in a
            ' new word document
            errGatherWMIInformation = GatherWMIInformation()
            If (errGatherWMIInformation) Then
                If (bDoRegistryCheck) Then
                    errGatherRegInformation = GatherRegInformation
                End If
                GetWMIProviderList
            Else
                WScript.Quit(999)
            End If
            If (bHasMicrosoftIISv2) Then ' Does the system have the WMI IIS Provider
                GatherIISInformation
            End If
            SystemRolesSet
            If (errGatherWMIInformation) Then
                Select Case strExportFormat
                    Case "word"
                        PopulateWordfile
                    Case "xml"
                        PopulateXMLFile
                End Select
            End If
        End If
    End If

    Unfortunately the script is too long to be posted but can be found at
    http://sydiproject.com/download/and is called Server v.2.3. I have also contacted the author and made the suggestion I
    asked about.
    Jason
    I do not know which script you had in mind but the one I looked at had 1,600 lines of code. As you say, posting it here would be inappropriate. At the same time it is unrealistic to ask for help for such a large script. Asking the author is one option. The
    other option would be to identify the module you wish to modify, analyse it until you fully understand it, modify it so that you can run it in a stand-alone manner, then post your question here. You will probably find that you can answer the question yourself
    after analysing the code!

Maybe you are looking for

  • Spilled water over laptop :-( lost all i-tunes music!!

    Hi there! Yes I know I'm really, really silly but last week I kicked a glass of water all over my laptop rendering it completely useless. I ost everything as nothing could be retrieved from the hard drive....Baically all my purchased music from i-tun

  • Postings in wrong Functional Area

    Hi, I have a complicated scenario, i have a service purchase order for a cost center C111 which as a Functional Area F101, during invoice i had changed the cost center to C222 and changed the Functional Area to F101, where the cost center C222 belong

  • Help Desk Availability

    I am contemplating upgrading our ZEN 3.2 to ZEN 4.1 for the simple reason that I know the help desk feature is removed from ZEN 4.1. On the other hand I have heard from unconfirmed source, that if you upgrade from ZEN version 3.2 you still get to kee

  • E_ADEPT_INTERNAL

    Buenas tardes, quiero abrir el libro digital que compre y me da este error. No es problema de la autorización porque ya la borré y volví a autorizar. Bajé la nueva versión del programa, la 3.0. Espero sus instrucciones. Muchas gracias.

  • TS3772 please help i tried to sync my iphone 4 to a computer and lost all of my info, my pics and my games. how do i get them back?

    please help i tried tosync my iphone 4 to a computer and lost all of my info, pics and games how  do i get them back?