Help with looping and counting

i am in a CS 1 class and need help with this loop
/*Write a program that will allow the user to enter a character
          until the capital letter Z is entered
     The program should count the number of letters entered
          and print the total after the loop is completed*/
here is what i have it doesn't end nor does it count and i don't know hwo to make it count also i suck at do..while loops hehe
char b,Z=0;
          Scanner a = new Scanner(System.in);
     do
               System.out.print("Enter a letter: "+"\n");
               b=a.next().charAt(0);
          while (b !=Z);
i know that its not even close to being right just help me out here
Edited by: purplesmurf on Nov 14, 2008 7:25 PM

The following program will count the number of chacters entered until Z is enetered.
import java.io.*;
class count
     public static void main(String[] args)throws IOException
          char ch;
          int cnt=0;
          DataInputStream br=new DataInputStream(System.in);
          do
          System.out.print("Enter a character:");
          ch=(char)br.read();
          if(ch!='Z')
               cnt++;
          else
               break;
          }while((ch=(char)br.read())!='Z');
          System.out.println("The Number of entered characters are:"+cnt);
}

Similar Messages

  • Help with writing and retrieving data from a table field with type "LCHR"

    Hi Experts,
    I need help with writing and reading data from a database table field which has a type of "LCHR". I have given an example of the original code but don't know what to change it to in order to fix it and still read in the original data that's stored in the LCHR field.
    Basically we have two Function modules, one that saves list data to a database table and one that reads in this data. Both Function modules have an identicle table which has an array of fields from type INT4, CHAR, and type P. The INT4 field is the first one.
    Incidentally this worked in the 4.7 non-unicode system but is now dumping in the new ECC6 Unicode system.
    Thanks in advance,
    C
    SAVING THE LIST DATA TO DB
    DATA: L_WA(800).
    LOOP AT T_TAB into L_WA.
    ZDBTAB-DATALEN = STRLEN( L_WA ).
    MOVE: L_WA to ZDBTAB-RAWDATA.
    ZDBTAB-LINENUM = SY-TABIX.
    INSERT ZDBTAB.
    READING THE DATA FROM DB
    DATA: BEGIN OF T_DATA,
                 SEQNR type ZDBTAB-LINENUM,
                 DATA type ZDBTAB-RAWDATA,
               END OF T_TAB.
    Select the data.
    SELECT linenum rawdata from ZDBTAB into table T_DATA
         WHERE repid = w_repname
         AND rundate = w_rundate
         ORDER BY linenum.
    Populate calling Internal Table.
    LOOP AT T-DATA.
    APPEND T_DATA to T_TAB.
    ENDLOOP.

    Hi Anuj,
    The unicode flag is active.
    When I run our report and then to try and save the list data a dump is happening at the following point
    LOOP AT T_TAB into L_WA.
    As I say, T_TAB consists of different fields and field types whereas L_WA is CHAR 800. The dump mentions UC_OBJECTS_NOT_CONVERTIBLE
    When I try to load a saved list the dump is happening at the following point
    APPEND T_DATA-RAWDATA to T_TAB.
    T_DATA-RAWDATA is type LCHR and T_TAB consists of different fields and field types.
    In both examples the dumps mention UC_OBJECTS_NOT_CONVERTIBLE
    Regards
    C

  • MOVED: [Athlon64] Need Help with X64 and Promise 20378

    This topic has been moved to Operating Systems.
    [Athlon64] Need Help with X64 and Promise 20378

    I'm moving this the the Administration Forum.  It seems more apporpiate there.

  • Help with Mathscipt and for loop

    I have a code in Mathscript/matlab and I need to output the array out. One option is my first code,the other option is using a for loop, but I am only getting the last ouput out. I need to get the whole output out.
    Any help.
    Thanks
    Solved!
    Go to Solution.
    Attachments:
    Help with Mathscript_for loop.vi ‏115 KB
    Help with Mathscript_for loop2.vi ‏84 KB

    Here's how it should look like.
    Message Edited by altenbach on 10-30-2008 05:12 PM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    MathscriptInFOR.png ‏15 KB

  • Help with Loops!! All loops are RED and unclickable after Leopard upgrade.

    I may need to just remove soundtrack pro from my computer and start from scratch again. When I upgraded to Leopard I failed to select preserve user settings when I did an archive and install. So therefore I had to find and drag files to the new library. This is on my Power Mac G5.
    I have a Macbook Pro laptop and I used that as a guide of how I have that set up. On my G5, I have all my loops in the same folders they are in on my laptop. When I open STP, and pull up my loop files, they are all listed in red. When I try to click on them, nothing happens.
    I have them set up as MAC>Library>Audio>Apple Loops>Apple Loops for Soundtrack Pro, Apple Loops for GarageBand, PowerFX Loops
    I am not sure if I am dealing with a bunch of corrupt files and need to start with a new slate or what.
    I also noticed that most if not all the audio loops end in .CAF instead of .AIFF in the folders. However when STP is open, the files ARE listed as .aiff files but they are red and non clickable.
    Any suggestions appreciated!
    Thanks!
    Message was edited by: DVX100Shooter
    Message was edited by: DVX100Shooter
    Message was edited by: DVX100Shooter

    Yea once I rearranged the loops and then opened STP and then Indexed those loops, I got everything back to normal except my Trumpet files. I cannot locate them anywhere. There are only 4 loops but I searched my HD and still can't locate where they are but I got everything else back to working.

  • Help with a Word Counting Program..

    I need some help with a program I am trying to write
    The program is being written in BlueJ.
    Im just starting the program and am completely confused on how I should write this...
    But here is what I have to do..
    I have to use a scanner to scan a Text file and count the # of Words the number of Vowels (including Y when it is) and the # of Palindromes (Word spelled same forward and Back) as well as which Palindromes are being used.
    It would be good to have a class to clean the text and a seperate class for the tasks...
    I do not want to use anything other than "If" statements and while loops (no "for" loops) and only use Printwriter as the output file writer.
    Thnx to anyone in advance

    I have a basic Vowel coding that doeswnt work...
    public class vowel{
    String word = "heyyou";
    String vowels = "aeiouy";
    int[] countv = new int[vowels.length()];
    int countv2;
    int i=0;
    if(i<word.length();) { i++ {
    if (int j=0 && j<vowels.length()) {
    return j++;
    if (word.charAt(i)==vowels.charAt(j)) {
    countV[j]++; countV2++;
    for (int i=0; i<vowels.length(); i++) {
    System.out.println("Vowel "vowels.charAt(i)" = "+vcnt);
    System.out.println("Consonants = "+(word.length()-vtot)); }
    I also have a basic Palindrome code that works as a boolean but I need to make it return what the palindromes are and how many of them are there. I wanna know how I would do this.
    public class Palindrome{
    public static boolean isPalindrome(String word) {
    int left = 0;
    int right = word.length() -1;
    while (left < right) {       
    if (word.charAt(left) != word.charAt(right)) {
    return false;
    left++;
    right--;
    return true;
    I would also like to know how to actually start writing the word counter.

  • Help with loop in code

    I have the following servlet which connects to a database and should brgin back the name of all films that an actor has stared in below is part of the servlet my problem is each time i run the servlet it just prints out "sorry there has been an error" a number of times. Can any body help me get this working?
    public static int MAX_COUNT = 100;
    int curr_item = 0;
    private static CatalogItem addedItem[] = new CatalogItem[MAX_COUNT];
    private static CatalogItem items[] = new CatalogItem[MAX_COUNT];
    CatalogItem item;
    CatalogItem details;
    public static CatalogItem getItem(int recordingid) {
               CatalogItem item;
              for(int i=0; i<items.length; i++) {
                item = items;
              addedItem[i] = items[i];
    if (recordingid==item.getrecordingid()) {
    return(item);
    return(null);
    // Database connection
         int recordingidDB;
         String directorDB;
         String titleDB;
         String categoryDB;
         String imageDB;
         int durationDB;
         String ratingDB;
         String yearDB;
         float priceDB;
         int StockDB;
         Connection conn = null;
         try{
         Class.forName("com.mysql.jdbc.Driver").newInstance();
         } catch(Exception e) {
         System.out.println(e);
         try{
         conn = DriverManager.getConnection
    ("jdbc:myurl");
         // System.out.println("Connection to database successful.");
    catch(SQLException se) {
         System.out.println(se);
         try{
                   String category = request.getParameter("category");
         String selectSQL = "select recording_id, director, title, category, image_name, duration, rating, year_released, price, stock_count "+
         "from video_recordings " +
                        "where recording_id IN "+
                        "(select recording_id "+
                        "from video_actors "+
                        "where name ='"+request.getParameter("category")+"')";
    System.out.println(selectSQL);     
         Statement stmt = conn.createStatement();
         ResultSet rs1 = stmt.executeQuery(selectSQL);
         while(rs1.next() && curr_item < MAX_COUNT){
              recordingidDB = rs1.getInt("recording_id");
              directorDB = rs1.getString("director");
              titleDB = rs1.getString("title");
              categoryDB = rs1.getString("category");
              imageDB = rs1.getString("image_name");
              durationDB = rs1.getInt("duration");
              ratingDB = rs1.getString("rating");
              yearDB = rs1.getString("year_released");
              priceDB = rs1.getFloat("price");
              StockDB = rs1.getInt("stock_count");
         item =
              new CatalogItem
              (recordingidDB, directorDB, titleDB, categoryDB, imageDB, durationDB, ratingDB, yearDB, priceDB, StockDB);
              addedItem[curr_item] = item;
    items[curr_item++] = item;
    int ITEM_COUNT = curr_item;
         String pagetitle = "Catalog Items";
    out.println(
    "<BODY BGCOLOR=\"#a00e0e\">\n" +
              "<center></center>\n" +
    "<H1 ALIGN=\"CENTER\">" + pagetitle + "</H1>\n");
         // loop to go over each item in the array of catalogItem
         for(int i=0; i<addedItem.length; i++) {
         details = items[i];
         if (details == null) {
    out.println("SORRY THERE HAS BEEN AN ERROR ");
         } else {  
              for(int j=0; j<MAX_COUNT; j++) {
    out.println(
    addedItem[j].gettitle() + "\n" +
    addedItem[j].getprice() + "\n" +
    addedItem[j].getstock() + "\n" );
         out.println("</BODY></HTML>");
         stmt.close();
         conn.close();
         } catch(SQLException se) {
         System.out.println(se);

    ok..
    1. To print the size of the resultset there is no direct way from wat i know so far. You need to work around it. This wat i normally do for testing:
    String selectSQL = "select count(video_recordings.recording_id) " +
                                "from video_recordings " +
                        "where recording_id IN "+
                                                 "(select recording_id "+
                                                "from video_actors "+
                                                 "where name ='"+request.getParameter("category")+"')";
    Statement stmt = con.createStatement() ;
    ResultSet rs = stmt.executeQuery(selectSQL) ;
    rs.next() ;
    BigDecimal rowCount = rs.getBigDecimal(1) ;
    System.out.println("Result size = " + rowCount.toString());The rowCount variable now contains the size of your query result.
    2. To print the stacktrace, just add in se.printStackTrace into your catch blocks.
    Additional: Can u also print something inside youe while loop to confirm that your code did enter the while loop and perform the assignment?
    Maybe u can also print the addedItem[curr_item] value after you addedItem[curr_item] = item to confirm that the item was successfully assigned to addedItem[curr_item]..

  • I need Help with loop

    Hello everyone this is my first time posting here, i have always find java easy(up to this point), this is my first class in programming java i am just needing help with the "for loops" i cant seem to get the program generate 10 random math questions. if you guys can please help i will appreciate it, i have been working on it for a couple of hours. I am not finished with it yet but thats the only thing i need help with.
    import javax.swing.JOptionPane;
    public class Lab5
    public static void main(String[] args)
    int num1 = (int) (Math.random() * 100 + 1);
    int num2 = (int) (Math.random() * 100 + 1);
    int sum = num1 + num2;
    int product = num1 * num2;
    int quotient = num1 / num2;
    int difference = num1 - num2;
    for (int i = 0; i > 11; i++);
    int number = (int)(Math.random()*4);
    if (number == 0 )
    String s1 = JOptionPane.showInputDialog(null, num1 + " + " + num2 + "=" );
    if(number == 1)
    String s3 = JOptionPane.showInputDialog(null, num1 + " - " + num2 + "=" );
    if(number == 2)
    String s3 = JOptionPane.showInputDialog(null, num1 + " x " + num2 + "=" );
    if(number == 3)
    String s4 = JOptionPane.showInputDialog(null, num1 + " &divide; " + num2 + "=" );

    for (int i = 0; i > 11; i++);Two problems with this line:
    1) The second part of a For loop is the constraint. You have said that for the loop to be entered, i must be greater than 11. Well since you've also told i to begin at 0, this will never happen. Thus, the loop will never enter. You may have meant less than?
    2) You put a semicolon in the line. Semicolons are used to end statements. The For loop, when used as a block with curly braces, is not a single statement and does not require a semicolon. Here's the two structures of a basic For loop:
    for(int i = 0; i <= 100; i++) {
        //this is a block. you can put multiple statements in here and they are all part of the loop
        int a = 1;
        int b = i;
    //if your loop only needs to use a single statement, no braces are required
    for(int i = 0; i <= 100; i++)
        int a = i;

  • Help with looped equation

    I am really struggling here with this (what seems) fairly simple labview problem.  I have a set of equations that rely on the answer of the previous other formula and so forth.  I can do this easily enough in excel.  I tried to recreate this function in labview and have been really struggling to get it to work.  I have tried using while loops and for loops, which I think is what I need to do here, but I haven't had much success.  Anyways, I attached the spreadsheet with the two formulas, a .png showing the relationship of the formulas in the spreadsheet, and my .VI.  Thanks for your help in advance.
    Solved!
    Go to Solution.
    Attachments:
    Formula.xlsx ‏42 KB
    Formula.png ‏38 KB
    Untitled 1.vi ‏8 KB

    You need both a loop and a shift register.
    Lynn
    Attachments:
    Looped equations.2.vi ‏10 KB

  • Help in loop and at new

    Hallow I have a program that call to smart form. The user have to put course number and employee number and  the program check if the student pass the course send sf and if don’t  send other sf .my problem is when the user put just course number in, other words he wont to print sf of all the student that do some course , I don’t now how to call to smart form in loop because all the time I have a new student and the program have to check if the student pass the course or not and send sf accordingly.
    I heard about at new but I don’t now how to use it or if its fitting my need .
    regards
    IF pernr IS INITIAL .
    *--For-Empty-Pernr--
      SELECT objid_e 
      FROM yhr_score_page
      INTO wa_score_tab-objid_e
      WHERE objid_e IN c_course.
        IF sy-subrc = 0.
          APPEND wa_score_tab TO score_tab.
          CLEAR wa_score_tab.
        ENDIF.
      ENDSELECT.
    ELSE.
      SELECT objid_e 
        FROM yhr_score_page
        INTO wa_score_tab-objid_e
        WHERE objid_e IN c_course
        AND objid_p = pernr.
        IF sy-subrc = 0.
          APPEND wa_score_tab TO score_tab.
          CLEAR wa_score_tab.
        ENDIF.
      ENDSELECT.
    ENDIF.
    This is  the call fo the smart form
    IF sum_n GE passed_nuric. " if student pass course use first function
      CALL FUNCTION 'SSF_FUNCTION_MODULE_NAME'
        EXPORTING
          formname               = 'YHR_SCORE_SMART_FORM_PASS'
      VARIANT                  = ' '
      DIRECT_CALL              = ' '
       IMPORTING
         fm_name                  = /1bcdwb/sf00000005
    EXCEPTIONS
      NO_FORM                  = 1
      NO_FUNCTION_MODULE       = 2
      OTHERS                   = 3
      IF sy-subrc <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
            WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
      CALL FUNCTION '/1BCDWB/SF00000005'
        EXPORTING
      ARCHIVE_INDEX              =
      ARCHIVE_INDEX_TAB          =
      ARCHIVE_PARAMETERS         =
      CONTROL_PARAMETERS         =
      MAIL_APPL_OBJ              =
      MAIL_RECIPIENT             =
      MAIL_SENDER                =
      OUTPUT_OPTIONS             =
      USER_SETTINGS              = 'X'
          score_tab2                 = wa_score_tab2
          sum_all                    = sum_all
          sum_n                      = sum_n
    IMPORTING
      DOCUMENT_OUTPUT_INFO       =
      JOB_OUTPUT_INFO            =
      JOB_OUTPUT_OPTIONS         =
        TABLES
          score_tab                  = score_tab
    EXCEPTIONS
      FORMATTING_ERROR           = 1
      INTERNAL_ERROR             = 2
      SEND_ERROR                 = 3
      USER_CANCELED              = 4
      OTHERS                     = 5
      IF sy-subrc <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
            WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
    *--dont pass--
    ELSE.
      READ TABLE score_tab INDEX 1 INTO wa_score_tab.
      CALL FUNCTION 'SSF_FUNCTION_MODULE_NAME'
        EXPORTING
          formname               = 'YHR_SCORE_SMART_FORM'
      VARIANT                  = ' '
      DIRECT_CALL              = ' '
       IMPORTING
         fm_name                  = /1bcdwb/sf00000002
    EXCEPTIONS
      NO_FORM                  = 1
      NO_FUNCTION_MODULE       = 2
      OTHERS                   = 3
      IF sy-subrc <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
            WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
      CALL FUNCTION '/1BCDWB/SF00000002'
        EXPORTING
      ARCHIVE_INDEX              =
      ARCHIVE_INDEX_TAB          =
      ARCHIVE_PARAMETERS         =
      CONTROL_PARAMETERS         =
      MAIL_APPL_OBJ              =
      MAIL_RECIPIENT             =
      MAIL_SENDER                =
      OUTPUT_OPTIONS             =
      USER_SETTINGS              = 'X'
          score_tab                  = wa_score_tab
    IMPORTING
      DOCUMENT_OUTPUT_INFO       =
      JOB_OUTPUT_INFO            =
      JOB_OUTPUT_OPTIONS         =
    EXCEPTIONS
      FORMATTING_ERROR           = 1
      INTERNAL_ERROR             = 2
      SEND_ERROR                 = 3
      USER_CANCELED              = 4
      OTHERS                     = 5
      IF sy-subrc <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
            WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.

    LOOP AT itab.
    AT NEW stud.
      perform xxxx.
    ENDAT.
    ENDLOOP.
    Refer SF
    Refer this link for Smartforms
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/d937ec90-0201-0010-0ca8-b6cb3b6dd1ef
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/b590fd97-0301-0010-db90-d09ff93cee5a
    Subroutine in smartform
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/library/uuid/ccab6730-0501-0010-ee84-de050a6cc287
    Style and mailing the Smartform output
    https://sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/library/uuid/8fd773b3-0301-0010-eabe-82149bcc292e
    Table,Template,Loop and Command in Smartform
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/library/uuid/3c5d9ae3-0501-0010-0090-bdfb2d458985

  • Need help with JTextArea and Scrolling

    import java.awt.*;
    import java.awt.event.*;
    import java.text.DecimalFormat;
    import javax.swing.*;
    public class MORT_RETRY extends JFrame implements ActionListener
    private JPanel keypad;
    private JPanel buttons;
    private JTextField lcdLoanAmt;
    private JTextField lcdInterestRate;
    private JTextField lcdTerm;
    private JTextField lcdMonthlyPmt;
    private JTextArea displayArea;
    private JButton CalculateBtn;
    private JButton ClrBtn;
    private JButton CloseBtn;
    private JButton Amortize;
    private JScrollPane scroll;
    private DecimalFormat calcPattern = new DecimalFormat("$###,###.00");
    private String[] rateTerm = {"", "7years @ 5.35%", "15years @ 5.5%", "30years @ 5.75%"};
    private JComboBox rateTermList;
    double interest[] = {5.35, 5.5, 5.75};
    int term[] = {7, 15, 30};
    double balance, interestAmt, monthlyInterest, monthlyPayment, monPmtInt, monPmtPrin;
    int termInMonths, month, termLoop, monthLoop;
    public MORT_RETRY()
    Container pane = getContentPane();
    lcdLoanAmt = new JTextField();
    lcdMonthlyPmt = new JTextField();
    displayArea = new JTextArea();//DEFINE COMBOBOX AND SCROLL
    rateTermList = new JComboBox(rateTerm);
    scroll = new JScrollPane(displayArea);
    scroll.setSize(600,170);
    scroll.setLocation(150,270);//DEFINE BUTTONS
    CalculateBtn = new JButton("Calculate");
    ClrBtn = new JButton("Clear Fields");
    CloseBtn = new JButton("Close");
    Amortize = new JButton("Amortize");//DEFINE PANEL(S)
    keypad = new JPanel();
    buttons = new JPanel();//DEFINE KEYPAD PANEL LAYOUT
    keypad.setLayout(new GridLayout( 4, 2, 5, 5));//SET CONTROLS ON KEYPAD PANEL
    keypad.add(new JLabel("Loan Amount$ : "));
    keypad.add(lcdLoanAmt);
    keypad.add(new JLabel("Term of loan and Interest Rate: "));
    keypad.add(rateTermList);
    keypad.add(new JLabel("Monthly Payment : "));
    keypad.add(lcdMonthlyPmt);
    lcdMonthlyPmt.setEditable(false);
    keypad.add(new JLabel("Amortize Table:"));
    keypad.add(displayArea);
    displayArea.setEditable(false);//DEFINE BUTTONS PANEL LAYOUT
    buttons.setLayout(new GridLayout( 1, 3, 5, 5));//SET CONTROLS ON BUTTONS PANEL
    buttons.add(CalculateBtn);
    buttons.add(Amortize);
    buttons.add(ClrBtn);
    buttons.add(CloseBtn);//ADD ACTION LISTENER
    CalculateBtn.addActionListener(this);
    ClrBtn.addActionListener(this);
    CloseBtn.addActionListener(this);
    Amortize.addActionListener(this);
    rateTermList.addActionListener(this);//ADD PANELS
    pane.add(keypad, BorderLayout.NORTH);
    pane.add(buttons, BorderLayout.SOUTH);
    pane.add(scroll, BorderLayout.CENTER);
    addWindowListener( new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    public void actionPerformed(ActionEvent e)
    String arg = lcdLoanAmt.getText();
    int combined = Integer.parseInt(arg);
    if (e.getSource() == CalculateBtn)
    try
    JOptionPane.showMessageDialog(null, "Got try here", "Error", JOptionPane.ERROR_MESSAGE);
    catch(NumberFormatException ev)
    JOptionPane.showMessageDialog(null, "Got here", "Error", JOptionPane.ERROR_MESSAGE);
    if ((e.getSource() == CalculateBtn) && (arg != null))
    try{
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 1))
    monthlyInterest = interest[0] / (12 * 100);
    termInMonths = term[0] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 2))
    monthlyInterest = interest[1] / (12 * 100);
    termInMonths = term[1] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 3))
    monthlyInterest = interest[2] / (12 * 100);
    termInMonths = term[2] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    catch(NumberFormatException ev)
    JOptionPane.showMessageDialog(null, "Invalid Entry!\nPlease Try Again", "Error", JOptionPane.ERROR_MESSAGE);
    }                    //IF STATEMENTS FOR AMORTIZATION
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 1))
    loopy(7, 5.35);
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 2))
    loopy(15, 5.5);
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 3))
    loopy(30, 5.75);
    if (e.getSource() == ClrBtn)
    rateTermList.setSelectedIndex(0);
    lcdLoanAmt.setText(null);
    lcdMonthlyPmt.setText(null);
    displayArea.setText(null);
    if (e.getSource() == CloseBtn)
    System.exit(0);
    private void loopy(int lTerm,double lInterest)
    double total, monthly, monthlyrate, monthint, monthprin, balance, lastint, paid;
    int amount, months, termloop, monthloop;
    String lcd2 = lcdLoanAmt.getText();
    amount = Integer.parseInt(lcd2);
    termloop = 1;
    paid = 0.00;
    monthlyrate = lInterest / (12 * 100);
    months = lTerm * 12;
    monthly = amount *(monthlyrate/(1-Math.pow(1+monthlyrate,-months)));
    total = months * monthly;
    balance = amount;
    while (termloop <= lTerm)
    displayArea.setCaretPosition(0);
    displayArea.append("\n");
    displayArea.append("Year " + termloop + " of " + lTerm + ": payments\n");
    displayArea.append("\n");
    displayArea.append("Month\tMonthly\tPrinciple\tInterest\tBalance\n");
    monthloop = 1;
    while (monthloop <= 12)
    monthint = balance * monthlyrate;
    monthprin = monthly - monthint;
    balance -= monthprin;
    paid += monthly;
    displayArea.setCaretPosition(0);
    displayArea.append(monthloop + "\t" + calcPattern.format(monthly) + "\t" + calcPattern.format(monthprin) + "\t");
    displayArea.append(calcPattern.format(monthint) + "\t" + calcPattern.format(balance) + "\n");
    monthloop ++;
    termloop ++;
    public static void main(String args[])
    MORT_RETRY f = new MORT_RETRY();
    f.setTitle("MORTGAGE PAYMENT CALCULATOR");
    f.setBounds(600, 600, 500, 500);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
    }need help with displaying the textarea correctly and the scroll bar please.
    Message was edited by:
    new2this2020

    What's the problem you're having ???
    PS.

  • Help with encapsulation and a specific case of design

    Hello all. I have been playing with Java (my first real language and first OOP language) for a couple months now. Right now I am trying to write my first real application, but I want to design it right and I am smashing my head against the wall with my data structure, specifically with encapsulation.
    I go into detail about my app below, but it gets long so for those who don't want to read that far, let me just put these two questions up front:
    1) How do principles of encapsulation change when members are complex objects rather than primitives? If the member objects themselves have only primitive members and show good encapsulation, does it make sense to pass a reference to them? Or does good encapsulation demand that I deep-clone all the way to the bottom of my data structure and pass only cloned objects through my top level accessors? Does the analysis change when the structure gets three or four levels deep? Don't DOM structures built of walkable nodes violate basic principles of encapsulation?
    2) "Encapsulation" is sometimes used to mean no public members, othertimes to mean no public members AND no setter methods. The reasons for the first are obvious, but why go to the extreme of the latter? More importantly HOW do you go to the extreme of the latter? Would an "updatePrices" method that updates encapsulated member prices based on calculations, taking a single argument of say the time of year be considered a "setter" method that violates the stricter vision of encapsulation?
    Even help with just those two questions would be great. For the masochistic, on to my app... The present code is at
    http://www.immortalcoil.org/drake/Code.zip
    The most basic form of the application is statistics driven flash card software for Japanese Kanji (Chinese characters). For those who do not know, these are ideographic characters that represent concepts rather than sounds. There are a few thousand. In abstract terms, my data structure needs to represent the following.
    -  There are a bunch of kanji.
       Each kanji is defined by:
       -  a single character (the kanji itself); and
       -  multiple readings which fall into two categories of "on" and "kun".
          Each reading is defined by:
          -  A string of hiragana or katakana (Japanese phoenetic characters); and
          -  Statistics that I keep to represent knowledge of that reading/kanji pair.Ideally the structure should be extensible. Later I might want to add statistics associated with the character itself rather than individual readings, for example. Right now I am thinking of building a data structure like so:
    -  A Vector that holds:
       -  custom KanjiEntry objects that each hold
          -  a kanji in a primitive char value; and
          -  two (on, kun) arrays or Vectors of custom Reading objects that hold
             -  the reading in a String; and
             -  statistics of some sort, probably in primitive valuesFirst of all, is this approach sensible in the rough outlines?
    Now, I need to be able to do the obvious things... save to and load from file, generate tables and views, and edit values. The quesiton of editting values raises the questions I identified above as (1) and (2). Say I want to pull up a reading, quiz the user on it, and update its statistics based on whether the user got it right or wrong. I could do all this through the KanjiEntry object with a setter method that takes a zillion arguments like:
    theKanjiEntry.setStatistic(
    "on",   // which set of readings
    2,      // which element in that array or Vector
    "score", // which statistic
    98);      // the valueOr I could pass a clone of the Reading object out, work with that, then tell the KanjiEntry to replace the original with my modified clone.
    My instincts balk at the first approach, and a little at the second. Doesn't it make more sense to work with a reference to the Reading object? Or is that bad encapsulation?
    A second point. When running flash cards, I do not care about the subtlties of the structure, like whether a reading is an on or a kun (although this is important when browsing a table representing the entire structure). All I really care about is kanij/reading pairings. And I should be able to quickly poll the Reading objects to see which ones need quizzing the most, based on their statistics. I was thinking of making a nice neat Hashtable with the keys being the kanji characters in Strings (not the KanjiEntry objects) and the values being the Reading objects. The result would be two indeces to the Reading objects... the basic structure and my ad hoc hashtable for runninq quizzes. Then I would just make sure that they stay in sync in terms of the higher level structure (like if a whole new KanjiEntry got added). Is this bad form, or even downright dangerous?
    Apart from good form, the other consideration bouncing around in my head is that if I get all crazy with deep cloning and filling the bottom level guys with instance methods then this puppy is going to get bloated or lag when there are several thousand kanji in memory at once.
    Any help would be appreciated.
    Drake

    Usually by better design. Move methods that use the
    getters inside the class that actually has the data....
    As a basic rule of thumb:
    The one who has the data is the one using it. If
    another class needs that data, wonder what for and
    consider moving that operation away from that class.
    Or move from pull to push: instead of A getting
    something from B, have B give it to A as a method
    call argument.Thanks for the response. I think I see what you are saying.. in my case it is something like this.
    Solution 1 (disfavored):
    public class kanjiDrill{ // a chunk of Swing GUI or something
         public void runDrill(Vector kanjiEntries){
              KanjiEntry currentKanjiEntry = kanjiEntries.elementAt(0); // except really I will pick one randomly
              char theKanji = currentKanjiEntry.getKanji();
              String theReading = currentKanjiEntry.getReading();
              // build and show a flashcard based on theKanji and theReading
              // use a setter to change currentKanji's data based on whether the user answers correctly;
    }Solution 2 (favored):
    public class kanjiDrill{ // a chunk of Swing GUI or something
         public void runDrill(Vector kanjiEntries){
              KanjiEntry currentKanjiEntry = kanjiEntries.elementAt(0); // except really I will pick one randomly
              currentKanji.buildAndShowFlashcard(); // method includes updating stats
    }I can definitely see the advantages to this, but two potential reasons to think hard about it occur to me right away. First, if this process is carried out to a sufficient extreme the objects that hold my data end up sucking in all the functionality of my program and my objects stop resembling natural concepts.
    In your shopping example, say you want to generate price tags for the items. The price tags can be generated with ONLY the raw price, because we do not want the VAT on them. They are simple GIF graphics that have the price printed on a an irregular polygon. Should all that graphics generating code really go into the item objects, or should we just get the price out of the object with a simple getter method and then make the tags?
    My second concern is that the more instance methods I put into my bottom level data objects the bigger they get, and I intend to have thousands of these things in memory. Is there a balance to strike at some point?
    It's not really a setter. Outsiders are not setting
    the items price - it's rather updating its own price
    given an argument. This is exactly how it should be,
    see my above point. A breach of encapsulation would
    be: another object gets the item price, re-calculates
    it using a date it knows, and sets the price again.
    You can see yourself that pushing the date into the
    item's method is much beter than breaching
    encapsulation and getting and setting the price.So the point is not "don't allow access to the members" (which after all you are still doing, albeit less directly) so much as "make sure that any functionality implicated in working with the members is handled within the object," right? Take your shopping example. Say we live in a country where there is no VAT and the app will never be used internationally. Then we would resort to a simple setter/getter scheme, right? Or is the answer that if the object really is pure data are almost so, then it should be turned into a standard java.util collection instead of a custom class?
    Thanks for the help.
    Drake

  • Can anyone help with iPlayer and Sky Mobile?

    Ok, I'm so close to giving up with this useless phone. There are 3 apps on my N97 which give me a constant headache.
    BBC iPlayer
    Sky Mobile*
    YouTube
    *I should point out that I only use Sky Mobile to set recordings on my Sky+. I do not use it for, nor have any desire to use it for actually watching Mobile TV.
    All of these apps work absolutely fine over my home WiFi network. It's when I try to use them over 3G (my Vodafone Live! connection) that I start running in to trouble.
    All 3 give me connection problems, errors, and simply refuse to load half the time when on 3G. I got so annoyed I just did a hard reset the other week, and magically all three started working again. However, now 2 of them are failing me again. YouTube (touch wood) is working fine at the moment, but iPlayer and Sky Mobile just aren't.
    iPlayer sometimes works. But sometimes I get script errors (unable to load content), and sometimes it says something about checking my connection settings. I wouldn't mind but it's not actually possible to access any options for the iPlayer. Even in application settings there are no options you're able to set.
    Sky Mobile simply flat out refuses to work ever on 3G. But it did after I did a hard reset for a couple of weeks, now it just stopped working! It wont even load. It just gives the error message 'Unable to connect to network - please check connection settings" or something along those lines.
    I've tried so many different things. Tried setting my internet connections to 'always ask', tried setting it to default to Vodafone Live! all the time, tried setting my video streaming settings to WAP, all sorts. Every combination I can think of.
    I just can't wait to get rid of this phone. I've put so many people off buying one. They see it and think it's all swish and cool, and I just say 'Don't. You'll regret it'. I can't wait for my contract to be up so I can upgrade to an iPhone now Vodafone have got them.
    Can anyone help with these problems? Thanks in advance, but I don't hold out much hope...

    About iPlayer.
    Have a chat with Vodaphone. Streaming iPlayer over 3G IS allowed on Vodaphone contract, unlike my O2 contract. As long as your contract allows it, and you have the correct AP address, it should be fine. Vodaphone should be able to give you the setting.
    Mine only works over Wlan.
    FWIW, "... streaming over 3G is not currently available on iPhone handsets on any mobile network".
    p.s. Just to be clear. You say  "Tried setting my internet connections to 'always ask', tried setting it to default to Vodafone Live!".
    iPlayer uses the Nokia browser "Web". So that's where you should make the setting "Ask when needed". It should then offer you the choice of whatever you've set in Destinations> Internet> then select whatever you've chosen as your GPRS connection.(as advised, or sent to you by Vodaphone).

  • Help with exporting and image size or boundaries?

    I am trying to slide the cat into the scene a little at a time foir an animation project I am working on. However, when I export the image the back ground of the image expands with a checkered back ground( showing here in white) and shows the whole cat.
    How do I just show a little of the cat on the image at a time when exporting. I am trying to give the impression that the cat is walking into the room. I do not want to have to cut the cat up.
    I would be thankful for any suggestions.

    Provide the name of the program you are using so a Moderator may move this message to the correct program forum
    This Cloud forum is not about help with program problems... a program would be Photoshop or Lighroom or Muse or ???

  • Help with Facebook and Social Media wigets (Was: How do I fix the three probs that...)

    I am having problems with the facebook or social media widgets. I would like the link to send viewers to my facebook business page, but when testing it shows my pic and a 'switch' sign (see screen shot) and when I open the site the message is as the other screenshot, great, but I don't know where to find which 'asset' is the problem and why. Also why bother having child pages if the menu doesn't reflect that? I see that drop down menus are an issue, also with some other forum members.
    Thanks for any help offered!, I think I have solved the first problem now but still would appreciate any help with the other 2!
    For some reason the facebook widget now loads the correct page, and I give up about the drop down menu, hopefully this will be addressed in the next update of Muse??

    Hello,
    For the "asset" issue, try locating the asset in the assets panel. It should have an icon like this: http://jingsite.businesscatalyst.com/jing/2013-12-16_0917.png
    For the child pages in the menus issue, go to the menu options (by clicking the small blue arrow in the right top corner of the menu), and then change the menu type to "All Pages" instead of "Top Level Pages".
    Hope this helps.
    Cheers
    Parikshit

Maybe you are looking for

  • I replaced my hard drive and the new one seems "loose".

    I recently put a new HDD in my 15" Macbook Pro as the old one failed. The new one is this one: https://www.pccasegear.com/index.php?main_page=product_info&products_id=26175 ; Western Digital 500GB 2.5" SATA. I made sure it was 9.5mm which is what was

  • Why there are some metric without "Last Upload" in "All Metric" page?

    I am developing a MYSQL Plugin. after I deployed it to agent, and add target to it. I found there is something strange for some metric collecting/uploading. And I test it on both OMS 10.2.0.4 and OMS 10.2.0.5, they have the same issue. In page “All M

  • Trouble importing ORF files from E-PL5 into LR5.3

    Hello, A small percentage of the RAW files from my Olympus E-PL5 look "blurry" or "out of focus" when viewed using LR5.3 (Windows 8.1).  However, most of the RAW files from this camera look fine when viewed in LR (even pictures from the same shooting

  • HT201272 How to download a song that says "Downloaded"

    When I go to my purchases and try to download my past purchase, the button says "Downloaded". However, I cannot play the song because I accidentally deleted some folder in the process of moving my music folder to a different location.  Is there a way

  • How can I clear the Safari cache without removing cookies?

    Safari preferences seem to only allow you to delete all website data. Is there a way of clearing the cache but leaving cookies and browsing history? I have Safari version 6.0.5 and OSX 10.8.4. Thanks.