User input in Jdeveloper (Scanner or Savitch class)

Hello,
well, sorry about the simplicity of the question but for the most simple block of code like this one, getting input from the user, the program runs and runs on the botton window below where the class is. I mean where you get a log of messages telling you how the compiling is doing. I think it is a problem of "where" the target for that runnable class is, but I have not a clue where to do it. When I worked on Unix on command line the program would continue down my lines but here, in the Jdev interface, I don't know where to input my answers to the asked questions of the block:
import java.util.*;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("enter an int");
int n = Integer.parseInt(scanner.nextLine());
System.out.println("you entered " + n);
System.out.println("enter a String");
String line = scanner.nextLine();
System.out.println("you entered " + line);
I have read all about "Run configurations" etc but still puzzled :((
Message was edited by:
AlvaroEP

Console Input Window at runtime
You need to enable console input
John

Similar Messages

  • User input in JDeveloper IDE not working?

    We just started to use JDeveloper. so the problem may be very basic, I could not figure it out what is wrong:
    I have a java class which is calling a third part application (Lotus Notes, domino server). The task of the class is to open a database on domino server(or local machine). When calling domino, there is a user(calling) authorization. So I must input the password for the domino server for authorization. When I input the password in input panel and hit return, nothing happened. It looks the Domino still wait for the password. It waited and waited and the process can not be stopped itself.
    when I copied the same code and ran in other IDE or Sun's JDK. It worked fine.
    So it looks that my JDeveloper could not pass user' input to the process?
    Any helps are highly appreciated.
    George

    Hi George,
    Let me make sure I understand what you are saying.
    You want to run (or debug) your program which reads input from System.in?
    If so...
    Have you checked the checkbox in the Project Settings Dialog - Runner - Options panel "Allow Program Input"? Then when you ran (or debugged) your program, did you see a text field labeled "Input:" in the Log window for your running process?
    Did you enter the password in that text field and press Enter on your keyboard?
    If that wasn't the problem, can you give us step by step what you are doing?
    Thanks,
    Liz

  • Using a scanner to interpret user input in an array

    Hi
    Does anyone know how to use an array to store user input?
    I'm a beginner in Java and I need help making an array with 5 positions that can be filed by the user as they type.
    This is needed as a guide to read up more complex user input methods. I have been told to use a "scanner" (java.util.Scanner) to do this and frankly, I'm ridiculously lacking in Java skills. Any help would mean a whole lot.
    So far, this is the scanner I've been working with:
    import java.io.*;
    import java.util.Scanner;
    import java.util.*;
    public class ReadConsole
    public static void main(String[] args)
    Scanner input = new Scanner(System.in);                                                                
    System.out.println("Menu System - Please enter your choice");
    System.out.println("Option 1");
    System.out.println("Option 2");
    System.out.println("Option 3");
    for(int i = 0; i < 1; i++){
    int num = input.nextInt();
    if(num==1){
    System.out.println("Option 6");}
    else if(num==2){
    System.out.println("Option 7");}
    else if(num==3){
    System.out.println("Option 8");}
    else{
    System.out.println("Try again");
    i = 0;
    }

    That sounds do-able, but im struggling when it comes to inputing 5 values from the user. what do i do to separate the values? i know that sounds vague, ... but if I can make one "position", why can't I make five??
    Take a look at what I've done:
    import java.io.*;
    import java.util.Scanner;
    import java.util.*;
    public class Input
    public static void main(String[] args)
    Scanner input = new Scanner(System.in);    
    System.out.println("Please select your lucky number");
    System.out.println("Options are:");
    System.out.println("1");
    System.out.println("2");
    System.out.println("3");
    System.out.println("or 4");
    for(int i = 0; i < 1; i++){
    int num = input.nextInt();
    if(num==1){
    System.out.println("Your lucky number is 1. Cool");}
    else if(num==2){
    System.out.println("Your lucky number is 2. Cool");}
    else if(num==3){
    System.out.println("Your lucky number is 3. Cool");}
    else if (num==4){
    System.out.println("Your lucky number is 4. Cool");
    //ELSE STATEMENT DOESNT COMPILE ... ((not a big deal right now))
    //else{
    //System.out.println("Start Over. You've done it all wrong");
    //i = 0;
    }okay I see that the scanner works this way, but when I copy-pasted that whole section of my code from "Scanner input = " down, it wouldn't compile at that first line.
    I had named it "Scanner input = new2 Scanner(System.in);"
    How can I make another user input position with the scanner?
    Message was edited by:
    tark_theshark

  • Owb - Capturing user input classes

    Hi,
    I'm using OWB 9.2.0.3 and I'm looking at creating some OMB*Plus scripts to deploy (instead of using the GUI)
    I noticed in the sample code (on OTN) for OWB, some classes for "capturing user inputs" in OMB*Plus. I think that this would be a great addition to my scripts (instead of hard coding userid and password).
    How do I get this to work? What do I do with these classes? where to put them? and would you have any documentation on how to code this in OMB*Plus.
    Thank you very much.
    Guy LaBelle

    Guy,
    The description is missing... and I will submit this right away to be added. The link will be with the location of the downloadable file. Will be there within the next couple of days.
    Now, without the screenshots (hope this helps to some extend):
    The omb_params zip file contains classes for a generic modal dialog that can be used from OMBPlus for capturing user input. It will support parameters that are text or passwords. If you unzip this file into owb\bin\admin you can try the dialog from OMBPlus.
    The Java can be invoked by calling as follows;
    # java::new oracle.owb.samples.CaptureParams {
    # display_string_list display string for dialog ie. {"Hostname", "Port", "Service"}
    # param_name_list to query after dialog is complete ie. {"vhostname", "vport", "vservice"}
    # param_type_list STRING or STRINGHIDE or list of tokens (comma separated) for combo box
    # title_string_for_dialog Title for the dialog.
    # dialog_prompt_string Prompt string for dialog.
    or
    # java::new oracle.owb.samples.CaptureParams {
    # display_string_list display string for dialog
    # param_name_list to query after dialog is complete
    # param_type_list STRING or STRINGHIDE or list of tokens (comma separated) for combo box
    # title_string_for_dialog
    # dialog_prompt_string
    # ok_button_string
    # cancel_button_string
    or
    # java::new oracle.owb.samples.CaptureParams
    # title_string_for_dialog
    # dialog_prompt_string
    # ok_button_string
    # cancel_button_string
    There is a Java accessor methiod named 'okButton' that will return a boolean (in Java), the Tcl shell will return 0 for false, and 1 for true. This can be used to determine if the user has pressed the OK or cancel button. Since the user can define the text for these buttons, they can be used for Yes/No style questions for example.
    5.1 Example to capture user input;
    The following dialog can be created with the Tcl below;
    The Tcl to create this dialog is show below, this creates a modal dialog to capture the user input for username, password (in password field), connection string and an option selectable from a combo box;
    set pars [java::new {String[][]} 3 {{"User" "Password" "Connect" "Option"} {"user" "pass" "connect" "option"} {"STRING"
    "STRINGHIDE" "STRING" "thick,thin"}} ]
    set jtitle "OWB Migration"
    set jprompt "Please enter migration properties:"
    set paramList [java::new oracle.owb.samples.CaptureParams $pars $jtitle $jprompt]
    # To check whether OK or cancel is pressed used retrieve okButton/cancelButton on object, then check value (0 - false, 1 - true)
    set okpressed [$paramList okButton]
    # To retrieve the parameters invoke getValue passing the parameter name, the user is stord in a variable (for example);
    set userval [$paramList getValue "user"]
    set passval [$paramList getValue "pass"]
    set connectval [$paramList getValue "connect"]
    set optionval [$paramList getValue "option"]
    5.2 Example to create a question-style dialog;
    set paramList [java::new oracle.owb.samples.CaptureParams "OWB Dimensional Design" "Do you want to create a cube?" "Yes" "No"]
    Like the example above the 'okButton'/'cancelButton' methods can be used to query the button that was selected.
    Thanks,
    Mark.

  • Linking user input to class

    Hello there,
    I have some code that records a ball around the screen for 30seconds, but i am trying to make this length to the users discretion. I have a seperate class which askes for the user input but I can not link this input to the lengh of scene integeger. I was told to use global variables but I have tried but it gives me 2 errors in my class where I have tried to add the userinput to the time frame;
    1. ; expected
    2.Cannot resolve symbol variable string
    here is the code where I have declared the global variable;
    public class Example2 extends JFrame implements ActionListener {
    public static String inputValue;
    public void actionPerformed(ActionEvent e) {
         if (e.getActionCommand().equals("Timer")) {
    String inputValue = JOptionPane.showInputDialog("Length Of Scene");
    System.out.println("Length of Scene " + inputValue);
    and here's the code where I have tried to link the user input to the lengh of scene;
    public class Example extends Panel implements TalktativeGuy, MouseListener
         int timeFrame = String Example2.inputValue;
    any suggestions?

    Scope is the key.
        public static String inputValue;
        public void actionPerformed(ActionEvent e) {
            if (e.getActionCommand().equals("Timer")) {
                String inputValue = JOptionPane.showInputDialog("Length Of Scene"); The first statement is a member variable in class scope (by definition). It appears not to be instantiated and so has the value null. The last statement is a local variable urelated to the first statement. If you remove the type (String) from the last statement then it becomes the instantiation/assignment for the first statement (which will no longer be null).
    About the two errors you listed: the stack trace will tell you what class each is in, the sequence of method calls in the class and usually will also tell you the line number where the trouble lies. You can use this information to track down the errors.

  • Help needed, Createing Dynamic User input

    Hello,
    I am attempting to create some dynamic user input by "predicting" what the user requires in a text box.
    For example if the user enters "Smi" I have a select list pop up which gives the user all options that begin with "Smi".
    I am able to achieve the popups but the interface is quite jerky and not terribly responsive I am trying to solve this by using a thread which starts and stops when new input is received but it is still not quite right.
    The program uses a Sorted TreeSet to hold the data (I thought this would give me a quick search time) and a simple interface at this stage.
    Any help would be fantastic
    Thanks in advance :P
    import java.io.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.text.*;
    import java.util.*;
       /** This program represents part of a larger user interface for allowing the
       user to select data from a file or database.
       <p>
       When the program starts up, it will read in data from a given file, and hold
       it in some type of container allowing rapid access.
       <p>
       The user may then type in the first few letters of the surname of a person,
       and this program should immediately present in a popup dialog the names which
       match.  The user will be able to click on one of the names in the popup and
       that will cause all data about that person to be displayed in the JTextArea
       at the bottom of the window.
       <p>
       This program requires the FormLayout.class, FormLayout$Placement.class, and
       FormLayout$Constraint.class files in the same directory
       (folder) or in its classpath.  These is provided separately.
    class PartMatch extends JFrame implements Runnable
                        /** Close down the program. */
       JButton quitbtn;
                        /** Field for the surname. */
       JTextField namefld;
                        /** Full details of the person(s). */
       JTextArea  results;
                        /** Popup dialog to display the names and addresses which
                        match the leading characters given in namefld. */
       Chooser matches;
                      /** Default background color for a window. */
       final static  Color            defBackground = new Color(0xD0C0C0);
                      /** Default foreground color for a window. */
       final static  Color            defForeground = new Color(0x000000);
                      /** Default background color for a field */
       final static  Color            fldBackground = new Color(0xFFFFFF);
                      /** Default background color for a button */
       final static  Color            btnBackground = new Color(0xF0E0E0);
       final static  Color            dkBackground = new Color(0xB0A0A0);
                      /** Larger font */
       final static  Font bold = new Font("Helvetica", Font.BOLD, 30);
       TreeSet members;
       String input;
       String[] found;
       public static void main(String arg[])
          UIManager.put("TextField.background",fldBackground);
          UIManager.put("TextField.foreground",defForeground);
          UIManager.put("TextField.selectionBackground",btnBackground);
          UIManager.put("TextArea.background",fldBackground);
          UIManager.put("TextArea.foreground",defForeground);
          UIManager.put("TextArea.selectionBackground",btnBackground);
          UIManager.put("Panel.background",defBackground);
          UIManager.put("Label.background",defBackground);
          UIManager.put("Label.foreground",defForeground);
          UIManager.put("Button.background",btnBackground);
          UIManager.put("Button.foreground",defForeground);
          UIManager.put("CheckBox.background",defBackground);
          UIManager.put("ScrollBar.background",defBackground);
          UIManager.put("ScrollBar.thumb",btnBackground);
          UIManager.put("ComboBox.background",btnBackground);
          UIManager.put("ComboBox.selectionBackground",dkBackground);
          PartMatch trial = new PartMatch(arg);
       public PartMatch( String [] arg )
          super("Part Match");
          setDefaultCloseOperation(EXIT_ON_CLOSE);
          Container cpane = getContentPane();
          FormLayout form = new FormLayout(cpane);
          JLabel lab1 = new JLabel("Fetch details") ;
          lab1.setFont( bold );
          form.setTopAnchor( lab1, 4 );
          form.setLeftAnchor( lab1, 4 );
          JLabel lab2 = new JLabel("Surname: ") ;
          form.setTopRelative( lab2, lab1, 4 );
          form.setLeftAlign( lab2, lab1 );
          namefld = new JTextField( 30 );
          form.setBottomAlign( namefld, lab2 );
          form.setLeftRelative( namefld, lab2, 4 );
          namefld.addCaretListener( new CaretListener()
             public void caretUpdate(CaretEvent e)
                 showMatches();
          quitbtn = new JButton( "Quit" );
          quitbtn.addActionListener( new ActionListener()
             public void actionPerformed(ActionEvent e)
                quitProcessing();
          form.setBottomAlign( quitbtn, namefld );
          form.setLeftRelative( quitbtn, namefld, 15 );
          results = new JTextArea( 10,50 );
          results.setEditable(false);
          JScrollPane jsp = new JScrollPane( results,
                                     JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                                     JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
          form.setTopRelative( jsp, lab2, 6 );
          form.setLeftAlign( jsp, lab2 );
          form.setBottomAnchor( jsp, 5 );
          form.setRightAnchor( jsp, 5 );
          form.setRightAnchor( quitbtn, 5 );
          matches = new Chooser( this );
          //matches.setUndecorated(true);
          pack();
          setVisible(true);
          namefld.requestFocus();
          if (arg.length > 0) init(arg[0]);
          else init("triathlon.txt"); //<<<<<<<<<<<<<<<< Place the default filename here
          /** Called once only, at the end of the constructor, to read the data
            * from the membership file.
       public void init( String fname )
          members = new TreeSet();
           try {
               FileReader fr = new FileReader(new File (fname));
               Scanner scan = new Scanner(fr);
               trimember cmem;
               String cLine, eTag, memberNo, first, last, gender, yob, tel ,addr,
                       club;
               while(scan.hasNextLine())
                   cLine = scan.nextLine();
                   Scanner scan2 = new Scanner(cLine);
                   scan2.useDelimiter(";");
                   eTag = scan2.next().trim();
                   memberNo = scan2.next().trim();
                   first = scan2.next().trim();
                   last = scan2.next().trim();
                   gender = scan2.next().trim();
                   yob = scan2.next().trim();
                   tel = scan2.next().trim();
                   addr = scan2.next().trim();
                   club = scan2.next().trim();
                   cmem = new trimember(eTag, memberNo, first, last, gender, yob,
                           tel, addr, club);
                   members.add(cmem);
           catch (FileNotFoundException ex)
               results.append("Sorry can't find the input file\n");
               results.append("Please check file name and location and try again");
               ex.printStackTrace();
          /** Called every time there is a change in the contents of the text field
            * namefld.  It will first clear the text area.  It then needs to search
            * through the container of data to find all records where the surname
            * starts with the characters that have been typed.  The names and
            * addresses need to be set up as strings and placed in
            * an array of Strings.  This can be placed in the "matches" window and
            * displayed for the user, inviting one to be selected.
            * <p>
            * The performance of this is very important.  If necessary, it may be
            * necessary to run as a separate thread so that the user interface is
            * not delayed.  It is essential that the user be able to type letters at a
            * reasonable speed and not have the keystroke processing held up by
            * previous text.
       public void showMatches( )
           run();
                // First clear the text area
          //results.setText("");
                // Determine the leading characters of the surname that is wanted
                input = namefld.getText();
                // Locate the data for this name, and display each matching item
                //  in the JTextArea ...
                // Example of how to set the data in the popup dialog
          matches.list.setListData(found);
          matches.pack();   // resize the popup
                // set the location of the popup if it is not currently visible
          if ( ! matches.isVisible())
             Dimension sz = matches.getSize();
             Point mouse = getMousePosition();
             Point framepos = getLocation();
             int x=0, y=0;
             if (mouse == null)
                Point pt = results.getLocation();
                x = pt.x + 20 + framepos.x;
                y = pt.y + 20 + framepos.y;
             else
                x = mouse.x - 2 + framepos.x;
                y = mouse.y - 2 + framepos.y;
             matches.setLocation(x,y);
          matches.setVisible(true);
          namefld.requestFocus();
          /** Perform any final processing before closing down.
       public void quitProcessing( )
          // Any closing work.  Then
          System.exit(0);
        public void run()
            ArrayList<String> foundit = new ArrayList<String>();
            System.out.println(input);
            if(input != null)
            Iterator it = members.iterator();
            while(it.hasNext())
               trimember test = (trimember) it.next();
               if (test.last.startsWith(input))
                   foundit.add(test.last +", "+ test.first);
            found = new String[foundit.size()];
            for(int i=0; i<foundit.size();i++)
                found[i] = foundit.get(i);
         /** A window for displaying names and addresses from the data set which
          match the leading characters in namefld.
          <p>
          This will automatically pop down if the user moves the mouse out of the
          window.
          <p>
          It needs code added to it to respond to the user clicking on an item in
          the displayed list. */
       class Chooser extends JWindow
                /** To display a set of names and addresses that match the leading
                characters of the namefld text field. */
          public JList list = new JList();
          Chooser( JFrame parent )
             super( parent );
             Container cpane = getContentPane();
             cpane.addMouseListener( new MouseAdapter()
                public void mouseExited(MouseEvent e)
                   Chooser.this.setVisible(false);
             cpane.add("Center",list);
             list.addListSelectionListener( new ListSelectionListener()
                public void valueChanged(ListSelectionEvent e)
                   Chooser.this.setVisible(false);
                   System.out.println("ValueChanged");
                   // First clear the text area
                   results.setText("");
                   String in = (String) list.getSelectedValue();
                   System.out.println("Selected Value was : "+in);
                   String[] inlf = in.split(", ");
                   System.out.println("inlf[0]:"+inlf[0]+" inlf[1]:"+inlf[1]);
                   results.append("Surname \tFirst \teTag \tMemberNo \tSex \tYOB " +
                           "\tTel \tAddress \t\t\tClub\n");
                   Iterator it = members.iterator();
                   while(it.hasNext())
                       trimember test = (trimember) it.next();
                       if (test.last.equals(inlf[0])&&test.first.equals(inlf[1]))
                           results.append(test.toString()+"\n");
                   namefld.requestFocus();
          public class trimember implements Comparable
           String eTag;
           public String memberNo;
           public String first;
           public String last;
           String gender;
           String yob;
           String tel;
           String addr;
           String club;
           public trimember(String eT, String me, String fi, String la,
                   String ge, String yo, String te, String ad, String cl)
               eTag = eT;
               memberNo = me;
               first = fi;
               last = la;
               gender = ge;
               yob = yo;
               tel = te;
               addr = ad;
               club = cl;         
           //To String method to output string of details
           public String toString()
               return last + "\t" + first + "\t" + eTag + "\t" +
                       memberNo + "\t" + gender + "\t" + yob + "\t"+ tel + "\t" +
                       addr + "\t" + club;
           //Compare and sort on Last name
           public int compareTo(Object o)
               trimember com = (trimember) o;
               int lastCmp = last.compareTo(com.last);
               int firstCmp = first.compareTo(com.first);
               int memCmp = memberNo.compareTo(com.memberNo);
               if (lastCmp == 0 && firstCmp !=0)return firstCmp;
               else if (lastCmp==0&&firstCmp==0)return memCmp;
               else return lastCmp;
    }

    Please don't cross-post. It is considered very rude to do that here:
    http://forum.java.sun.com/thread.jspa?messageID=9953193

  • Help needed, Providing Dynamic User input

    Hello,
    I am attempting to create some dynamic user input by "predicting" what the user requires in a text box.
    For example if the user enters "Smi" I have a select list pop up which gives the user all options that begin with "Smi".
    I am able to achieve the popups but the interface is quite jerky and not terribly responsive I am trying to solve this by using a thread which starts and stops when new input is received but it is still not quite right.
    The program uses a Sorted TreeSet to hold the data (I thought this would give me a quick search time) and a simple interface at this stage.
    Any help would be fantastic
    Thanks in advance :P
    import java.io.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.text.*;
    import java.util.*;
       /** This program represents part of a larger user interface for allowing the
       user to select data from a file or database.
       <p>
       When the program starts up, it will read in data from a given file, and hold
       it in some type of container allowing rapid access.
       <p>
       The user may then type in the first few letters of the surname of a person,
       and this program should immediately present in a popup dialog the names which
       match.  The user will be able to click on one of the names in the popup and
       that will cause all data about that person to be displayed in the JTextArea
       at the bottom of the window.
       <p>
       This program requires the FormLayout.class, FormLayout$Placement.class, and
       FormLayout$Constraint.class files in the same directory
       (folder) or in its classpath.  These is provided separately.
    class PartMatch extends JFrame implements Runnable
                        /** Close down the program. */
       JButton quitbtn;
                        /** Field for the surname. */
       JTextField namefld;
                        /** Full details of the person(s). */
       JTextArea  results;
                        /** Popup dialog to display the names and addresses which
                        match the leading characters given in namefld. */
       Chooser matches;
                      /** Default background color for a window. */
       final static  Color            defBackground = new Color(0xD0C0C0);
                      /** Default foreground color for a window. */
       final static  Color            defForeground = new Color(0x000000);
                      /** Default background color for a field */
       final static  Color            fldBackground = new Color(0xFFFFFF);
                      /** Default background color for a button */
       final static  Color            btnBackground = new Color(0xF0E0E0);
       final static  Color            dkBackground = new Color(0xB0A0A0);
                      /** Larger font */
       final static  Font bold = new Font("Helvetica", Font.BOLD, 30);
       TreeSet members;
       String input;
       String[] found;
       public static void main(String arg[])
          UIManager.put("TextField.background",fldBackground);
          UIManager.put("TextField.foreground",defForeground);
          UIManager.put("TextField.selectionBackground",btnBackground);
          UIManager.put("TextArea.background",fldBackground);
          UIManager.put("TextArea.foreground",defForeground);
          UIManager.put("TextArea.selectionBackground",btnBackground);
          UIManager.put("Panel.background",defBackground);
          UIManager.put("Label.background",defBackground);
          UIManager.put("Label.foreground",defForeground);
          UIManager.put("Button.background",btnBackground);
          UIManager.put("Button.foreground",defForeground);
          UIManager.put("CheckBox.background",defBackground);
          UIManager.put("ScrollBar.background",defBackground);
          UIManager.put("ScrollBar.thumb",btnBackground);
          UIManager.put("ComboBox.background",btnBackground);
          UIManager.put("ComboBox.selectionBackground",dkBackground);
          PartMatch trial = new PartMatch(arg);
       public PartMatch( String [] arg )
          super("Part Match");
          setDefaultCloseOperation(EXIT_ON_CLOSE);
          Container cpane = getContentPane();
          FormLayout form = new FormLayout(cpane);
          JLabel lab1 = new JLabel("Fetch details") ;
          lab1.setFont( bold );
          form.setTopAnchor( lab1, 4 );
          form.setLeftAnchor( lab1, 4 );
          JLabel lab2 = new JLabel("Surname: ") ;
          form.setTopRelative( lab2, lab1, 4 );
          form.setLeftAlign( lab2, lab1 );
          namefld = new JTextField( 30 );
          form.setBottomAlign( namefld, lab2 );
          form.setLeftRelative( namefld, lab2, 4 );
          namefld.addCaretListener( new CaretListener()
             public void caretUpdate(CaretEvent e)
                 showMatches();
          quitbtn = new JButton( "Quit" );
          quitbtn.addActionListener( new ActionListener()
             public void actionPerformed(ActionEvent e)
                quitProcessing();
          form.setBottomAlign( quitbtn, namefld );
          form.setLeftRelative( quitbtn, namefld, 15 );
          results = new JTextArea( 10,50 );
          results.setEditable(false);
          JScrollPane jsp = new JScrollPane( results,
                                     JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                                     JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
          form.setTopRelative( jsp, lab2, 6 );
          form.setLeftAlign( jsp, lab2 );
          form.setBottomAnchor( jsp, 5 );
          form.setRightAnchor( jsp, 5 );
          form.setRightAnchor( quitbtn, 5 );
          matches = new Chooser( this );
          //matches.setUndecorated(true);
          pack();
          setVisible(true);
          namefld.requestFocus();
          if (arg.length > 0) init(arg[0]);
          else init("triathlon.txt"); //<<<<<<<<<<<<<<<< Place the default filename here
          /** Called once only, at the end of the constructor, to read the data
            * from the membership file.
       public void init( String fname )
          members = new TreeSet();
           try {
               FileReader fr = new FileReader(new File (fname));
               Scanner scan = new Scanner(fr);
               trimember cmem;
               String cLine, eTag, memberNo, first, last, gender, yob, tel ,addr,
                       club;
               while(scan.hasNextLine())
                   cLine = scan.nextLine();
                   Scanner scan2 = new Scanner(cLine);
                   scan2.useDelimiter(";");
                   eTag = scan2.next().trim();
                   memberNo = scan2.next().trim();
                   first = scan2.next().trim();
                   last = scan2.next().trim();
                   gender = scan2.next().trim();
                   yob = scan2.next().trim();
                   tel = scan2.next().trim();
                   addr = scan2.next().trim();
                   club = scan2.next().trim();
                   cmem = new trimember(eTag, memberNo, first, last, gender, yob,
                           tel, addr, club);
                   members.add(cmem);
           catch (FileNotFoundException ex)
               results.append("Sorry can't find the input file\n");
               results.append("Please check file name and location and try again");
               ex.printStackTrace();
          /** Called every time there is a change in the contents of the text field
            * namefld.  It will first clear the text area.  It then needs to search
            * through the container of data to find all records where the surname
            * starts with the characters that have been typed.  The names and
            * addresses need to be set up as strings and placed in
            * an array of Strings.  This can be placed in the "matches" window and
            * displayed for the user, inviting one to be selected.
            * <p>
            * The performance of this is very important.  If necessary, it may be
            * necessary to run as a separate thread so that the user interface is
            * not delayed.  It is essential that the user be able to type letters at a
            * reasonable speed and not have the keystroke processing held up by
            * previous text.
       public void showMatches( )
           run();
                // First clear the text area
          //results.setText("");
                // Determine the leading characters of the surname that is wanted
                input = namefld.getText();
                // Locate the data for this name, and display each matching item
                //  in the JTextArea ...
                // Example of how to set the data in the popup dialog
          matches.list.setListData(found);
          matches.pack();   // resize the popup
                // set the location of the popup if it is not currently visible
          if ( ! matches.isVisible())
             Dimension sz = matches.getSize();
             Point mouse = getMousePosition();
             Point framepos = getLocation();
             int x=0, y=0;
             if (mouse == null)
                Point pt = results.getLocation();
                x = pt.x + 20 + framepos.x;
                y = pt.y + 20 + framepos.y;
             else
                x = mouse.x - 2 + framepos.x;
                y = mouse.y - 2 + framepos.y;
             matches.setLocation(x,y);
          matches.setVisible(true);
          namefld.requestFocus();
          /** Perform any final processing before closing down.
       public void quitProcessing( )
          // Any closing work.  Then
          System.exit(0);
        public void run()
            ArrayList<String> foundit = new ArrayList<String>();
            System.out.println(input);
            if(input != null)
            Iterator it = members.iterator();
            while(it.hasNext())
               trimember test = (trimember) it.next();
               if (test.last.startsWith(input))
                   foundit.add(test.last +", "+ test.first);
            found = new String[foundit.size()];
            for(int i=0; i<foundit.size();i++)
                found[i] = foundit.get(i);
         /** A window for displaying names and addresses from the data set which
          match the leading characters in namefld.
          <p>
          This will automatically pop down if the user moves the mouse out of the
          window.
          <p>
          It needs code added to it to respond to the user clicking on an item in
          the displayed list. */
       class Chooser extends JWindow
                /** To display a set of names and addresses that match the leading
                characters of the namefld text field. */
          public JList list = new JList();
          Chooser( JFrame parent )
             super( parent );
             Container cpane = getContentPane();
             cpane.addMouseListener( new MouseAdapter()
                public void mouseExited(MouseEvent e)
                   Chooser.this.setVisible(false);
             cpane.add("Center",list);
             list.addListSelectionListener( new ListSelectionListener()
                public void valueChanged(ListSelectionEvent e)
                   Chooser.this.setVisible(false);
                   System.out.println("ValueChanged");
                   // First clear the text area
                   results.setText("");
                   String in = (String) list.getSelectedValue();
                   System.out.println("Selected Value was : "+in);
                   String[] inlf = in.split(", ");
                   System.out.println("inlf[0]:"+inlf[0]+" inlf[1]:"+inlf[1]);
                   results.append("Surname \tFirst \teTag \tMemberNo \tSex \tYOB " +
                           "\tTel \tAddress \t\t\tClub\n");
                   Iterator it = members.iterator();
                   while(it.hasNext())
                       trimember test = (trimember) it.next();
                       if (test.last.equals(inlf[0])&&test.first.equals(inlf[1]))
                           results.append(test.toString()+"\n");
                   namefld.requestFocus();
          public class trimember implements Comparable
           String eTag;
           public String memberNo;
           public String first;
           public String last;
           String gender;
           String yob;
           String tel;
           String addr;
           String club;
           public trimember(String eT, String me, String fi, String la,
                   String ge, String yo, String te, String ad, String cl)
               eTag = eT;
               memberNo = me;
               first = fi;
               last = la;
               gender = ge;
               yob = yo;
               tel = te;
               addr = ad;
               club = cl;         
           //To String method to output string of details
           public String toString()
               return last + "\t" + first + "\t" + eTag + "\t" +
                       memberNo + "\t" + gender + "\t" + yob + "\t"+ tel + "\t" +
                       addr + "\t" + club;
           //Compare and sort on Last name
           public int compareTo(Object o)
               trimember com = (trimember) o;
               int lastCmp = last.compareTo(com.last);
               int firstCmp = first.compareTo(com.first);
               int memCmp = memberNo.compareTo(com.memberNo);
               if (lastCmp == 0 && firstCmp !=0)return firstCmp;
               else if (lastCmp==0&&firstCmp==0)return memCmp;
               else return lastCmp;
    }Edited by: Roger on Nov 3, 2007 11:50 AM

    Please don't cross-post. It is considered very rude to do that here:
    http://forum.java.sun.com/thread.jspa?threadID=5233033&messageID=9953169#9953169

  • Showing user input in a JFrame

    i need to be able to take user-given values and display them in a JFrame. i'm testing the input of a sudoku puzzle. i have a sudokuComponent and a sudokuViewer.
    i'm confused as to where to place my code that will do the process of taking user input (via Scanner class) and testing it for certain conditions.
    i dont think figuring out the testing conditions should be hard, i'm just having trouble with getting the input read in correctly and a way of getting it displayed on the JFrame which displays the sudoku puzzle with the values so far.
    i was given a tip that said i needed to use the method repaint() of JFrame to see the updates.
    SUDOKUCOMPONENT
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import java.awt.geom.Line2D;
    import javax.swing.JPanel;
    import javax.swing.JComponent;
    import java.util.Scanner;
    public class SudokuComponent extends JComponent
         public void paintComponent(Graphics g)
              //recover graphics2s
              Graphics2D g2 = (Graphics2D) g;
              //Construct the Sudoku square
              Rectangle box = new Rectangle(20, 20, 270, 270);
              g2.draw(box);
              g2.draw(new Line2D.Double(20, 110, 290, 110)); //horizontal
              g2.draw(new Line2D.Double(20, 200, 290, 200));
              g2.draw(new Line2D.Double(110, 20, 110, 290)); //vertical
              g2.draw(new Line2D.Double(200, 20, 200, 290));
    }SUDOKUVIEWER
    import javax.swing.JFrame;
    import java.util.Scanner;
    public class SudokuViewer
       public static void main(String[] args)
          JFrame frame = new JFrame();
          final int FRAME_WIDTH = 350;
          final int FRAME_HEIGHT = 350;
          frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
          frame.setTitle("Sudoku Viewer");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          SudokuComponent component = new SudokuComponent();
          frame.add(component);
          frame.setVisible(true);
    }

    I have improved your application to show how it can be programmed.
    For more information you can see about
    KeyListener:
    http://java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html
    MouseListener:
    http://java.sun.com/docs/books/tutorial/uiswing/events/mouselistener.html
    and of course use repaint() when you want to update your component
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.geom.Line2D;
    import java.util.LinkedList;
    import java.util.List;
    import javax.swing.JComponent;
    public class SudokuComponent extends JComponent {
        SudokuElement currentElement = new SudokuElement();
        List<SudokuElement> elementList = new LinkedList<SudokuElement>();
        public SudokuComponent(){
            addMouseListener(new MyMouseListener());
            setFocusable(true);
            addKeyListener(new MyKeyListener());
        public void paintComponent(Graphics g) {
            //public void paint(Graphics g) {
            //recover graphics2s
            Graphics2D g2 = (Graphics2D) g;
            //Construct the Sudoku square
            Rectangle box = new Rectangle(20, 20, 270, 270);
            g2.draw(box);
            g2.draw(new Line2D.Double(20, 110, 290, 110)); //horizontal
            g2.draw(new Line2D.Double(20, 200, 290, 200));
            g2.draw(new Line2D.Double(110, 20, 110, 290)); //vertical
            g2.draw(new Line2D.Double(200, 20, 200, 290));
            // show place where user can type a digit
            g2.draw(new Line2D.Double(currentElement.x - 10, currentElement.y, currentElement.x + 10, currentElement.y));
            // show all typed digits
            for(SudokuElement elem : elementList ){
               g2.drawString(elem.digit + "", elem.x, elem.y);
        class SudokuElement {
            int digit;
            int x;
            int y;
            SudokuElement getCopy(){
                SudokuElement elem = new SudokuElement();
                elem.x = x;
                elem.y = y;
                elem.digit= digit;
                return elem;
        class MyMouseListener extends MouseAdapter {
            public void mouseClicked(MouseEvent e) {
                System.out.println("mouse clicked: x = "  + e.getX() + " y = " + e.getY());
                currentElement.x = e.getX();  // It is better to use local coordinats 0 .. 9
                currentElement.y = e.getY();
                repaint(); 
        class MyKeyListener extends KeyAdapter {
            public void keyTyped(KeyEvent e) {
                char ch = e.getKeyChar();
                System.out.println("char typed= " + ch);
                if( Character.isDigit(ch) ){  // Filter only digits
                    currentElement.digit = Character.digit(ch, 10);
                    elementList.add(currentElement.getCopy());
                    repaint();
    }

  • User input in loop

    For some reason I could not find information about user input in the first chapters of my programming book, therefore I decided to find out on my own. using google gave me a few hints, but I cannot figure out how to solve this problem: when trying to assign the same variable a new value I get a error. how would you solve this?
    program:
    package henke;
    import java.util.Scanner;
    public class Main {
        public static void main(String[] args) {
           System.out.println("\n\n\t\t\tWelcome to the 'guess my number' game!\n");
           while(true){
               System.out.println("\nChose your option: \n" +
                   "1\) Guess the random number!\n" +
                   "2\) Make the computer guess your number!\n" +
                   "3\) Exit\n");
               int option;
               Scanner in = new Scanner(System.in);
               System.out.print("Your option: ");
               option = in.nextInt();
               in.close();
               if(option == 1){
                   System.out.println("Not built yet. ");
               else if(option == 2){
                   System.out.println("Will be built last. ");
               else if(option == 3){
                   break;
               else{
                   System.out.println("Illegal option.. ");
    }output including error messages:
    run:
                            Welcome to the 'guess my number' game!
    Chose your option:
    1) Guess the random number!
    2) Make the computer guess your number!
    3) Exit
    Your option: 1
    Not built yet.
    Chose your option:
    1) Guess the random number!
    2) Make the computer guess your number!
    3) Exit
    Exception in thread "main" java.util.NoSuchElementException
            at java.util.Scanner.throwFor(Scanner.java:838)
            at java.util.Scanner.next(Scanner.java:1461)
            at java.util.Scanner.nextInt(Scanner.java:2091)
            at java.util.Scanner.nextInt(Scanner.java:2050)
            at henke.Main.main(Main.java:18)
    Your option: Java Result: 1
    BUILD SUCCESSFUL (total time: 1 second)

    thanks for the links. some googling made it possible for me to finish this script. It might be somewhat messy since I have just written it (no complaints about the output though). and oh, I didn't finish the 'while ... and ...' loop somwhere in there since I didn't have the energy. I should really go to sleep now. bye
    package javaapplication;
    import java.util.Scanner;
    public class Main {
        public static void main(String[] args) {
        System.out.println("\n\n\t\t\tWelcome to the 'guess my number' game!\n");
    //    Startup delay
        System.out.print("|");
            for(int i = 0; i <= 30; i++) {
                 System.out.print("=");
                 try {
                     Thread.sleep(300);
                 catch (InterruptedException ie){
        System.out.println("|\nJob's done!");
                //Den stora loopen
           while(true){
               System.out.println("\nChose your option: \n" +
                   "1) Guess the random number!\n" +
                   "2) Make the computer guess your number!\n" +
                   "3) Quit\n");
               Scanner in = new Scanner(System.in);
               System.out.print("Your option: ");
               int option = in.nextInt();
               //in.close();
               //Guess the random number!
               if(option == 1){
                   System.out.print("Number of possibilities: ");
                   int numPosA = in.nextInt();
                   int secretA = (int)(Math.random()*numPosA);
                   int iA = 0;
                   while(true){
                       iA++;
                       System.out.print("Your guess: (between 0 and "+ (numPosA -1)+ ") ");
                       int guessA = in.nextInt();
                       if(guessA == secretA){
                           System.out.println("Correct! The secret number is "+ secretA+
                                   " - you guessed "+ guessA+ "! It only took you "+ iA+
                                   " guesses!");
                           System.out.println("\nPress enter to return to the main menu. ");
                           try {
                               System.in.read();
                           } catch (java.io.IOException ie) {}
                           break;
                   else if(guessA > secretA){
                       System.out.println("To high. Try again. ");
                   else if(guessA < secretA){
                       System.out.println("To low. Try again. ");
                   else{
                       System.out.println("Illegal option. ");
               //Make the computer guess your number!
               else if(option == 2){
                   System.out.print("Number of possibilities: ");
                   int numPosB = in.nextInt();
                   //while(secretB >= 1) and (secretB <= numPosB){
                   System.out.print("The secret number: (has to be between 1 and "
                           + numPosB+ ") ");
                   int secretB = in.nextInt();
                   int iB = 0;
                   while(true){
                       iB++;
                       int guessB = (int)(Math.random()*numPosB+1);
                       if(guessB == secretB){
                           System.out.println("The computer figured out your secret number! "+
                                   "The computer guessed "+ guessB+ " - and your secret number is "+
                                   secretB+ ". It took "+ iB+ " random numbers!");
                           System.out.println("\nPress enter to return to the main menu. ");
                           try {
                               System.in.read();
                           } catch (java.io.IOException ie) {}
                           break;
                       else if(iB >= numPosB * 2){
                           System.out.print("The computer has guessed "+ (numPosB * 2)+ " times."+
                                   "no more chances!");
                           System.out.println("\nPress enter to return to the main menu. ");
                           try {
                               System.in.read();
                           } catch (java.io.IOException ie) {}
                           break;
               //Quit
               else if(option == 3){
                   break;
               //Else
               else{
                   System.out.println("Illegal option.. ");
    }

  • User input; how to account for unlimited names typed in

    So, I finally figured out how to write a program that, given the input of three names, can replace any one of the given names with anything the user wants.
    My problem is that it only works for three names, and apparently, my professor wants the program to work for as many names as the user puts in (ie, a user can input 10, 100, 5000 names, and the program will replace any one of those names with anything else).
    I have no idea in the world how to do this. How can you extract the name "pieces" from the user-inputed string?
    Help is GREATLY appreciated!
    Here is the code for the three-name-only program, but I don't know if it can be modified.
    import java.util.Scanner;
    public class Rename
    public static void main(String args[])
    Scanner in = new Scanner(System.in);
    String name, first, middle, last, space;
    space = " ";
    System.out.print("Type your whole name: ");
    name = in.nextLine();
    first = name.substring(0, name.indexOf(space));
    name = name.substring(name.indexOf(space)+1, name.length());
    middle= name.substring(0, name.indexOf(space));
    last = name.substring(name.indexOf(space)+1, name.length());
    System.out.print("Which part don't you like? ");
    String dlike = in.nextLine();
    System.out.print("What should it be changed to? ");
    String rep = in.nextLine();
    String kirt, john, bob;
    kirt = first.replace(dlike, rep);
    john = middle.replace(dlike, rep);
    bob = last.replace(dlike, rep);
    if (dlike.equals(first))
    System.out.println("New name: " + kirt + space + middle + space + last);
    else if (dlike.equals(middle))
    System.out.println("New name: " + first + space + john + space + last);
    else
    System.out.println("New name: " + first + space + middle + space + bob);
    }

    Do you have to read in within the program using Scanner? If not, then you could also just let the user submit the names using the args[] array in your main method. This way the names automatically come in a array as long as necessary with all the names.
    Just to clarify:
    User types: java Rename John Bob Roger Whoever
    And in your program:
    public static void main(String[] args){
        // args now contains "John", "Bob", "Roger", and "Whoever"
        // do all your stuff
    }

  • How to add User Inputs?

    Well I'm new to Java, and I was trying to make a basic calculator to add 2 user inputs and give a total. Here is my code:
    import java.util.Scanner;
    public class calculator {
         public static void main(String[] args) {
              int total;
              Scanner number1 = new Scanner(System.in);
              Scanner number2 = new Scanner(System.in);
              System.out.print("Enter your first number: ");
              System.out.println(number1.nextLine());
              System.out.print("Enter your second number: ");
              System.out.println(number2.nextLine());
              total = number1 + number2;
              System.out.print("Your total is: " + total);
    }And here is my error:
    C:\Users\Jennifer\Desktop\Vincent's Things>javac calculator.java
    calculator.java:13: operator + cannot be applied to java.util.Scanner,java.util.
    Scanner
                    total = number1 + number2;
                                    ^
    1 errorI tried giving it a cast, since it's saying Scanner's can't be operated, such as:
              total = (int)number1 + (int)number2;But that didn't work. How can I make it so it adds the two inputs?

    A Scanner is a Scanner. Of course you can't just add two Scanners together. The Scanner could also be used to read text. A Scanner can't read your mind to know what type of data you are reading. You have to tell the Scanner what type of data you are reading. They way you do that is to read the Scanner API and use the proper methods.

  • Need help with Java app for user input 5 numbers, remove dups, etc.

    I'm new to Java (only a few weeks under my belt) and struggling with an application. The project is to write an app that inputs 5 numbers between 10 and 100, not allowing duplicates, and displaying each correct number entered, using the smallest possible array to solve the problem. Output example:
    Please enter a number: 45
    Number stored.
    45
    Please enter a number: 54
    Number stored.
    45 54
    Please enter a number: 33
    Number stored.
    45 54 33
    etc.
    I've been working on this project for days, re-read the book chapter multiple times (unfortunately, the book doesn't have this type of problem as an example to steer you in the relatively general direction) and am proud that I've gotten this far. My problems are 1) I can only get one item number to input rather than a running list of the 5 values, 2) I can't figure out how to check for duplicate numbers. Any help is appreciated.
    My code is as follows:
    import java.util.Scanner; // program uses class Scanner
    public class Array
         public static void main( String args[] )
          // create Scanner to obtain input from command window
              Scanner input = new Scanner( System.in);
          // declare variables
             int array[] = new int[ 5 ]; // declare array named array
             int inputNumbers = 0; // numbers entered
          while( inputNumbers < array.length )
              // prompt for user to input a number
                System.out.print( "Please enter a number: " );
                      int numberInput = input.nextInt();
              // validate the input
                 if (numberInput >=10 && numberInput <=100)
                       System.out.println("Number stored.");
                     else
                       System.out.println("Invalid number.  Please enter a number within range.");
              // checks to see if this number already exists
                    boolean number = false;
              // display array values
              for ( int counter = 0; counter < array.length; counter++ )
                 array[ counter ] = numberInput;
              // display array values
                 System.out.printf( "%d\n", array[ inputNumbers ] );
                   // increment number of entered numbers
                inputNumbers++;
    } // end close Array

    Yikes, there is a much better way to go about this that is probably within what you have already learned, but since you are a student and this is how you started, let's just concentrate on fixing what you got.
    First, as already noted by another poster, your formatting is really bad. Formatting is really important because it makes the code much more readable for you and anyone who comes along to help you or use your code. And I second that posters comment that brackets should always be used, especially for beginner programmers. Unfortunately beginner programmers often get stuck thinking that less lines of code equals better program, this is not true; even though better programmers often use far less lines of code.
                             // validate the input
       if (numberInput >=10 && numberInput <=100)
              System.out.println("Number stored.");
      else
                   System.out.println("Invalid number.  Please enter a number within range."); Note the above as you have it.
                         // validate the input
                         if (numberInput >=10 && numberInput <=100)
                              System.out.println("Number stored.");
                         else
                              System.out.println("Invalid number.  Please enter a number within range."); Note how much more readable just correct indentation makes.
                         // validate the input
                         if (numberInput >=10 && numberInput <=100) {
                              System.out.println("Number stored.");
                         else {
                              System.out.println("Invalid number.  Please enter a number within range.");
                         } Note how it should be coded for a beginner coder.
    Now that it is readable, exam your code and think about what you are doing here. Do you really want to print "Number Stored" before you checked to ensure it is not a dupe? That could lead to some really confused and frustrated users, and since the main user of your program will be your teacher, that could be unhealthy for your GPA.
    Since I am not here to do your homework for you, I will just give you some advice, you only need one if statement to do this correctly, you must drop the else and fix the if. I tell you this, because as a former educator i know the first thing running through beginners minds in this situation is to just make the if statement empty, but this is a big no no and even if you do trick it into working your teacher will not be fooled nor impressed and again your GPA will suffer.
    As for the rest, you do need a for loop inside your while loop, but not where or how you have it. Inside the while loop the for loop should be used for checking for dupes, not for overwriting every entry in the array as you currently have it set up to do. And certainly not for printing every element of the array each time a new element is added as your comments lead me to suspect you were trying to do, that would get real annoying really fast again resulting in abuse of your GPA. Printing the array should be in its own for loop after the while loop, or even better in its own method.
    As for how to check for dupes, well, you obviously at least somewhat understand loops and if statements, thus you have all the tools needed, so where is the problem?
    JSG

  • Hashmap from user input

    I am writing a battleship program and I have created an array of xycoordinates in my board class, in my player class i created a method to accept user input for an xy coordinate to place the ship. In my game class (where the main method is in) I want to be able to put this coordinate in the ship hashmap with the ship name.
    I am not sure how to get the user input from my method in the player class to the hashmap in the game class.

    I was originally calling this method when the player selected to play the game. I have created the method in my player class:
    public String placeBships() {
              System.out.println("Enter xy coordinates for: Battleship");
              Scanner blocationxy = new Scanner(System.in);
              String bxycoordinate;
              bxycoordinate = blocationxy.next();
              System.out.println("You Chose " + bxycoordinate);
              return bxycoordinate;
    how do make it return to the Game class?
    I am not sure how to load it to my hashmap "ships". I tried ships.put(myplayer.placeBships());

  • Help With Homework Reading user input into an Array

    This program is to read questions from a file and retrieve user input as answers.
    This program is no where near complete, but I am stuck. (I dont know why, maybe its too late at night)
    I have a total of three classes. I am currently stuck in my main class. See Comments ("What the hell am I printing/ Will this work?"). In this next line of code, i need to read the question from the file to the user, and then accept their input.
    Main Class:
        public static void main(String[] args) {
            try {
            Scanner in = new Scanner(new FileReader("quiz.txt"));
                catch (Exception e) {
                System.out.println(e);
            ArrayList <Questions> Questions = new ArrayList<Questions>();
            ArrayList<String> answers = new ArrayList<String>();
                  for (Questions qu : Questions)
             System.out.println(); //What the hell am I printing.
             String answer = in.nextLine(); //Will this work?
             answers.add(answer); //This should work
          }Questions Class:
    public class Questions {
        String Questions = "";
        public String getQuestions() {
            return Questions;
        public void setQuestions(String Questions) {
            this.Questions = Questions;
        public Questions(String Questions)
            this.Questions = Questions;
    }answers class:
    package QuizRunner;
    * @author Fern
    public class answers {
        String answers = "";
        public String addAnswers() {
            return answers;
        public answers(String answers) {
            this.answers = answers;
        }

    doremifasollatido wrote:
    According to standard Java coding conventions, class names should start with a capital letter (so, your "answers" should be "Answers"). And, variable and method names should start with a lowercase letter (so, your "Questions" should be "questions").
    And classnames should (almost) never be plural words. So it should probably be an 'Answer' and something else containing a collection of those objects called 'answers'.
    Also, *your variable name should not be the same (case-sensitive match) as your class name.* Although it will compile if done syntactically correctly, it is highly confusing! I first wrote this because you did this for both "Questions" and "answers" classes in their class definition, but you also used "Questions" as your variable name in 'main'. (Note that applying the standard capitalization conventions will prevent you from using the same name for your class name as for your variable name, since they should start with different cases.)
    Of course having an 'Answer' called 'answer' is often fine.
    Your Questions class should probably be called "Question", anyway--it looks like it should hold a single question. And, your "answers" class should probably be called "Answer"--it looks like it should hold a single answer. You aren't using your "answers" class anywhere right now, anyway.Correct. There might be room for a class containing a collection of Question objects, but it's unlikely such a class would contain just that and nothing else.

  • How to calculate elapsed time based on user input

    I'm not sure what to do next in this program. Basically, I'm not sure exactly how to get the time to output accurately, as in what forumla I should be using.
    This is the question:
    What comes 13 hours after 4 o'clock? Create an ElaspedTimeCalculator application that prompts the user for a starting hour, whether it is am or pm, and the number of elapsed hours. The application then displays the time after that many hours have passed. Application output should look similar to:
    Enter the starting hour: 7
    Enter am or pm: pm
    Enter the number of elapsed hours: 10
    The time is: 5:00 amHere's the code I have so far:
    import java.util.Scanner;
    public class ElapsedTimeCalculator
         public static void main(String[] args)
              int starting_hour;
              int starting_minutes; /*This is added in case the user wants to add minutes as well.*/
              String am_or_pm;
              int elapsed_hours;
              int elasped_minutes;
              int time_hours;
              int time_minutes;
              System.out.println("Welcome. This application will give you the time based on your input.");
              System.out.println(" ");
              Scanner input = new Scanner(System.in);
              System.out.print("Enter the starting hour: ");
              starting_hour = input.nextDouble();
              System.out.print("Enter the starting minutes: ");
              starting_minutes = input.nextDouble();
              System.out.print("Enter either 'am' or pm': ");
              am_or_pm = input.nextString();
              System.out.print("Enter the number of elapsed hours: ");
              elapsed_hours = input.nextDouble();
              input.close();
              time_hours =
              time_minutes = 
              if(am_or_pm = "am" || am_or_pm = "a.m." || am_or_pm = "AM" || am_or_pm = "A.M.")
                   System.out.println("The time is " + time_hours + ":" + time_minutes + "am");
              if(am_or_pm = "pm" || am_or_pm = "p.m." || am_or_pm = "PM" || am_or_pm = "P.M.")
                   System.out.println("The time is " + time_hours + ":" + time_minutes + "pm");
    }To calculate time_hours should I just calculate this by adding the elapsed hour to the starting hour? I doubt it will be accurate for all situations.
    Same for the time_minutes For example, if the starting minutes and the elapsed minutes were 50, it would be greater than 60. Also, not sure if it makes sense to separate hours and minutes like this, it's not required to in the question. I initally thought it would be easier to approach like this instead of allowing the user to input a double for the starting hour. ex. 5.7
    I get the feeling that this is extremely simple, but nonetheless, I'm stuck, so any help would be appreciated.

    Well thanks to both of you. I did a little reading up on the modulus operator and coupled it with some logic (although, truthfully, I'm not really using to there actually being an application for the remainder of a division operation, since it's never really used very much in any of my Math courses) and the hours portion works perfectly now:
    import java.util.Scanner;
    public class ElapsedTimeCalculator
         public static void main(String[] args)
              int starting_hour;
              //int starting_minutes; /*This is added in case the user wants to add minutes as well.*/
              String am_or_pm;
              int elapsed_hours;
              //int elasped_minutes;
              System.out.println("Welcome. This application will give you the time based on your input.");
              System.out.println(" ");
              Scanner input = new Scanner(System.in);
              System.out.print("Enter the starting hour: ");
              starting_hour = input.nextInt();
              //System.out.print("Enter the starting minutes: ");
              //starting_minutes = input.nextInt();
              System.out.print("Enter either 'am' or pm': ");
              am_or_pm = input.next();
              System.out.print("Enter the number of elapsed hours: ");
              elapsed_hours = input.nextInt();
              input.close();
              int time_hours = 0;
              //int time_minutes;
              String meridien;
              if(am_or_pm.equals("am"))
                   time_hours = (starting_hour + elapsed_hours) % 24;
                   //time_minutes = (starting_minutes + elapsed_minutes) % 60;
              else if(am_or_pm.equals("am"))
                   time_hours = (starting_hour + elapsed_hours) % 24;
                   //time_minutes = (starting_minutes + elapsed_minutes) % 60;
              else if(am_or_pm.equals("AM"))
                   time_hours = (starting_hour + elapsed_hours) % 24;
                   //time_minutes = (starting_minutes + elapsed_minutes) % 60;
              else if(am_or_pm.equals("A.M."))
                   time_hours = (starting_hour + elapsed_hours) % 24;
                   //time_minutes = (starting_minutes + elapsed_minutes) % 60;
              else if(am_or_pm.equals("pm"))
                   time_hours = (starting_hour + elapsed_hours + 12) % 24;
                   //time_minutes = (starting_minutes + elapsed_minutes) % 60;
              else if(am_or_pm.equals("p.m."))
                   time_hours = (starting_hour + elapsed_hours + 12) % 24;
                   //time_minutes = (starting_minutes + elapsed_minutes) % 60;
              else if(am_or_pm.equals("PM"))
                   time_hours = (starting_hour + elapsed_hours + 12) % 24;
                   //time_minutes = (starting_minutes + elapsed_minutes) % 60;
              else if(am_or_pm.equals("P.M."))
                   time_hours = (starting_hour + elapsed_hours + 12) % 24;
                   //time_minutes = (starting_minutes + elapsed_minutes) % 60;
              if(time_hours < 12)
                   meridien = "A.M.";
                   System.out.println("The time is: " + time_hours + ":00 " + meridien);
              else if(time_hours > 12)
                   meridien = "P.M.";
                   System.out.println("The time is: " + time_hours + ":00 " + meridien);
    }Now the only thing is the minutes. My teacher did say she wants the user to have the option to input minutes also if he/she desires, so I do need it. However, the only problem is that if say the user inputs a "starting minute" of 14 for example, and 66 minutes elapsing, then (14 + 66) int/ 60 = 1r20 but using the modulus operator would only give me 20. So how will I be able to add any extra hours if it is necessary?

Maybe you are looking for

  • User-Defined Fields and Form Settings

    I have a User-Defined Field in the table "OCLG" and I'd like to show it in the "Activities Overview for Business Partner - xxx" window. Is possibile to do that by the "Form Settings" window? Here I don't find U-D Fields. Is there a way to show them?

  • Om infotype modification

    Hi, plz tell me how i can add one field in infotype HRP1003.plz tell me in detail thanks

  • Inbound IDOC User Exit ZXVEDU04 change IDoc Data

    Hi all, We have to develop an user exit for changing the Plant, Shipping Point and Storage location We have identified the exit ZXVEDU04 . Is there some other exit for this ?? But which internal table we are supposed to change this to change the data

  • Getting the location of non-transperant pixels in an image

    Hello everybody, I'm not really new into java, but I am new at working with images... and since I'm making this game i simply have to ^^, anyway here's my problem: I'm trying to test for collosion (if a part of a character/player hits an object (enem

  • SAP Solution for customer crosscheck

    Hi. For security reasons one of our customers wants to crosscheck customers with an external database located in Switzerland.  Does someone have an idea whether or not SAP has a standard solution for this? Basically it entails reading the customer de