Transferring User Input Into an Array

I want the user to input whats inside the matrix so I tell them "Enter Row 1 of Matrix 1: " Say for example they entered the length of the square matrix as 3, I would then want them to enter something like "1 2 3" as Row 1. With my current code I get:
3 3 3
3 3 3
3 3 3
I cant figure out what I should change so that its:
1 2 3
1 2 3
1 2 3
Thanks so much for any help. Heres the code so far:
import java.util.Scanner;
public class MatrixAddPro
  public static void main (String[] args)
     int row1, col1;
     Scanner scan = new Scanner(System.in);
     System.out.println("Enter the length of the square matrix: ");
     col1 = scan.nextInt(); 
     int[][] a = new int[col1][col1];
     System.out.println("Enter Row 1 of Matrix1: ");
     while(scan.hasNext())
     a[1][1] = scan.nextInt();
     //for (int row = 0; row < a.length; row++)
        //for (int col = 0; col < a[row].length; col++)
           //a[col1][col1] = scan.nextInt();
     for (int row = 0; row < a.length; row++)
        for (int col = 0; col < a[row].length; col++)     
           System.out.print(a[1][1] + "\t");
        System.out.println();  
}

import java.util.Scanner;
public class MatrixAddPro
  public static void main (String[] args)
     int input, row, col;
     Scanner scan = new Scanner(System.in);
     System.out.println("Enter the length of the square matrix: ");
     col = scan.nextInt(); 
     row = col;
     int[][] a = new int[row][col];
     for (int x = 0; x < row; x++)
        for (int y = 0; y < col; y++)
           {System.out.println("Enter Row"+(x+1)+" Col"+ (y+1));
           input = scan.nextInt();
           a[x][y] = input;
     for (int x = 0; x < row; x++)
        for (int y = 0; y < col; y++)     
           {System.out.print(a[x][y] + "\t");
           System.out.println();      
}OUTPUT:
Enter the length of the square matrix:
3
Enter Row1 Col1
1
Enter Row1 Col2
2
Enter Row1 Col3
3
Enter Row2 Col1
1
Enter Row2 Col2
2
Enter Row2 Col3
3
Enter Row3 Col1
1
Enter Row3 Col2
2
Enter Row3 Col3
3
1
2
3
1
2
3
1
2
3
Alright so now its not printing in rows...
Thanks for your patience/help guys.

Similar Messages

  • 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 save User input into DB using webdynpro abap

    Hi,
    Im trying to create an application using webdynpro abap.
    I want to know how to save the data input by user, into a database table.
    In my UI, I have a table control which is editable and user inputs data into this. I need to know how i can transfer this data to a DB table.

    hello,
    u can do it by reading ur context node.
    we bind our UI elements to context attributes of appropriate type .
    we read their values using the code wizard or by pressing control+F7, click on radio button read node/attribute
    here for ur specific case , u must have binded ur table control with the context attribute , now u need to simply read this attribute
    eg suppose u have created a context node " cn_table"
      reading context node cn_table
       DATA : lo_nd_cn_table TYPE REF TO if_wd_context_node ,
             lo_el_cn_table TYPE REF TO if_wd_context_element ,
             ls_cn_table    TYPE wd_this->element_cn_table.
    *   navigate from <CONTEXT> to <CN_TABLE> via lead selection
      lo_nd_cn_table = wd_context->get_child_node(
                       name = wd_this->wdctx_cn_table ).
    **    get element via lead selection
      lo_el_cn_table = lo_nd_cn_table->get_lead_selection(  ).
      lo_el_cn_table->get_static_attributes( IMPORTING
                 static_attributes = wa_table ).
    here wa_table is the work area of structure type . u need to create a structure first with the same variables as there are the context attributes in ur node cn_table
    in ur
    now ur wa_tablecontains value
    u can nw use appropriate FM to update , delete and modify the DB table using the value
    u cn directly use SQL statements as well in the method of ur view , but direct SQL statements are nt recommende
    rgds,
    amit

  • 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

  • What is the Problem in the way that I get input into an Array

    Hi Guru's,
    Im learning Java and I have written a simple program to get the input and write into an Array. The program is as follows.
    import java.util.*;
    public class ArraysSort {
         public static void main(String[] args)
              System.out.println("Enter the Number of Entries that you want to Enter");
              Scanner num = new Scanner(System.in);
              int len = num.nextInt();
              int arr[] = null;
              System.out.println(len);
              System.out.println("Enter the Numbers");
              for (int i=0;i<len;i++)
    *               *arr[i] = num.nextInt();*
              //System.out.println("The Numbers in Ascending Order are:");
              //Arrays.sort(arr);
              for (int i=0;i<arr.length;i++)
                   System.out.println(arr);
    Can anyone tell me what is wrong with the Way that I get the input. I have marked the statement in Bold for easy identification.
    Thanks a lot for all your help..

    VijaySwaminathan wrote:
    *               *arr[i] = num.nextInt();*I don't think you can just say
    int arr[] = null;and then expect it to insert? Surely first create an array like this....
    int arr[] = new int[len];

  • Putting input into an array

    I've created a java program with an array of 7 numbers. the first number indicated how many numbers will be entered.
    for ex. 6, 202, 303, 101, 303, 505, 404
    I created an array with the above examples number, and all my methods are working to compute the average, values equal to average, below average and above average.
    However, right now its not quite right because ive entered the numbers into the array manually. What i need to do is take the numbers from the input stream and enter them into the array. How do I do this? Ive been doing so much research and can't figure out how to do it/get it right.
    // shortcut, creates array manualy. need to change this to take the numbers from the standard input stream.
    int[] numbers = { 6, 202, 303, 101, 303, 505, 404};
    // position 0 holds how many numbers there are
    int howMany = 0;
    howMany = numbers[0];
    // average numbers in array
    int numHolder = 0;
    int average = 0;
    int add = 0;
    for (int i = 1; i<numbers.length; i++) {
        add = numbers[i] + add;
        average = add / howMany;
    // number of integers that is less than the average
    int lessThan = 0;
    for (int i=1; i<numbers.length; i++){
        if (numbers[i] <  average) {
            lessThan ++ ;
    // number of integers exactly equal to the average
    int equal = 0;
    for (int i=1; i<numbers.length; i++){
         if (numbers[i] ==  average) {
         equal ++ ;
    // number of integers that greater than the average
    int greaterThan = 0;   
    for (int i=1; i<numbers.length; i++){
        if (numbers[i] <  average) {
            greaterThan ++ ;
    // print the results
    System.out.println("Average Value : " + average + "\n");
    System.out.println("Number of values below the average : " + lessThan);
    System.out.println("Number of values equaling average  : " + equal);
    System.out.println("Number of values above the average : " + greaterThan + "\n");

    BufferedReader buffy = new BufferedReader(new InputStreamReader(System.in));
    String input = buffy.readLine();   
    int num = Integer.parseInt(input);
    array[somenumber] = num;You should have try/catch statements so the program does not let the client enter strings.
    Hope this helped

  • Input into 2d array table

    code is not right :( will repost.
    Edited by: jettaz on May 24, 2008 3:43 PM
    I have initialized a 14x4 array and filled it myself, while allowing the user to further input 4 more rows if he so wishes.
    The array table is 2d for an inventory, sorted by type and brand.
    try
    plainWrapString = JOptionPane.showInputDialog("Please enter Plain Wrap type:");
    brandAString = JOptionPane.showInputDialog("Enter serial for brand A:");
    brandCString = JOptionPane.showInputDialog("Enter serial for brand C:");
    brandXString = JOptionPane.showInputDialog("Enter serial for brand X:");
    for(rowsInteger = 0; rowsInteger < 14; rowsInteger++)
    if(plainWrapString.equalsIgnoreCase(inventoryArray[rowsInteger][columnInteger]))
    throw new IllegalArgumentException("Duplicate found! Please retry.");
    inventoryArray[rowsInteger][columnInteger] = plainWrapString;First of all, my try... catch statement, doesn't catch even when plainWrapString input is a copy of the already entered data in the array table. I had it working okay, though, before I attempt to get the user tp further input more data corresponding to the plainWrapString's row. I'm not sure if this works for inputting the following data according to brands.
    for (columnInteger = 0; columnInteger < 4; columnInteger ++)
    inventoryArray[rowsInteger][columnInteger] = brandAString;
    columnInteger = 0; // resets columnInteger back to zero to continue filling next
                                // column in array?
    for (columnInteger = 0; columnInteger < 4; columnInteger++)
    inventoryArray[rowsInteger][columnInteger] = brandXString;
    columnInteger = 0;
    for (columnInteger = 0; columnInteger < 4; columnInteger++)
    inventoryArray[rowsInteger][columnInteger] = brandCString;
    selectionDropMenu[rowsInteger] = plainWrapString; // something extra to add to a
                                                                               // drop menu
    catch(IllegalArgumentException error)
    JOptionPane.showMessageDialog(null, error.getMessage());
    }Any help is appreciated :)
    Edited by: jettaz on May 24, 2008 3:46 PM
    Edited by: jettaz on May 24, 2008 4:20 PM

    A HashMap would be a better way to ensure that you have unique elements. This approach will allow you to get away from using exception. I have attached two classes. I have assumed that you only want to store one type, but each type can have many brands. The types will be unique but the brands can be duplicates. The brand object counts the number of duplicate entries. An additional benefit of this approach is that you do not need to know the size of your collection before hand.
    The test class contains the main() method.
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Set;
    import java.util.SortedSet;
    import java.util.TreeSet;
    public class TestClass{
         private HashMap<String, Brand> type = new HashMap<String, Brand>();
         public TestClass(){
         public void addTypeAndBrand(String typeName, String brandName){
              Brand b = type.get(typeName);
              if(b==null){
                   type.put(typeName, new Brand(brandName));
              }else{
                   b.addBrand(brandName);
         public void listTypeAndBrand(){
              Set<String> types = type.keySet();
              SortedSet<String> sortedTypes = new TreeSet<String>(types);
              Iterator<String> typeIter = sortedTypes.iterator();
              Brand b = null;
              String typeName = "", brandName = "";
              int frequency=0;
              while(typeIter.hasNext()){
                   typeName = typeIter.next();
                   b = type.get(typeName);
                   Set<String> brands = b.getKeys();
                   SortedSet<String> sortedBrands = new TreeSet<String>(brands);
                   Iterator<String> brandIter = sortedBrands.iterator();
                   while(brandIter.hasNext()){
                        brandName = brandIter.next();
                        frequency = b.getCount(brandName);
                        System.out.println("Type: " + typeName + ",     Brand: " + brandName + ",     Brand Count: " + frequency);
         public static void main(String[] arg){
              TestClass test = new TestClass();
              test.addTypeAndBrand("Japan", "Toyota");
              test.addTypeAndBrand("Japan", "Honda");
              test.addTypeAndBrand("Japan", "Honda");
              test.addTypeAndBrand("USA", "Ford");
              test.addTypeAndBrand("USA", "Chevy");
              test.addTypeAndBrand("USA", "Dodge");
              test.listTypeAndBrand();
    }The Brand class is:
    import java.util.HashMap;
    import java.util.Set;
    public class Brand {
         private HashMap<String, Frequency> brand = new HashMap<String, Frequency>();
         public Brand(String brandName){
              brand.put(brandName, new Frequency());
          * Add brand to HashMap. If brand does not already exist, add brand to HashMap.
          * Otherwise increment count of brand.
          * @param newBrand brand to be added to HashMap
         public void addBrand(String newBrand){
              Frequency freq = brand.get(newBrand);
              if(freq==null){
                   brand.put(newBrand, new Frequency());
              }else{
                   freq.add();
         public Set<String> getKeys(){
              return brand.keySet();
         public int getCount(String key){
              Frequency f = brand.get(key);
              return f.getFrequency();
          * Inner class for frequency counts.
         class Frequency{
              private int total;
              public Frequency(){
                   total = 1;
              public void add(){
                   total++;
              public int getFrequency(){
                   return total;
    }The output I get is:
    Type: Japan, Brand: Honda, Brand Count: 2
    Type: Japan, Brand: Toyota, Brand Count: 1
    Type: USA, Brand: Chevy, Brand Count: 1
    Type: USA, Brand: Dodge, Brand Count: 1
    Type: USA, Brand: Ford, Brand Count: 1

  • [C] piping user input into system() call (or similar)

    Hey guys,
    I'm working on creating a C program I think will be really neat to use with linux and scp but I have run in to a roadblock.
    I need to pass a statement to the system from my C program but with user defined variables, allow me to explain with an example:
    #include <stdio.h>
    int main()
    gets (port);
    gets (cypher);
    system("scp", "-P" port, "-c" cypher);
    return(0);
    Now obviously (and sadly!) this doesn't work. Can anyone help me achieve this goal?
    Regards,
    Mike.
    Last edited by DrMikeDuke (2009-10-12 23:01:18)

    Fork and exec is probably the more common way of doing it, but from your example you probably want something like this (can't guarantee this will work but it should help):
    #include <stdio.h>
    int main()
    char temp[256], port[32], cypher[32];
    gets(port);
    gets(cypher);
    // This line uses formatted printing to insert variables into a string
    sprintf(temp, "scp -P %i -c %s", atoi(port), cypher); // %i = int %s = string/char array
    system(temp);
    return 0;
    the "atoi" part isn't actually necessary at all but is something to take a note of for future usage. It converts a string into an integer.
    Last edited by HashBox (2009-10-13 04:56:41)

  • Dividing User Input Into Separate Line Items

    The user will input the following information:
    (1) Start date
    (2) Number of weeks
    (3) Weekly Benefit
    Example:
    03/14/08 start date
    4 weeks
    $200.00 per week
    We want to break down the key information as shown below.
    Week 1 of 4 3/14/08 $200.00
    Week 2 of 4 3/21/08 $200.00
    Week 3 of 4 3/28/08 $200.00
    Week 4 of 4 4/04/08 $200.00
    Total $800.00
    Each line will be a separate entry to the database. This would allow the user to easily change/delete a week's benefit.
    Your help is greatly appreciated!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    If there is an easier way to do this, please let me know..........
    Thanks Very Very Very VERY VERY MUCH!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    We did indeed, this should fix it:
    with criteria as (select to_date('03/14/08', 'mm/dd/rr')  as start_date,
                             4 as periods,
                             'Week' as period,
                             200 per_period from dual),
    periods as (select 'Week' period, 7 days, 0 months from dual
      union all select 'BiWeek', 14, 0 from dual
      union all select 'Month', 0, 1 from dual
      union all select 'ByMonth', 0, 2 from dual
      union all select 'Quarter', 0, 3 from dual
      union all select 'Year', 0 , 12 from dual
    t1 as (
    select add_months(start_date,months*(level-1))+days*(level-1) start_date,
           per_period,
           c.period||' '||level||' of '||c.periods period
      from criteria c join periods p on c.period = p.period
    connect by level <= periods)
    select case grouping(start_date)
                when 1 then 'Total'
                else to_char(start_date)
           end start_date,
           sum(per_period) per_period,
           period
    from t1
    group by rollup ((start_date, period))
    START_DATE                 PER_PERIOD             PERIOD                                            
    14-MAR-2008 00:00          200                    Week 1 of 4                                       
    21-MAR-2008 00:00          200                    Week 2 of 4                                       
    28-MAR-2008 00:00          200                    Week 3 of 4                                       
    04-APR-2008 00:00          200                    Week 4 of 4                                       
    Total                      800                                                                      
    5 rows selectedOf course I figured that you wanted to use the query to populate another table in which case you would get the summary information from the table populated with this data, since you wanted to be able change and/or delete entries at a later point in time. Adding the summarized data now makes this query less useful as the data source of an insert statement.
    Message was edited by:
    Sentinel

  • Storing user input into a variable

    Hello,
    i dont know why but flash is being a pain!!
    what i am doing should work as i have done pretty much as it
    says from the official actionscript mx 2004 book.
    Basically i am using the following code:
    enter_btn.onRelease = function() {
    gotoAndPlay(2);
    forename = forename_txt.text;
    surname = surname_txt.text;
    gQuestionNum = 1;
    this script is written so that when i press the enter button
    the values entered into the forename_txt and surname_txt fields
    should be stored in their respective variables (forename and
    surname).
    however when i use the following code on the next frame:
    name_txt.text = forename + " " + surname;
    to display the forename variable and the surname variable
    into the name_txt field, it says UNDEFINED!!
    what am i doiong wrong??
    i know this is probably a simple thing to do but its normally
    the simple thing which makes you wanna chuck your computer out the
    window!!
    please help if you can,
    thank you and all replies will be much appreciated.
    thanks again
    lee

    >>i dont know why but flash is being a pain!!
    Because your code is wrong. You send the playhead to frame 2
    before the vars are defined!!! Keep reading

  • Email notification User Input property

      I have query results from service request as part of user input into Service Request and processing them in Orchestrator.
      As a part of email notification, I would like to display the same query results as part of body of email notification.
      Query results are displayed as part of User Input in Service Request
      In email notification I am able to display all fields of service requests except User Input maybe because its inturn a XML value.
      Any suggestion to come across this ?
    Shahid Roofi

    I am assuming that you are sending the email notification as HTML, in that case the "User Input" will be filtered as it starts with < and ends with > (HTML notification will filter the context between <...>)
    You have to use a PS script in Orchestrator to get the query results only from the "User Input" without all the junk info between <...> then return that using Published Data tab so you will be able to use it in the runbook activities such
    as the email activity.
    Do you have a working example of how to do what you describe?  I am trying to accomplish the same thing and having alot of difficulty coming up with a proper solution.  Any help is appreciated!

  • MVC 5 Database Help (calculations and input based on user input)

    Hello all! I am learning MVC 5 database interactions. I would like to fill in certain database columns based on a calculation done on columns the user inputs. I am not having trouble getting user inputs into the database. I am wondering
    about how to take 2 user input database values, make a calculation using them, and put the resulting number in its own column in the database.
    So: after the user inputs price and lot price, I want the application to figure out the margin (price / lot price) and then input margin into the database. Here is what I have, but the calculation doesn't seem to input the result into my database.
    Where am I going wrong? (margin is already a column in the database)
    Thanks in advance!
    publicActionResultCreate([Bind(Include
    = "ID,Name,Price,Location,Color,LotPrice")]
    Automobile automobile)
    if(ModelState.IsValid)
                    db.Automobile.Add(automobile);          
    automobile.Margin = automobile.Price / automobile.LotPrice;
                    db.SaveChanges();        
    returnRedirectToAction("Index");
    returnView(automobile);

    Hi Ruben,
    Please post your question to the MVC forum below for a better assistance on your issue:
    http://forums.asp.net/1146.aspx
    Regards,
    Fouad Roumieh

  • User input from pl/sql

    How could I get user input from a pl/sql block?
    Hope that somebody can help me.
    thanx
    Amelio.

    There is a package DBMS_LOCK that has a SLEEP routine, which suspends the session for a given period of time (in seconds).
    However, you can only pause the procedure and not accept user input into the procedure during the pause.
    syntax: DBMS_LOCK.SLEEP(1) ;
    I need only to run an 'pause' or something like that within a pl/sql block. Do you know if it's possible? Thanks.

  • Validate user input in textfield?

    Am trying validate user input into my JTextfield but its not working right... Am using the classes from sun's hp :
    http://java.sun.com/docs/books/tutorial/uiswing/components/textfield.html
    The classes with changes made:
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.Toolkit;
    import java.text.*;
    public class DecimalField extends JTextField
    private NumberFormat format;
    private NumberFormat percentFormat;
    public DecimalField()
    super(10);
    percentFormat = NumberFormat.getNumberInstance();
    percentFormat.setMinimumFractionDigits(2);
    // ((DecimalFormat)percentFormat).setPositiveSuffix(" ");
    setDocument(new FormattedDocument(percentFormat));
    format = percentFormat;
    public double getValue()
    double retVal = 0.0;
    try
    retVal = format.parse(getText()).doubleValue();
    } catch (ParseException e)
    Toolkit.getDefaultToolkit().beep();
    return retVal;
    public void setValue(double value)
    setText(format.format(value));
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.Toolkit;
    import java.text.*;
    import java.util.Locale;
    public class FormattedDocument extends PlainDocument
    public FormattedDocument(Format f)
    format = f;
    public Format getFormat()
    return format;
    public void insertString(int offs, String str, AttributeSet a)
    throws BadLocationException
    String currentText = getText(0, getLength());
    String beforeOffset = currentText.substring(0, offs);
    String afterOffset = currentText.substring(offs, currentText.length());
    String proposedResult = beforeOffset + str + afterOffset;
    try
    format.parseObject(proposedResult);
    super.insertString(offs, str, a);
    } catch (ParseException e)
    Toolkit.getDefaultToolkit().beep();
    // System.err.println("insertString: could not parse: "
    // + proposedResult);
    public void remove(int offs, int len) throws BadLocationException
    String currentText = getText(0, getLength());
    String beforeOffset = currentText.substring(0, offs);
    String afterOffset = currentText.substring(len + offs,
    currentText.length());
    String proposedResult = beforeOffset + afterOffset;
    try
    if (proposedResult.length() != 0)
    format.parseObject(proposedResult);
    super.remove(offs, len);
    } catch (ParseException e)
    Toolkit.getDefaultToolkit().beep();
    // System.err.println("remove: could not parse: " + proposedResult);
    private Format format;
    what am I doing wrong?

    am sorry
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.Toolkit;
    import java.text.*;
    import java.util.Locale;
    public class FormattedDocument extends PlainDocument
        public FormattedDocument(Format f)
            format = f;
        public Format getFormat()
            return format;
        public void insertString(int offs, String str, AttributeSet a)
        throws BadLocationException
            String currentText = getText(0, getLength());
            String beforeOffset = currentText.substring(0, offs);
            String afterOffset = currentText.substring(offs, currentText.length());
            String proposedResult = beforeOffset + str + afterOffset;
            try
                format.parseObject(proposedResult);
                super.insertString(offs, str, a);
            } catch (ParseException e)
                Toolkit.getDefaultToolkit().beep();
    //            System.err.println("insertString: could not parse: "
    //            + proposedResult);
        public void remove(int offs, int len) throws BadLocationException
            String currentText = getText(0, getLength());
            String beforeOffset = currentText.substring(0, offs);
            String afterOffset = currentText.substring(len + offs,
            currentText.length());
            String proposedResult = beforeOffset + afterOffset;
            try
                if (proposedResult.length() != 0)
                    format.parseObject(proposedResult);
                super.remove(offs, len);
            } catch (ParseException e)
                Toolkit.getDefaultToolkit().beep();
    //            System.err.println("remove: could not parse: " + proposedResult);
        private Format format;
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.Toolkit;
    import java.text.*;
    public class DecimalField extends JTextField
        private NumberFormat format;
        private NumberFormat percentFormat;
        public DecimalField()
            super(10);
            percentFormat = NumberFormat.getNumberInstance();
            percentFormat.setMinimumFractionDigits(2);
    //        ((DecimalFormat)percentFormat).setPositiveSuffix(" ");       
            setDocument(new FormattedDocument(percentFormat));
            format = percentFormat;
        public double getValue()
            double retVal = 0.0;
            try
                retVal = format.parse(getText()).doubleValue();
            } catch (ParseException e)
                Toolkit.getDefaultToolkit().beep();
            return retVal;
        public void setValue(double value)
            setText(format.format(value));
    }Well when I create this overriden TextField ( DecimalField ) its working as it should with the first character. Its only accepting digits and . but after the first character its accepting everything. Its like the validation disappear?

  • How to get input from keyboard scanner into an array

    This is probably a very basic question but I'm very new to java..
    My task is to reverse a string of five digits which have been entered using keyboard scanner.
    E.g. - Entered number - 45896
    Output - 69854
    I used the StringBuffer(inputString).reverse() command for this, but i need a more basic method to do this.
    I thought of defining an array of 5
    int[] array = new int [5];
    and then using,
    Scanner scan = new Scanner(System.in);
    to enter the numbers. But I can't figure out how to get the five input numbers into the array.
    If I can do this I can print the array in reverse order to get my result.
    Any other simple method is also welcome.

    Hey thanks for the quick reply,
    But how can I assign the whole five digit number into the array at once without asking to enter numbers separately?
    E.g. - if entered number is 65789
    Assign digits into positions,
    anArray [0] = 6;
    anArray [1] = 5;
    anArray [2] = 7;
    anArray [3] = 8;
    anArray [4] = 9;
    I'm really sorry but I am very new to the whole subject.

Maybe you are looking for

  • Outgoing mail keeps defaulting to a secondary account rather than the account I sent the message from?

    I have a new MacBook Air. I have two google mail accounts set up in the mail app  - one primary account and one secondary account. For some reason my outgoing messages keep defaulting to the secondary account. Even when I create a new message or repl

  • How to configure iTunes for travel with an iPhone?

    While I keep iTunes and iPhone on my primary iMac, I'm going to be doing some travel and will need to make adjustments for keeping my iPhone backed up on a new MacBook Pro I'll be taking with me. I do not want to add any songs from my current iTunes

  • Exit Code: 24 when installing Production Premium

    I downloaded this today and I'm only tring to install illustartor and photoshop, but I keep getting errors. I've tried restarting, re-downloading, nothing works. Here's a screen shot of the installer when it gives me the error.

  • Sharing between 2 Macbooks

    I have a MacBook Pro and ordered a MacBook Air last Friday. The Air is on the way ... I wonder if I can share some free bulit-in apps (Page, Numbers and Keynote) in the Air to the Pro. How?

  • Radio Mode Settings

    Currently, I have my Time Capsule set to 802.11n only (5GHZ) and I have my Airport Extreme setup as 802.11n(802.11b/g compatible). My question is if I change the Time Capsule to 802.11n(802.11b/g compatible) is that going to make both Radio Modes run