Need help figuring out what's wrong with my code!

I am having a few problems with my code and can't see what I've done wrong. Here are my issues:
#1. My program is not displaying the answers to my calculations in the table.
#2. The program is supposed to pause after 24 lines and ask the user to hit enter to continue.
2a. First, it works correctly for the first 24 lines, but then jumps to every 48 lines.
2b. The line count is supposed to go 24, 48, etc...but the code is going from 24 to 74 to 124 ... that is NOT right!
import java.text.DecimalFormat; //needed to format decimals
import java.io.*;
class Mortgage2
//Define variables
double MonthlyPayment = 0; //monthly payment
double Principal = 200000; //principal of loan
double YearlyInterestRate = 5.75; //yearly interest rate
double MonthlyInterestRate = (5.75/1200); //monthly interest rate
double MonthlyPrincipal = 0; //monthly principal
double MonthlyInterest = 0; //monthly interest
double Balance = 0; //balance of loan
int TermInYears = 30; //term of loan in yearly terms
int linecount = 0; //line count for list of results
// Buffered input Reader
BufferedReader myInput = new BufferedReader (new
InputStreamReader(System.in));
//Calculation Methods
void calculateMonthlyPayment() //Calculates monthly mortgage
MonthlyPayment = Principal * (MonthlyInterestRate * (Math.pow(1 + MonthlyInterestRate, 12 * TermInYears))) /
(Math.pow(1 + MonthlyInterestRate, 12 * TermInYears) - 1);
void calculateMonthlyInterestRate() //Calculates monthly interest
MonthlyInterest = Balance * MonthlyInterestRate;
void calculateMonthlyPrincipal() //Calculates monthly principal
MonthlyPrincipal = MonthlyPayment - MonthlyInterest;
void calculateBalance() //Calculates balance
Balance = Principal + MonthlyInterest - MonthlyPayment;
void Amortization() //Calculates Amortization
DecimalFormat df = new DecimalFormat("$,###.00"); //Format decimals
int NumberOfPayments = TermInYears * 12;
for (int i = 1; i <= NumberOfPayments; i++)
// If statements asking user to enter to continue
if(linecount == 24)
System.out.println("Press Enter to Continue.");
linecount = 0;
try
System.in.read();
catch(IOException e) {
e.printStackTrace();
else
linecount++;
System.out.println(i + "\t\t" + df.format(MonthlyPrincipal) + "\t" + df.format(MonthlyInterest) + "\t" + df.format(Balance));
//Method to display output
public void display ()
DecimalFormat df = new DecimalFormat(",###.00"); //Format decimals
System.out.println("\n\nMORTGAGE PAYMENT CALCULATOR"); //title of the program
System.out.println("=================================="); //separator
System.out.println("\tPrincipal Amount: $" + df.format(Principal)); //principal amount of the mortgage
System.out.println("\tTerm:\t" + TermInYears + " years"); //number of years of the loan
System.out.println("\tInterest Rate:\t" + YearlyInterestRate + "%"); //interest rate as a percentage
System.out.println("\tMonthly Payment: $" + df.format(MonthlyPayment)); //calculated monthly payment
System.out.println("\n\nAMORTIZATION TABLE"); //title of amortization table
System.out.println("======================================================"); //separator
System.out.println("\nPayment\tPrincipal\tInterest\t Balance");
System.out.println(" Month\t Paid\t\t Paid\t\tRemaining");
System.out.println("--------\t---------\t--------\t-------");
public static void main (String rgs[]) //Start main function
Mortgage2 Mortgage = new Mortgage2();
Mortgage.calculateMonthlyPayment();
Mortgage.display();
Mortgage.Amortization();
ANY help would be greatly appreciated!
Edited by: Jeaneene on May 25, 2008 11:54 AM

From [http://developers.sun.com/resources/forumsFAQ.html]:
Post once and in the right area: Multiple postings are allowed, but they make the category lists longer and create more email traffic for developers who have placed watches on multiple categories. Because of this, duplicate posts are considered a waste of time and an annoyance to many community members, that is, the people who might help you.

Similar Messages

  • I need help figuring out what is wrong with my Macbook Pro

    I have a mid 2012 Macbook Pro with OS X Mavericks on it and for the past few weeks it has running VERY SLOW! I have no idea what is wrong with it, i have read other discussion forums trying to figure it out on my own. So far i have had no luck in fixing the slowness. When i open applications the icon will bounce in dock forever before opening and then my computer will freeze with the little rainbow wheel circling and circling for a few minutes... and if i try to browse websites it take forever for them to load or youtube will just stop working for me. Everything i do, no matter what i click, the rainbow wheel will pop up! The only thing i can think of messing it up was a friend of mine plugging in a flash drive a few weeks ago to take some videos and imovie to put on his Macbook Pro, he has said his laptop has been running fine though... so idk if that was the problem. Anyways, could someone please help me try something? Thank you!!

    OS X Mavericks: If your Mac runs slowly?
    http://support.apple.com/kb/PH13895
    Startup in Safe Mode
    http://support.apple.com/kb/PH14204
    Repair Disk
    Steps 1 through 7
    http://support.apple.com/kb/PH5836
    Reset SMC.     http://support.apple.com/kb/HT3964
    Choose the method for:
    "Resetting SMC on portables with a battery you should not remove on your own".
    Increase disk space.
    http://support.apple.com/kb/PH13806

  • I can't figure out what's wrong with this code

    First i want this program to allow me to enter a number with the EasyReader class and depending on the number entered it will show that specific line of this peom:
    One two buckle your shoe
    Three four shut the door
    Five six pick up sticks
    Seven eight lay them straight
    Nine ten this is the end.
    The error message i got was an illegal start of expression. I can't figure out why it is giving me this error because i have if (n = 1) || (n = 2) statements. My code is:
    public class PoemSeventeen
    public static void main(String[] args)
    EasyReader console = new EasyReader();
    System.out.println("Enter a number for the poem (0 to quit): ");
    int n = console.readInt();
    if (n = 1) || (n = 2)
    System.out.println("One, two, buckle your shoe");
    else if (n = 3) || (n = 4)
    System.out.println("Three, four, shut the door");
    else if (n = 5) || (n = 6)
    System.out.println("Five, six, pick up sticks");
    else if (n = 7) || (n = 8)
    System.out.println("Seven, eight, lay them straight");
    else if (n = 9) || (n = 10)
    System.out.println("Nine, ten, this is the end");
    else if (n = 0)
    System.out.println("You may exit now");
    else
    System.out.println("Put in a number between 0 and 10");
    I messed around with a few other thing because i had some weird errors before but now i have narrowed it down to just this 1 error.
    The EasyReader class code:
    // package com.skylit.io;
    import java.io.*;
    * @author Gary Litvin
    * @version 1.2, 5/30/02
    * Written as part of
    * <i>Java Methods: An Introduction to Object-Oriented Programming</i>
    * (Skylight Publishing 2001, ISBN 0-9654853-7-4)
    * and
    * <i>Java Methods AB: Data Structures</i>
    * (Skylight Publishing 2003, ISBN 0-9654853-1-5)
    * EasyReader provides simple methods for reading the console and
    * for opening and reading text files. All exceptions are handled
    * inside the class and are hidden from the user.
    * <xmp>
    * Example:
    * =======
    * EasyReader console = new EasyReader();
    * System.out.print("Enter input file name: ");
    * String fileName = console.readLine();
    * EasyReader inFile = new EasyReader(fileName);
    * if (inFile.bad())
    * System.err.println("Can't open " + fileName);
    * System.exit(1);
    * String firstLine = inFile.readLine();
    * if (!inFile.eof()) // or: if (firstLine != null)
    * System.out.println("The first line is : " + firstLine);
    * System.out.print("Enter the maximum number of integers to read: ");
    * int maxCount = console.readInt();
    * int k, count = 0;
    * while (count < maxCount && !inFile.eof())
    * k = inFile.readInt();
    * if (!inFile.eof())
    * // process or store this number
    * count++;
    * inFile.close(); // optional
    * System.out.println(count + " numbers read");
    * </xmp>
    public class EasyReader
    protected String myFileName;
    protected BufferedReader myInFile;
    protected int myErrorFlags = 0;
    protected static final int OPENERROR = 0x0001;
    protected static final int CLOSEERROR = 0x0002;
    protected static final int READERROR = 0x0004;
    protected static final int EOF = 0x0100;
    * Constructor. Prepares console (System.in) for reading
    public EasyReader()
    myFileName = null;
    myErrorFlags = 0;
    myInFile = new BufferedReader(
    new InputStreamReader(System.in), 128);
    * Constructor. opens a file for reading
    * @param fileName the name or pathname of the file
    public EasyReader(String fileName)
    myFileName = fileName;
    myErrorFlags = 0;
    try
    myInFile = new BufferedReader(new FileReader(fileName), 1024);
    catch (FileNotFoundException e)
    myErrorFlags |= OPENERROR;
    myFileName = null;
    * Closes the file
    public void close()
    if (myFileName == null)
    return;
    try
    myInFile.close();
    catch (IOException e)
    System.err.println("Error closing " + myFileName + "\n");
    myErrorFlags |= CLOSEERROR;
    * Checks the status of the file
    * @return true if en error occurred opening or reading the file,
    * false otherwise
    public boolean bad()
    return myErrorFlags != 0;
    * Checks the EOF status of the file
    * @return true if EOF was encountered in the previous read
    * operation, false otherwise
    public boolean eof()
    return (myErrorFlags & EOF) != 0;
    private boolean ready() throws IOException
    return myFileName == null || myInFile.ready();
    * Reads the next character from a file (any character including
    * a space or a newline character).
    * @return character read or <code>null</code> character
    * (Unicode 0) if trying to read beyond the EOF
    public char readChar()
    char ch = '\u0000';
    try
    if (ready())
    ch = (char)myInFile.read();
    catch (IOException e)
    if (myFileName != null)
    System.err.println("Error reading " + myFileName + "\n");
    myErrorFlags |= READERROR;
    if (ch == '\u0000')
    myErrorFlags |= EOF;
    return ch;
    * Reads from the current position in the file up to and including
    * the next newline character. The newline character is thrown away
    * @return the read string (excluding the newline character) or
    * null if trying to read beyond the EOF
    public String readLine()
    String s = null;
    try
    s = myInFile.readLine();
    catch (IOException e)
    if (myFileName != null)
    System.err.println("Error reading " + myFileName + "\n");
    myErrorFlags |= READERROR;
    if (s == null)
    myErrorFlags |= EOF;
    return s;
    * Skips whitespace and reads the next word (a string of consecutive
    * non-whitespace characters (up to but excluding the next space,
    * newline, etc.)
    * @return the read string or null if trying to read beyond the EOF
    public String readWord()
    StringBuffer buffer = new StringBuffer(128);
    char ch = ' ';
    int count = 0;
    String s = null;
    try
    while (ready() && Character.isWhitespace(ch))
    ch = (char)myInFile.read();
    while (ready() && !Character.isWhitespace(ch))
    count++;
    buffer.append(ch);
    myInFile.mark(1);
    ch = (char)myInFile.read();
    if (count > 0)
    myInFile.reset();
    s = buffer.toString();
    else
    myErrorFlags |= EOF;
    catch (IOException e)
    if (myFileName != null)
    System.err.println("Error reading " + myFileName + "\n");
    myErrorFlags |= READERROR;
    return s;
    * Reads the next integer (without validating its format)
    * @return the integer read or 0 if trying to read beyond the EOF
    public int readInt()
    String s = readWord();
    if (s != null)
    return Integer.parseInt(s);
    else
    return 0;
    * Reads the next double (without validating its format)
    * @return the number read or 0 if trying to read beyond the EOF
    public double readDouble()
    String s = readWord();
    if (s != null)
    return Double.parseDouble(s);
    // in Java 1, use: return Double.valueOf(s).doubleValue();
    else
    return 0.0;
    Can anybody please tell me what's wrong with this code? Thanks

    String[] message = {
        "One, two, buckle your shoe",
        "One, two, buckle your shoe",
        "Three, four, shut the door",
        "Three, four, shut the door",
        "Five, six, pick up sticks",
        "Five, six, pick up sticks",
        "Seven, eight, lay them straight",
        "Seven, eight, lay them straight",
        "Nine, ten, this is the end",
        "Nine, ten, this is the end"
    if(n>0)
        System.out.println(message[n]);
    else
        System.exit(0);

  • Calling all java gurus - i cant figure out what is wrong with my code

    please can someone see why a null pointer exception is being thrown and how do i fix it?
    my current code which throws the null pointer is as below - the key issues that i need some java expert to tell me about is
    1. is the usage of resultSet ok in the way i'm doing it , i'm not able to look at the code in debug mode as don't have an IDE and don't know how to do a log4j setup. - i tried doing an out.println("Got........"); but servlet keeps on forwarding the request object to results.jsp even when i comment out the code. and recomplie and restart tomcat 4.1.
    2. is the way i'm declaring the List object and the adding stuff to bean and then stuffing bean into list ok?
    3. why is the List object null? although i know the query works fine - and that using the below original code where only one row of data was being retrieved and set into bean worked fine.
    current code with problem in the List object:
    package com.bt.ros;
    import java.util.*;
    import java.io.*;
    import java.net.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    import javax.sql.*;
    import javax.naming.InitialContext;
    import javax.naming.Context;
    import javax.naming.NamingException;
    * This class is a servlet that searches for a Finder Aid.
    * @author
    public class FinderAidsSearchS extends HttpServlet {
       * This is the static initializer,
       * executed the first time this class is referred to.
       * It makes sure the JDBC pool driver is loaded.
       * This method examines an HTTP request and searches for the
       * specified Finder Aid record in the database. It then redirects
       * the response to the <tt>Results.jsp</tt> JSP page.
      public void service(HttpServletRequest req, HttpServletResponse res)
           throws IOException
        HttpSession session = req.getSession(true);
    //res.setContentType("text/html");
    //PrintWriter out = res.getWriter( );
    //out.println("<HTML>");
    //out.println("<HEAD>");
    //out.println("<TITLE>");
    //out.println("A Servlet Example");
        String year   = req.getParameter("Year");
        String year_range      = req.getParameter("Year_Range");
        String county          = req.getParameter("County");
        Connection conn = null;
        try {
    //example code from tomcatmanual
    Context initContext = new InitialContext();
    Context envContext  = (Context)initContext.lookup("java:/comp/env");
    DataSource ds = (DataSource)envContext.lookup("jdbc/rosDS");
    //Connection
    conn = ds.getConnection();
              Statement stmt = conn.createStatement();
          String select = "select * from abridgment where " +
                          "(a_county = '" + county +
                          "' AND a_year_date = " + year +
    out.println("<DEBUG> <select> the select staement is : " + select);
          stmt.execute(select);
          ResultSet resultSet = stmt.getResultSet();
         Results abridgeresults = new Results();
         abridgeresults.setName("NaeemColl");
         Abridgment varabridgment = null;
          int nRows = 0;
          while(resultSet.next()){
            nRows++;
               varabridgment = new Abridgment();
           varabridgment.seta_county(county);
          varabridgment.seta_year_date(Integer.parseInt(year));
            varabridgment.seta_sub_year_volume(resultSet.getInt("a_sub_year_volume"));
           // out.println("varabridgment - attributes are:");
              //out.println("varabridgment - attributes are:" +varabridgment.geta_sub_year_volume());
              //out.println("varabridgment - attributes are:"+resultSet.getInt("a_sub_year_volume"));
              varabridgment.seta_page_id(resultSet.getString("a_page_id"));
            varabridgment.seta_month_date(resultSet.getInt("a_month_date"));
            varabridgment.seta_day_date(resultSet.getInt("a_day_date"));
            varabridgment.seta_year_sequence(resultSet.getLong("a_year_sequence"));
            varabridgment.seta_day_sequence(resultSet.getLong("a_day_sequence"));
            varabridgment.seta_year_volume(resultSet.getInt("a_year_volume"));
            varabridgment.seta_volume_id(resultSet.getString("a_volume_id"));
            varabridgment.seta_summary(resultSet.getString("a_summary"));
            varabridgment.seta_batch_id(resultSet.getLong("a_batch_id"));
            varabridgment.seta_image_id(resultSet.getLong("a_image_id"));
              abridgeresults.addAbridgment(varabridgment);
              //trying to use vector construct
          req.setAttribute("results",abridgeresults);
          //session.setAttribute("results", abridgeresults);
          stmt.close();
          conn.close();
    //out.println("</BODY>");
    //out.println("</HTML>");
    //      String sURL = res.encodeRedirectURL("/rossearch/results.jsp");
            try{
    //TEMPCOMM        res.sendRedirect(sURL);
    req.getRequestDispatcher("/rossearch/results.jsp").forward(req, res);
    //TEMPCODE
    //out.println("</BODY>");
    //out.println("</HTML>");
          catch(Exception e){
            System.err.println("Exception: FinderAidsSearchS.service: " + e);
        catch (Exception e) {
          System.err.println("Exception: FinderAidsSearchS.service: " + e);
    original code that worked fine - for one test row retrieved by query
      public void service(HttpServletRequest req, HttpServletResponse res)
           throws IOException
        HttpSession session = req.getSession(true);
    res.setContentType("text/html");
    PrintWriter out = res.getWriter( );
    out.println("<HTML>");
    out.println("<HEAD>");
    out.println("<TITLE>");
    out.println("A Servlet Example");
    out.println("</TITLE>");
    out.println("</HEAD>");
    out.println("<BODY>");
    out.println("Using servlets");
       // if (! checkParams(req, res))
       //      return;
        String year   = req.getParameter("Year");
        String year_range      = req.getParameter("Year_Range");
        String county          = req.getParameter("County");
        Connection conn = null;
        try {
    //example code from tomcatmanual
    Context initContext = new InitialContext();
    Context envContext  = (Context)initContext.lookup("java:/comp/env");
    DataSource ds = (DataSource)envContext.lookup("jdbc/rosDS");
    //Connection
    conn = ds.getConnection();
          Statement stmt = conn.createStatement();
          String select = "select * from abridgment where " +
                          "(a_county = '" + county +
                          "' AND a_year_date = " + year +
    out.println("<DEBUG> <select> the select staement is : " + select);
          stmt.execute(select);
          ResultSet resultSet = stmt.getResultSet();
          Abridgment abridgment = new Abridgment();
          abridgment.seta_county(county);
          abridgment.seta_year_date(Integer.parseInt(year));
        //  abridgment.a_sub_year_volume        = Long.parseLong(c_phone);
          if (resultSet.next()){
            abridgment.seta_sub_year_volume(resultSet.getInt("a_sub_year_volume"));
            abridgment.seta_page_id(resultSet.getString("a_page_id"));
            abridgment.seta_month_date(resultSet.getInt("a_month_date"));
            abridgment.seta_day_date(resultSet.getInt("a_day_date"));
            abridgment.seta_year_sequence(resultSet.getLong("a_year_sequence"));
            abridgment.seta_day_sequence(resultSet.getLong("a_day_sequence"));
            abridgment.seta_year_volume(resultSet.getInt("a_year_volume"));
            abridgment.seta_volume_id(resultSet.getString("a_volume_id"));
            abridgment.seta_summary(resultSet.getString("a_summary"));
            abridgment.seta_batch_id(resultSet.getLong("a_batch_id"));
            abridgment.seta_image_id(resultSet.getLong("a_image_id"));
            session.setAttribute("isNewAbridgment", new Boolean(false));
          else{
            session.setAttribute("isNewAbridgment", new Boolean(true));
            out.println("<DEBUG> <AbridgmentSearchS-service> Abridgment not found: " + abridgment);
          session.setAttribute("abridgment", abridgment);
          stmt.close();
          conn.close();
    out.println("</BODY>");
    out.println("</HTML>");
          String sURL = res.encodeRedirectURL("/rossearch/results.jsp");
              try{
            res.sendRedirect(sURL);
          catch(Exception e){
            System.err.println("Exception: FinderAidsSearchS.service: " + e);
        catch (Exception e) {
          System.err.println("Exception: FinderAidsSearchS.service: " + e);
    exception being thrown is:
    2005-11-07 02:45:20 StandardWrapperValve[jsp]: Servlet.service() for servlet jsp threw exception
    org.apache.jasper.JasperException
         at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:254)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:256)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2415)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:171)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:172)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:594)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:392)
         at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:565)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:619)
         at java.lang.Thread.run(Thread.java:536)
    ----- Root Cause -----
    java.lang.NullPointerException
         at org.apache.jsp.results_jsp._jspService(results_jsp.java:95)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:137)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:210)
    ......etc..
    the problem line in the results_jsp.java is:
    for (int i = 0; i < myAbridgments.size(); i++) in a scriptlet in the jsp to retrieve the List of beans and go through each one as follows:
    <% List myAbridgments = (List) request.getAttribute("results");
    for (int i = 0; i < myAbridgments.size(); i++) {
                    abridgment = (Abridgment) myAbridgments.get(i);
    %>ok then all wanabe java experts lets see who is the first and best at resolving this one!
    i have 10 points on offer - and a HUGE AMOUNT of graditude and appreciation for any one who can help me resolve this - Thanks.

    Check replies here
    http://forum.java.sun.com/thread.jspa?threadID=680127

  • Can't figure out what's wrong with my code

    Hello everyone. I'm new here and I am trying to write this program and am completely stuck. What i want the program to do is to read in two directory paths from the user and compare those directories and print out the differences. The catch is i only want it to compare 2 directories deep. For example, to compare the music folder on my hard drive and on my external hard drive. My folders are organized: my music>artist>albums, so i just want it to be able to search these folders, not the files inside the albums folders, to show what's different. I hope that makes sense... Anyways, here is the class that I have written to do the comparison. The error it is giving me is:
    Exception in thread "main" java.lang.NullPointerException
         at ToArrayList.ArrayToArrayList(ToArrayList.java:15)
         at NewFunctionClass.compareDirs(NewFunctionClass.java:44)
         at MainMenu.main(MainMenu.java:37)
    Any suggestion on how to make this work/why it doesn't work or any suggestion on a more efficient way to go about doing it would be greatly appreciated. Thank you.
    public class MainMenu {
         public static void main(String[]args)
              boolean flag = true;
              int userInput;
              String dir1;
              String dir2;
              System.out.println("****************************");
              System.out.println("*   Directory Comparison   *");
              System.out.println("*         v 1.2            *");
              System.out.println("****************************");
              while(flag)
                   System.out.println(" Make a selection:");
                   System.out.println(" 1. Compare new directories");
                   System.out.println(" 2. (coming soon)");
                   System.out.println(" 3. exit");
                   System.out.println(">");
                   userInput = inputClass.readInt();
                   switch(userInput){
                   case 1:
                        System.out.println("Enter the location of the first directory:");
                        dir1 = inputClass.readString();
                        NewFunctionClass.readDir1(dir1);
                        System.out.println("Enter the location of the second directory:");
                        dir2 = inputClass.readString();
                        NewFunctionClass.readDir2(dir2);
                       System.out.println("Differences in directories");
                       System.out.println("---------------------------");
                        System.out.println();
                        NewFunctionClass.compareDirs(dir1, dir2);
                   }//end case 1
                        break;
                   case 2:
                   }//end case 2
                   case 3:
                        flag = false;
                        break;
                   }//end switch
              }//end while
         }//end main
    }//end class
    import java.io.*;
    import java.util.*;
    public class NewFunctionClass {
         private static File[] mainDir1;
         private static File[] mainDir2;
         private static File[] subDir1;
         private static File[] subDir2;
         public static void readDir1(String dirName1) {
              File dir1 = new File(dirName1);
              mainDir1 = dir1.listFiles();
         }// end readDir1
         public static void readDir2(String dirName2) {
              File dir2 = new File(dirName2);
              mainDir2 = dir2.listFiles();
         }// end readDir1
         public static void compareDirs(String dir1, String dir2) {
              int i,j;
              List<File> mainDir1List;
              List<File> subDir1List;
              List<File> mainDir2List;
              List<File> subDir2List;
              ToArrayList a = new ToArrayList();
              // compare first directory to second
              for (i = 0; i < mainDir1.length; i++) {                                      //<<<<<
                   if (mainDir1.isDirectory()) {                                //<<<<< From here to the rest of the class is where most of the
                        subDir1 = mainDir1[i].listFiles(); //<<<<< error seems to be
                   }// end if
                   mainDir1List = a.ArrayToArrayList(mainDir1);
                   subDir1List = a.ArrayToArrayList(subDir1);
                   for (j = 0; j < mainDir2.length; j++) {
                        if (!mainDir1List.contains(mainDir2[j])) {
                             System.out.println("Didn't find " + mainDir2[j].toString()
                                       + " in " + dir1);
                        }// end if
                        if (!subDir1List.contains(mainDir2[j])) {
                             System.out.println("Didn't find " + mainDir2[j].toString()
                                       + " in " + dir1);
                        }// end if
                   }// end for
              }// end for
              // now compare second directory to first
              for (i = 0; i < mainDir2.length; i++) {
                   if (mainDir2[i].isDirectory()) {
                        subDir2 = mainDir2[i].listFiles();
                   mainDir2List = a.ArrayToArrayList(mainDir2);
                   subDir2List = a.ArrayToArrayList(subDir2);
                   for (j = 0; j < mainDir1.length; j++) {
                        if (!mainDir2List.contains(mainDir1[j])) {
                             System.out.println("Didn't find " + mainDir1[j].toString()
                                       + " in " + dir2);
                        if (!subDir2List.contains(subDir1[j])) {
                             System.out.println("Didn't find " + mainDir1[j].toString()
                                       + " in " + dir2);
                   }//end for
              }//end for
         }// end method
    }// end class
    import java.util.*;
    import java.io.*;
    public class ToArrayList {
         List<File>myArrayList;
         public ToArrayList(){
              myArrayList = new ArrayList<File>();
         public List<File> ArrayToArrayList(File[] myArray)
              int i;
              for(i = 0; i < myArray.length; i++)
                   myArrayList.add(myArray[i]);
              return myArrayList;
    }//end class
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    public class inputClass {
         public static String readString(){
              String str = "";
              InputStreamReader isr = new InputStreamReader(System.in);
              BufferedReader br = new BufferedReader(isr);
              try {
                   str = br.readLine();
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              str = str.trim();
              return str;
         }//end readString
         public static int readInt() {
              * Method for reading from keyboard and returning int
              String str = "";
              int i = 0;
              InputStreamReader isr = new InputStreamReader(System.in);
              BufferedReader br = new BufferedReader(isr);
              try {
                   str = br.readLine();
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              i = Integer.parseInt(str);
              return i;
         }// end readInt
    }//end inputClass

    Start by looking at line 15 of the ToArrayList class. That's where you are trying to use a variable which is still null. And don't fuss about making it "more efficient", it doesn't even work yet.

  • Trouble with calculating fields. Can't select (check) fields. Also can't figure out what's wrong with a division field (percent) that I created. Keep getting the pop up that format of the field doesn't allow blah blah blah... Help!

    Trouble with calculating fields. Can't select (check) fields. Also can't figure out what's wrong with a division field (percent) that I created. Keep getting the pop up that format of the field doesn't allow blah blah blah... Help!

    1. Use the mouse to select the field and then press the space bar.
    2. A null string is the same as zero. What is the result for division by zero?

  • Please help me figure out what's wrong with my girls fairly new Toshiba lap top.

    OK as of late my girl got a nice new laptop. It started off really fast and she was really happy with it. But in the past three weeks or so it's been acting up. It's not connecting to the Wi-Fi properly, and won't read and other available confections. If we reset and restart it one of two times that usually does the trick but the last time took 3 restarts before connecting to the right the way it was made to. To top it all off though. We were just laying down and she had heard the cooling fan going in it. This is odd because I had used it last and i always meme site to shut it down properly. But to my dismay when she picked it up and showed me I could clearly tell it was the cooling fan and that the lights on the side indicated that it was still on. What would cause these things to happen like this and more importantly, what can I do to not only fix the issues, but to stop this from becoming potentialy a bigger and worse problem? Please, anyone with any knowledge on this matter. Please help me out to prevent this from becoming a bigger more expensive issue. Thank you everyone for your time and you only would be greatly appreciated. The model number for this lasso to is XXXXXXXXX. Again thank you
    [Moderator edit to remove serial number corresponding to a L755-S5244.]

    your  L755-S5244 support site is here.
    L305-S5955, T9300 Intel Core 2 Duo, 4GB RAM, 60GB SSD, Win 7 Ultimate 64-bit

  • Can't figure out what is wrong with recovery DVDs

    Last year, right after turning my laptop ON, I've created 4 DVDs as such: http://i56.tinypic.com/6i79rn.jpg
    Recovery DVD Disk 1
    Recovery DVD Disk 2
    Recovery DVD Disk 3
    Windows Recovery Environment 64-bit
    My Laptop is Qosmio F60-14R, with Windows 7 Home Premium.
    Now all I want to do is format my laptop and re-install windows 7 Home premium using those 4 DVDs. However I can't figure out why I cannot re-install or get the laptop back to the factory state.
    This have wasted 8 hours straight of my time and frustrated me by great deal. Can you kindly tell me what I have to do? I am lost!

    Here is what I have done so far:
    I inserted 'Windows Recovery Environment (64-bit)' DVD and booted the laptop from it.
    First thing that loads up is a window with two options:
    - Toshiba Recovery Wizard
    - System Recovery Options
    Taking Toshiba Recovery Wizard as choice, clicking Next.
    It asks me: "Please set 1st Recovery Media and press Next to Continue.
    So, I insert Recovery DVD 1 and then click Next. However it ejects the disc drive (seems Recovery DVD 1 is not the correct Disk!).
    So I repeat the same process with Recovery DVD 2 and Recovery DVD 3 and again the Disk Drive ejects the Disks.... As a desperation attempt I even put the Windows Recovery Environment Disk inside but that as well get ejected.
    Okay, so the Toshiba Recovery Wizard is not the right choice 'it seems'.
    So, I restart the laptop and inserted 'Windows Recovery Environment (64-bit)' DVD and booted the laptop from it.
    First thing that loads up is a window with two options: (First choice failed, now trying second choice)
    - --Toshiba Recovery Wizard--
    - System Recovery Options
    So, choosing System Recovery Options this time and clicking Next. I Choose US as Keyboard, then click Next. A small window appears which gives me two further options:
    - Use Recovery tools that can help fix problems starting Windows. Select an Operating System to repair.
    - Restore your computer using a system image that you created earlier.
    So, I already tried the first choice and it takes me to another window with several recovery tools. One of the tools is System Image Recovery but when I click it, it gives a Warning messagebox that says:
    Windows cannot find a system image on this computer. etc.
    But when I insert every disk, still the warning messagebox shows up as if all the four recovery DVDs are irrelevant.
    So, it seems the first choice doesn't lead me anywhere. So, remains the second choice:
    - Restore your computer using a system image that you created earlier.
    Turns out it is exactly the same 'System Image Recovery' from first option mentioned few lines earlier. So, there you have it, checkmate.
    Please guide.

  • Need help figuring out what's going wrong

    With the explicit help/instructions of some users here I've managed to build some sort of a tokenizer.
    There are a couple of mistakes in its rules which I am aware of, and probably it could be a lot more efficient, but I've found something funny. When copying a sentence from a WSJ article:
    "Book publishers were locked in 11th-hour negotiations with Apple Inc. that could rewrite the industry's revenue model after the technology giant unveils its highly anticipated tablet device Wednesday."
    I got:
    Book
    publishers
    were
    locked
    in
    11th-hour
    negotiations
    with
    Apple
    Incorporated
    that
    could
    rewrin
    exemplificationthe
    industry
    is
    revenue
    model
    after
    the
    technology
    giant
    unveils
    its
    highly
    anticipated
    tablet
    devin
    exemplificationWednesday
    ./sd
    Remarkably, it rewrites the "ite" from "rewrite" to "in exemplification", just as "ice" from "device".
    Any thoughs as to why this mystery occurs?
    Here's the code:
    public static void main(String args[])
             InputStreamReader istream = new InputStreamReader(System.in) ;
             BufferedReader bufRead = new BufferedReader(istream) ;
             try {
                  System.out.println("Enter input.");
                  //read input
                  String input = bufRead.readLine();
                  //rewrite abbreviations
                  input = input.replaceAll("dr.", "doctor");
                  input = input.replaceAll("mr.", "mister");
                  input = input.replaceAll("e.g.", "exempli gratia");
                  input = input.replaceAll("vs.", "versus");
                  input = input.replaceAll("i.e.", "in exemplification");
                  input = input.replaceAll("Inc." , "Incorporated");
                  //more abbreviations to come here
                  //rewrite contractions
                  input = input.replaceAll("'ll", " will");
                  input = input.replaceAll("n't", " not"); // this one needs to be a bit smarter to cover cases like "won't"
                  input = input.replaceAll("'s", " is"); // this one needs to be a lot smarter, since now it incorrectly rewrites "John's house" to "John is house"
                  //perhaps rewrite some more stuff here
                  String[] tokens = input.split("(?=\\p{Punct}(\\s|$))|\\s+");
                  for(String t : tokens) {
                       //maybe rewrite back the stuff rewritten above?
                       //mark/tag sentence delimiters alreadys
                       if (t.equals(".") || t.equals("?") || t.equals("!") || t.equals(":") || t.equals(";")){
                            t = t + "/sd";
                       System.out.println(t);
             catch (IOException err) {
                  System.out.println("Error reading line");
             }     

    You're passing a regular expression into the replaceAll function (not just a normal String), so the "." you use in "i.e" really means "any character".
    To mean literally a dot, you have to escape it: "i\\.e".
    This problem will also happen in any of the other regular expressions with dots in them. So for example, "e.g." will replace "eggs", "edge", and "ergo" with "exempli gratia" as well.
    Read all about it here !
    PS- You might want to try using more meaningful post titles in the future...

  • Please Help me Figure out What is Wrong with Itunes Video Uploads

    Hi all. I would be so greatful for someones help. Since I bought my Ipod Video I frequesntly purchase videos from Itunes. Recently, I purchased 8 diffent videos-- ranging from television shows to movies, etc... The problem is that I cannot download anything fromthe Itunes store. Eachtime Itunes goes to download the items that I have purchased I receive an error message for each of the items as follows:
    "There was a problem downloading “______”.
    Parts of the file seems to be corrupted. To redownload the file, choose “Check for Purchases” from the Store menu."
    The thing is that this happens with any videos that Ipurchase now, so I doubt that they are all currupted. Could this bean issue with my settings or something? MaybeI am a bit clueless, but it is quite frustrating that I have spent alot of $ on things that I can't actually watch The problem doesn't happen with regularmusic downloads.
    Any help is VERY GREATLY appreciated.

    your  L755-S5244 support site is here.
    L305-S5955, T9300 Intel Core 2 Duo, 4GB RAM, 60GB SSD, Win 7 Ultimate 64-bit

  • Can someone please help me figure out what's wrong with my phone???

    So ive basically just deleted everything off my phone. i have 240 pictures and 2 short videos. my phone keeps displaying storage almost full when i do have crap on there!! my phone says i have 4.6 available space on icloud but my phone wont let me use that space!! this is getting real tiring and annoying!! I have 8gb &amp; my phone won't let me do anything with that 8gb!! &amp; I have 4.6 space available on iCloud!! Someone tell how to fix this!! I'm getting real angered about it

    Well, besides that my phone storage is still acting up. I just sat here &amp; deleted all my music &amp; everything!

  • When I boot up my Mac, Messages opens automatically. I quit the app, but it just re-opens itself. It won't stay off!!! I can't figure out what's wrong with it!

    For the past few months, my Mac has been acting weird. EVERY time I boot up the computer, Messages opens automaticallly (I am runing OS X 10.8.x). I quit the app, but it just re-opens a few seconds later! It just won't stay off! I've looked it up online and nothing helps. I have no idea what to do!!!

    Please read this whole message before doing anything.
    This procedure is a test, not a solution. Don’t be disappointed when you find that nothing has changed after you complete it.
    Step 1
    The purpose of this step is to determine whether the problem is localized to your user account.
    Enable guest logins* and log in as Guest. For instructions, launch the System Preferences application, select Help from the menu bar, and enter “Set up guest users” (without the quotes) in the search box. Don't use the Safari-only “Guest User” login created by “Find My Mac.”
    While logged in as Guest, you won’t have access to any of your personal files or settings. Applications will behave as if you were running them for the first time. Don’t be alarmed by this; it’s normal. If you need any passwords or other personal data in order to complete the test, memorize, print, or write them down before you begin.
    Test while logged in as Guest. Same problem?
    After testing, log out of the guest account and, in your own account, disable it if you wish. Any files you created in the guest account will be deleted automatically when you log out of it.
    *Note: If you’ve activated “Find My Mac” or FileVault, then you can’t enable the Guest account. The “Guest User” login created by “Find My Mac” is not the same. Create a new account in which to test, and delete it, including its home folder, after testing.
    Step 2
    The purpose of this step is to determine whether the problem is caused by third-party system modifications that load automatically at startup or login.
    Disconnect all wired peripherals except those needed for the test, and remove all aftermarket expansion cards. Boot in safe mode* and log in to the account with the problem. The instructions provided by Apple are as follows:
    Shut down your computer, wait 30 seconds, and then hold down the shift key while pressing the power button.
    When you see the gray Apple logo, release the shift key.
    If you are prompted to log in, type your password, and then hold down the shift key again as you click Log in.
    Safe mode is much slower to boot and run than normal, and some things won’t work at all, including wireless networking on certain Macs.  The next normal boot may also be somewhat slow.
    The login screen appears even if you usually log in automatically. You must know your login password in order to log in. If you’ve forgotten the password, you will need to reset it before you begin.
    *Note: If FileVault is enabled, or if a firmware password is set, or if the boot volume is a software RAID, you can’t boot in safe mode.
    Test while in safe mode. Same problem?
    After testing, reboot as usual (i.e., not in safe mode) and verify that you still have the problem. Post the results of steps 1 and 2.

  • HT204347 I need to find out what is wrong with my Macbook Pro. I have Adobe Reader installed on it and Adobe Flashplayer installed on it. I am not able to do anything with either of these programs, no videos, printing certificates, etc.

    I have adobe reader installed on my Macbook Pro and also Adobe flashplayer installed. I am not anble to see any video from the net, news feeds, or anything like that on my computer. I cannot print off certificates that I need all it does when I attempt to print the certificate is that it shows that it is loading and comes back and tells me there was an error in loading the information. I would appreciate any help I can get. Thanks
    Very Respectfully
    Steven Hetletvedt

    SMC Reset - check http://www.apple.com/support/macpro
    Clean out the insides and especially the graphic card.
    Both the 7300GTs could be failing, or X1900 with heat and dust (and causing the system fans to work harder)
    Disk Warrior maintenance along with SuperDuper
    Apple Hardware Test

  • Can't figure out what is wrong with my form

    Aloha all!
    Need some help from my DW friends.  For some reason my form isn't emailing all the fields.  I have sent several tests and only 2 of the fields are showing, the name and the comments.  I can't see why the other wouldn't be working, it looks right to me.  Can anyone see what the issue is?
    http://www.windwardmassage.com/evaluation.html
    Mahalo!!

    It's because most of your fields have the same name (textfield). Give each field a unique name (no spaces or special characters).

  • Need help figuring out how to deal with inheritence issues

    So I have these two classes, one's called MC, which represents a Multiple-Choice question, and one's called TF, which represents a True/False question. It would make sense to have TF inherit from MC, since TF is simple a MC question with two set options (true and false!).
    So it would also make sense for the constructor for MC to take a prompt (the question itself) and a Vector of Strings for choices, like so:
    MC(String prompt, Vector<String> choices);
    And then the TF constructor would just take a prompt (since the choices are always going to be true and false) and just pass a preset vector to the MC constructor, like so
    TF(String prompt);
    However, here's where the problem lies. Since I can must call my super constructor first, I have no way to initialize my preset Vector of choices (true and false). I could have a seperate MC constructor for handling this, but a parent class should not have to know what a child class needs to do, right? I need a quick and relatively proper solution for this if anyone has one. Thanks in advance!

    private static final List CHOICES = new ArrayList();
    static {
      CHOICES.add("True");
      CHOICES.add("False");
    public TrueFalse(final String question) {
      super(question, CHOICES);
    }For the record, if I were doing this, I'd make an interface called "Question" and have both TrueFalse and MultipleChoice implement it. If there were similar functionality, I'd put it in an abstract class AbstractQuestion, then have TrueFalse and MultipleChoice extend AbstractQuestion and implement Question.

Maybe you are looking for

  • HP 1300 wont print from Remote Desktop applications

    I have an HP 1300n attached via USB to a windows 7 computer.  I log onto a clien'ts windows 2003 server using remote desktop application.  I have installed the driver to HP 1300 PCL 5 on the remote server and of course it's installed on the windows 7

  • External Monitor Not Working After Upgrade

    Hello friends. I upgraded computer and software (Production Premium CS5.5). I use an external deck that is connected through Firewire. Premiere Pro sees the deck but does not output the image/video to it. I even managed to capture from the deck into

  • Please clarify the following related to IACOR

    Dear Experts, Please clarify the following related to IACOR. 1   For using workflow, IACOR service should be active in ITS? T or F 2   Is sometimes IACOR activation is required to be done prior to publishing a service u2013 T/F Regards, Ramakrishna

  • How to migrate 'responsibility' level personalizations?

    Hi all, We have done a set of personalizations at responsibility level in our UAT instance. We have no problem migrating the 'site' level personalization. We use the 'Functional Administrator' -> Import/Export utility. But, We find that the responsib

  • Online backup

    Hi After an online backup, if there is no checkpoint, there is no need for recovery, true? beacuse CHECKPOINT_CHANGE# of the datafiles are not modified therefore no need to recovery..