Reading from a file. How to ask the user for file name at run time????

I have the code to read from a file but my problem is how to prompt the user for the file name at run time.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
import java.util.Scanner;
public class FileRead {
    public static void main(String args[]) {
        Scanner scan = null;
        File file = new File("Results.txt");
        String number;
        try {
            scan = new Scanner(file);
            while (scan.hasNext()){
            number = scan.next();
            System.out.println(number);}
        catch (FileNotFoundException ex1){
            System.out.println("No such file");
        catch (IllegalStateException ex2){
            System.out.println("Did you close the read by mistake");
        catch (InputMismatchException ex){
            System.out.println("File structure incorrect");
        finally{
            scan.close();}
}Any hints would be greatly appreciated. Thank you in advance

I have read through some of the tutorials that you have directed me too and they are very useful, thank you. however there are still a few things that i am not clear about. I am using net beans 5.0 I have placed a text file named Results.txt into the project at the root so the program can view it.
When I use the code that you provided me with, does it matter where the file is, or will it look through everywhere on the hard drive to find a match?
This code compiles but at run time it comes up with this error
run-single:
java.lang.NoClassDefFoundError: NamedFile
Exception in thread "main"
Java Result: 1
BUILD SUCCESSFUL (total time: 3 seconds)
import java.util.Scanner;
import java.io.*;
class NamedFileInput
  public static void main (String[] args) throws IOException
    int num, square;   
    // this Scanner is used to read what the user enters
    Scanner user = new Scanner( System.in );
    String  fileName;
    System.out.print("File Name: ");
    fileName = user.nextLine().trim();
    File file = new File( fileName );     // create a File object
    // this Scanner is used to read from the file
    Scanner scan = new Scanner( file );     
    while( scan.hasNextInt() )   // is there more data to process?
      num = scan.nextInt();
      square = num * num ;     
      System.out.println("The square of " + num + " is " + square);
}his is the code that i used. It is the same as the code you posted for me (on chapter 23 I/O using Scanner and PrintStream) Sorry im just really stuck on this!!

Similar Messages

  • How to build sql query for view object at run time

    Hi,
    I have a LOV on my form that is created from a view object.
    View object is read-only and is created from a SQL query.
    SQL query consists of few input parameters and table joins.
    My scenario is such that if input parameters are passed, i have to join extra tables, otherwise, only one table can fetch the results I need.
    Can anyone please suggest, how I can solve this? I want to build the query for view object at run time based on the values passed to input parameters.
    Thanks
    Srikanth Addanki

    As I understand you want to change the query at run time.
    If this is what you want, you can use setQuery Method then use executeQuery.
    http://download.oracle.com/docs/cd/B14099_19/web.1012/b14022/oracle/jbo/server/ViewObjectImpl.html#setQuery_java_lang_String_

  • How to ask the I2C device alias name from the MAX

    Hi,
    How can I ask the I2C device alias name which MAX uses in Labview? If the VISA Alias on My System is for example I2C in MAX, I need to ask it in Labview and write it then to Device Reference In input of a I2C vi.
    BR,
    Jick
    Solved!
    Go to Solution.

    Here is a picture which should clarify the problem a bit more.
    As you can see I use "I2C2" as an alias in MAX and I need somehow query that alias in Labview and write it to the device reference in input node. How?
    BR,
    Jick
    Attachments:
    pic1.JPG ‏21 KB

  • Is it possible to let the SecurityManager ask the user for permissions?

    Hi there!
    I would like to write an applet which should realize single-sigon via JAAS and for jaas I need some access to the underlaying os which is permitted by the security manager.
    I dont want to buy a certificate or to go through all our (700) Computers and install my self-made certificates and change the policy file.
    So is there a way to let java ask the user if it trusts the applet (may with remeber this desision) to e.g. let it access features needed for jaas.
    This way can be direct (via api call) or not (applet signed via free long valid (at least 5 years) certificate), however the only important thing is that I get access to the system.
    Any ideas, I would be happy about (nearly g) everything ;-)
    Thanks a lot, lg Clemens

    However thanks a lot for help g
    Found the answer myself: Simply sign the applet with an self-made certificate, the next time the browser is restartet there will be a promt for acceptimg the certificate.
    Cool!

  • How to build the "Path Prefix" HTTP Adapter at run time

    Hi All,
    I have a scenario wherein I have to call the HTTP Url of a thiird party system from R/3 via PI.
    The third party url looks liike this:
    http://gis/ias/cgi-bin/siscgi.exe?request=batch&command=<requests><request><name>sis_neighbouring_knos_for_sambandh_service</name><buffer>20</buffer><same_premise_kno>123</same_premise_kno><l
    eft_kno>331</left_kno><gis_id>4019589</gis_id><priority>same_premise_kno,left_kno,right_kno,gis_id</priority></request></requests>&user_name=sambandh.sias&pa
    ssword=sambandhsias
    I have successfully created a HTTP Recevier comm channel and provided the following in the "Path Prefix"
    /ias/cgi-bin/siscgi.exe?request=batch&command=<requests><request><name>sis_neighbouring_knos_for_sambandh_service</name><buffer>20</buffer><same_premise_kno>123</same_premise_kno><l
    eft_kno>331</left_kno><gis_id>4019589</gis_id><priority>same_premise_kno,left_kno,right_kno,gis_id</priority></request></requests>&user_name=sambandh.sias&pa
    ssword=sambandhsias
    But If I need to pass the values inside the xml tags specified above e.g. "name" at run time, How do I do that?
    I have explored the "Apply URL Parameters" option in the HTTP Comm channel but it has fixed names for the HTTP URL parameter.
    Please let me know how is this possible hopefully without a UDF
    thanks,
    Piyush

    Hi Piyush,
    Have you checked the option of ASMA of the adapter?
    http://help.sap.com/saphelp_nw04/helpdata/en/43/64dbb0af9f30b4e10000000a11466f/content.htm
    Also see Note 1101338 - Dynamic configuration of HTTP adapter
    Regards
    Suraj

  • How to restrict the user for re-submitting the same form

    Hi All,
    I would like to know, How to restrict a user for re-submitting the same page.
    I have a jsp page with submit button... and should not allow the user to save the same data again ..
    Anil

    Try the followings. If user disable cookies, this will not work. You need to modify to detect such situation!
    String processed = "mycooke";
    Cookie[] cookies = request.getCookies();
    Cookie c = null;
    if (cookies!=null) {
       for (int i=0; i < cookies.length; i++) {
           if (cookies.getName.equals(processed)) {
    c = cookies[i];
    break;
    if (c!=null) {
    // already processed.
    // send error message and exit.
    // set cookie;
    c = new Cookie(processed , "yourdata");
    c.setMaxAge(-1);
    response.addCookie(c);
    // process as it is the first;

  • How to make the user choose file.

    I am making a program in which a file is read using RandomAcessFile. I wamt the user to choose the file from its location. I am giving the code. Just help me in knowing where the error is.
    import java.awt.*;
    import java.awt.event.*;
    public class ChooseFiles{
         public static void main(String[] args){
              getFiles();
         public static String getFiles(){
              DialogFrames df = new DialogFrames("MedInfo");
              df.setSize(800,555);
              df.addWindowListener(new WindowAdapter(){
                   public void windowClosing(WindowEvent we){
                        System.exit(0);
              df.show();
              return df.getFile();
    class DialogFrames extends Frame implements ActionListener{
         Menu m = new Menu("File");
         MenuBar mb = new MenuBar();
         MenuItem mi = new MenuItem("Open");
         FileDialog fd;
         DialogFrames(String title){
              super(title);
              setLayout(new GridLayout(1,1));
              m.add(mi);
              mi.addActionListener(this);
              mb.add(m);
              setMenuBar(mb);
              fd = new FileDialog(this,"Open");
         public void actionPerformed(ActionEvent ae){
              if (ae.getSource()==mi){
                   fd.setVisible(true);
         public String getFile(){
              return fd.getFile();
    import java.io.*;
    public class Plot{
         boolean flag = true;
         ChooseFiles cf = new ChooseFiles();
         public static void main(String[] args){
              try{
                   String ftr = cf.getFiles();
                   RandomAccessFile raf = new RandomAccessFile(ftr,"r");
                   long l = 0;
                   while (l < raf.length()){
                        String str = raf.readLine().toString();
                        l = raf.getFilePointer();
                        if (str != null){
                             System.out.println("This line is " str" at l = "+l);
                   raf.close();
              }catch (Exception e){
                   System.out.println("Caught Exception " + e.toString());
    I get the following compilation error. Please help me to sort it out.
    Plot.java:7: Can't make a static reference to nonstatic variable cf in class Plot.
    String ftr = cf.getFiles();
    ^

    I made the changes to Plot.java.
    This is the first one.
    import java.io.*;
    public class Plot{
         boolean flag = true;
         public static void main(String[] args){
              Plot plot = new Plot();
         Plot(){
              try{
                   String ftr = "";
                   ChooseFiles cf = new ChooseFiles();
                   ftr += cf.getFiles();
                   RandomAccessFile raf = new RandomAccessFile(ftr,"r");
                   long l = 0;
                   while (l < raf.length()){
                        String str = raf.readLine().toString();
                        l = raf.getFilePointer();
                        if (str != null){
                             System.out.println("This line is " str" at l = "+l);
                   raf.close();
              }catch (Exception e){
                   System.out.println("Caught Exception " + e.toString());
    It gives the following exception.
    Caught Exception java.io.FileNotFoundException: null (The system cannot find the file specified)
    This is the second one.
    import java.io.*;
    public class Plot{
         boolean flag = true;
         public static void main(String[] args){
              Plot plot = new Plot();
         Plot(){
              try{
                   ChooseFiles cf = new ChooseFiles();
                   String ftr = cf.getFiles();
                   RandomAccessFile raf = new RandomAccessFile(ftr,"r");
                   long l = 0;
                   while (l < raf.length()){
                        String str = raf.readLine().toString();
                        l = raf.getFilePointer();
                        if (str != null){
                             System.out.println("This line is " str" at l = "+l);
                   raf.close();
              }catch (Exception e){
                   System.out.println("Caught Exception " + e.toString());
    Caught Exception java.lang.NullPointerException

  • CRM 5.0 ear files - How to get the b2c.ear file for custom development

    Hi all,
    We are using CRM 5.0 e-commerce (B2C). We are looking to import the b2c.ear file into the NW dev studio. We do not seem to be able to find the file.
    Alexandre
    PS: Do we need to have the NWDI in order to do custom ISA (b2c) development ?

    Hi
    Unlike in 4.0 we wont have EAR file directly to import. First Basis people need to setup NWDI where in they import all packages. Once it is ready, in NWDS(dev env) we need to import configuration which will internally impors Development Components and their dependencies. Once you have everything in locla machine, we can create project make EAR FILE...
    i hope this answers your quesiton.
    regards,
    Laxman

  • How to change Crystal Reports XI database name at run time from ASP code using ADO

    Dear All,
    I need advises regarding to my problem below
    I have two database in same SQL 2005 SERVER for TEST01 and LIVE01 Environtment, and I've created more than 100 reports with Crystal Reports 11 and call it from ASP classic page.
    The problem is how can I change a database from TEST01 to LIVE01 at the run time from ASP code as I already using TEST01 database on Crystal Reports and I do not want to set a new database location inside crystal for each reports
    Thanks and wait for your reply soon.
    Below is my code, which has no effect to crystal reports although I've change the database from TEST01 to LIVE01:
    <%
    Dim oADOConnection, oRptTable, oADORecordset, sql
    Dim struser, strpwd, strdriver, dblocation, dbname, strConnect
    struser = "sa"
    strpwd = ""     
    strdriver = "{SQL SERVER}" 
    dblocation = "SQL200501"     
    dbname = "LIVE01"    ' Changed from TEST01 to LIVE01
    strConnect = "User Id=" & strUser & ";"
    strConnect = strConnect & "PWD=" & strPwd & ";"
    strConnect = strConnect & "DRIVER=" & StrDriver & ";"
    strConnect = strConnect & "SERVER=" & DBLocation & ";"
    strConnect = strConnect & "DATABASE=" & dbName
    sql="Select * from Employee"
    Set session("oApp") = Server.CreateObject("CrystalRuntime.Application.11")
    Set session("oRpt") = session("oApp").OpenReport("C:\REPORTS\RPT01.RPT", 1) 'USING TEST01 DATABASE
    session("oRpt").MorePrintEngineErrorMessages = False
    session("oRpt").EnableParameterPrompting = False
    session("oRpt").DiscardSavedData
    Set oADOConnection = Server.CreateObject("ADODB.Connection")
    oADOConnection.Open (strConnect)
    Set oADORecordset = Server.CreateObject("ADODB.Recordset")
    Set oRptTable = session("oRpt").Database.Tables.Item(1)
    oRptTable.SetDataSource oADORecordset, 3
    session("oRpt").SQLQueryString = CStr(sql)
    session("oRpt").ReadRecords
    %>

    Did you ever find a solution to this problem?  I have the same problem when moving reports from development to Test to Production environments.  If the DBName is not the same the report ignores the name provided at runtime.

  • How to change the font size and style on run time

    dear all
    i try to change the font style and font size on runtime. I did the following:
    1- i created an item(:font_size) in which i will write the size of the font for the the other item ('customer_name')
    2 on the post_change trigger for 'font_size' i write this code
    SET_ITEM_PROPERTY('customer_name',FONT_size,(:font_size);
    i write 12 then then font size changed , then i write 18 , the size does not change. and when i write any value , no change happens. I do not know why
    the second problem is how to change the font style
    i made three checkbooks (bold,italic,underline)
    on the trugger when_checkbox_checked i write
         IF :BOLD = 'B' THEN
         SET_ITEM_PROPERTY('N_SAMPLE',FONT_STYLE,'BOLD');
         ELSE
    SET_ITEM_PROPERTY('N_SAMPLE',FONT_STYLE,'REGULAR');
         END IF;     
    no change happend at all.
    please help

    Hi friend,
    it's a really really strange tip... May be it's a Forms bug? I've tried with set_item_property..and.. you're right, it doesn't work..
    So.. you can try making this:
    - create a visual attribute with an specific font size....
    - use the
    SET_ITEM_INSTANCE_PROPERTY('block.item',CURRENT_RECORD,VISUAL_ATTRIBUTE,'you_visual_attribute');
    and call it from psot-change....
    It works
    Hope it helps,
    Jose.

  • How to set the number of records displayed at run time

    Is it possible to set the number of records displayed block property at run time? The built-in 'GET_BLOCK_PROPERTY' can retrieve the number of RECORDS_DISPLAYED. But I can't find SET_BLOCK_PROPERTY to set this property. Is there anyway I can set this property programmatically? Thanks for any suggestions!

    Bookmark Go to End
    goal: How to vary the number of records displayed in a block
    programmatically
    fact: Oracle Forms Developer
    fix:
    Block property 'Number of Records Displayed' can not be changed during runtime
    using SET_BLOCK_PROPERTY. However, it is still possible programmatically change
    the visual appearance of the form so that it creates effect of changing this
    property. To achieve such an effect follow these steps:
    1. in Forms Builder, in the multirecord block define the new set of items.
    The simplest way is to copy/paste the original item and rename created item.
    2. set properties of these new items so that they are the same as the properties
    of the original items. If these new items were copied from original items
    then properties are already the same. Modify following properties
    'Database item' on new items to value 'No'
    'Synchronize with item' to the value of the original item
    'Number of Items Displayed' to desired value.
    'Visible' to 'No'
    In other words, these new items are mirrors of original items.
    3. code event, which is meant to trigger the change in block appearance.
    This code should use SET_ITEM_PROPERTY built-in to set properties
    like 'VISIBLE', 'ENABLED', 'NAVIGABLE', 'UPDATE_ALLOWED' and others
    to desired value for items which are about to be displayed, then
    move cursor to one of these just displayed items with GO_ITEM built-in
    and then hide the previously displayed items.
    Example:
    Assume that the block is built on SCOTT.DEPT schema. Following will
    change the set of displayed items
    set_item_property('dept.mdeptno',visible,property_true);
    set_item_property('dept.mdname',visible,property_true);
    set_item_property('dept.mloc',visible,property_true);
    set_item_property('dept.mdeptno',enabled,property_true);
    set_item_property('dept.mdname',enabled,property_true);
    set_item_property('dept.mloc',enabled,property_true);
    set_item_property('dept.mdeptno',update_allowed,property_true);
    set_item_property('dept.mdname',update_allowed,property_true);
    set_item_property('dept.mloc',update_allowed,property_true);
    set_item_property('dept.mdeptno',navigable,property_true);
    set_item_property('dept.mdname',navigable,property_true);
    set_item_property('dept.mloc',navigable,property_true);
    go_item('dept.mdeptno');
    set_item_property('dept.deptno',visible,property_false);
    set_item_property('dept.dname',visible,property_false);
    set_item_property('dept.loc',visible,property_false);
    Regards,
    Monica

  • How to change the user for an event job as SAP_MONITORING_STARTUP_DISPATCH

    Hi experts!
    We change the user that execute all our jobs. I can change the user JOB-BW for JOB-BI for this job SAP_CCMS_MONI_BATCH_STARTUP_DP, but the problem is when this job is executed by event for this other job SAP_MONITORING_STARTUP_DISPATCH, but i can't change the user JOB-BW for JOB-BI for this event
    Could you tell me, how i do the change user for this job.
    Best Regards
    Ramon Sanchez

    Hi!
    My problem have been solved. The job SAP_CCMS_MONI_BATCH_STARTUP_DP is automatically created by
    Job SAP_CCMS_MONI_BATCH_DP. It is an event triggered job to handle the startup-methods which are to be processed in batch.
    The event is SAP_MONITORING_STARTUP_DISPATCH; I only select the job in SM37 and specify this event and after made the search the job  SAP_CCMS_MONI_BATCH_STARTUP_DP i only change the user.
    Thank you all for your help!
    Ramon Sanchez

  • How to find the user ID or name who deleted the reservation

    HI,
    Some one has set the indicator Delete in reservation.I need to find who has done that activity.
    we have CDPOS and CDHDR but what are the parameters i need to pass to get the user name
    Kindly guide me
    regards
    subbu

    no way to ffind this
    Have you tried with  AUT10  ??
    thanks
    G. Lakshmipathi

  • How do I send instance for manual recovery at run time.

    Hi
    I have a BPEL process within which I am trying to handle a business error. I understand using the default-policies on the application server I can send a message for manual recovery. But is it possible to force an instance into the manual recovery queue in the event of a handled error?
    I have previosuly used the default policies to route remote/binding faults to the activities tab (manual recovery) tab and the users find this useful to adjust XM land retry, re-throw etc. But can we do the same for errors handled within the BPEL. So if I have a catch all within my process how would I send the instance to this manual recovery queue.
    Thanks
    Rich

    I hate it when after an hour's searching I post a question
    and then find the answer ten minutes later...
    "Current VI's Path" on the file IO palette...
    Bob

  • How to restrict the user for creating CR memo if the billing qty exceeds

    Hi sd gurus
    I am facing a problame. th issue is when ever I am going to raise a cr memo req more then the billing qty the system simply gives an error msg stating that the billing qty is exceeds and still I am able to create the document. I want to restrict it. means if the cr req qty exceeds the billing qty system has to throw an error and document should not saved. Plz suggest me
    thankx in advance

    Go to VTAF, select the item category for the combination of credit memo request and billing type and maintain "+" for the field "Pos./neg. quantity"
    Also go to OVAH and change message class V4 no 229 to E will work
    G. Lakshmipathi

Maybe you are looking for

  • How to stop autoplay of videos?

    June 2013: videos on websites start playing without my permission, how to stop this? What I tried: I uninstalled Adobe Flash (disabling Flash add-on didn't work), existing "stop autoplay" add-ons are no longer working according to reviews, tried solu

  • Impossible to listen to whole album or to add it to queue

    Hello, I am testing Spotify right now and plan eventually to continue my Premium supscription after the trial period but right now, I have a very annoying problem on the desktop version. I want to to a very simple and basic action : Listen to an albu

  • Raising alert in BPM

    Hi Folks I have a scenario in which i have to merge three files  in BPm and generate an Idoc  MY BPM has >>>>3  recieve steps in a fork                                   1  transformation step                                   1 send Step            

  • Error when importing

    Twice now when i put my memory stick in my memory reader i get an error message saying something like my device has ejected improperly and i may lose my files. Last time i lost my files, because iPhoto would not eject my card. The icon on the desktop

  • Installer failed to initialise help from Trevor Dennis..gladly

    trying to install photoshop cs5, inserting disc I receive error message "installer failed to initialise"   what's happening. operating Mac 10.9 maverick.