David W 131 Practically a Posting Shark

In Matthew 24 we can hear Jesus warning us about the present BIG FAKE NEWS:

For there shall arise false Christs, and false prophets, and shall shew great signs and wonders; insomuch that, if [it were] possible, they shall deceive the very elect. Behold, I have told you before.

The biggest LIE, so widely repeated these days, is that explosions, (i.e. undirected energy events - like mutations) can sometimes add useful code to a computer program (or useful structure to a computer)... this lie should be easily obviously a lie to any real computer programmer.

JamesCherrill commented: Pathetic nonsense. +0
rproffitt commented: "Bro, you OK?" +0
David W 131 Practically a Posting Shark

I haven't checked in for a long time ... We are, for sure, living in the time, long foretold, of Great Deception
... see Matthew 24.

The first thing I heard Trump say, back in 2016, was: I was greedy for myself, but now I'm going to be greedy for the people.

These are clearly the words of a man who has repented ... as we are all are called to do.

Note that true repentance has fruits that can be seen.

For example, has Trump brought back jobs to U.S.A.?

See:

https://youtu.be/ND40ur07Eyo

JamesCherrill commented: Are you joking? Trump repented??? Not on this planet +0
David W 131 Practically a Posting Shark

If you need use a C++ vector of char, (instead of C++ strings), you might like to try something like this:

// compareMyStrings.cpp //  // 2017-10-09 //

#include <iostream>
#include <vector>
#include <cstdlib> // re. atoi //
#include <cctype> // re. tolower //

typedef std::vector< char > MyString; // define MyString as a vector of type char elements //

// definition of overloaded operator << for MyString objects //
std::ostream& operator << ( std::ostream& os, const MyString& myStr )
{
    for( unsigned i = 0; i < myStr.size(); ++ i ) os << myStr[i];
    return os;
}

void readLine( std::istream& is, MyString& line )
{
    char ch;
    while( is.get( ch ) && ch != '\n' )
        line.push_back( ch );
}

bool match( const MyString& a, const MyString& b, unsigned numChars )
{
    if( a.size() >= numChars && b.size() >= numChars )
    {
        for( unsigned i = 0; i < numChars; ++ i )
        {
            if( a[i] != b[i] )
                return false;
        }
        // if reach here ...
        return true;
    }
    // if reach here ...
    std::cout << "Either '" << a << "'and/or '"
              << b << "' had less than " << numChars << " characters, so ...\n";
    return false;
}

MyString takeInString( const char* msg )
{
    std::cout << msg;
    MyString line;
    readLine( std::cin, line );
    return line;
}

char takeInChr( const char* msg )
{
    MyString reply = takeInString( msg );
    if( reply.size() )
        return reply[0];
    // else ...
    return 0;
}

bool more( const char* text …
David W 131 Practically a Posting Shark

Declaring a number with unsigned type is the same as declaring it with unsigned int type.

And note that the method
.size()
returns an unsigned int type.

So ...
when comparing numbers, we need to compare values with the same type.

We can safely assume here that the number of char’s you wish to check to be the same is a positive number ... yes?

If you need to use vectors of char ... just copy all the characters in each input string to a vector of type char ...

then your match function would compare two vectors of type char

David W 131 Practically a Posting Shark

Firstly, you may like to note that you mentioned using a vector of characters, but your code uses C++ strings, which is probably what you really meant to say?

Also, you need to lean to break up your program into 'jobs' ... and each job can be called by coding a function to do that specific job, then calling the function to execute that job at the appropriate place in the logic flow of your program.

Using descriptive function names, will help to self-document the logic flow of your program.

The following example may help you to see this:

// compareStrings.cpp //  // 2017-10-07 //

#include <iostream>
#include <sstream>
#include <string>
#include <cctype>

bool match( const std::string& a, const std::string& b, unsigned numChars )
{
    if( a.size() >= numChars && b.size() >= numChars )
    {
        for( unsigned i = 0; i < numChars; ++ i )
        {
            if( a[i] != b[i] ) return false;
        }
        // if reach here ...
        return true;
    }
    // if reach here ...
    std::cout << "Either '" << a << "'and/or '"
              << b << "' had less than " << numChars << " characters, so ...\n";
    return false;
}

std::string takeInString( const std::string& msg )
{
    std::cout << msg;
    std::string line;
    getline( std::cin, line );
    return line;
}

char takeInChr( const std::string& msg )
{
    std::string reply = takeInString( msg );
    if( reply.size() )
        return reply[0];
    // else ...
    return 0;
}

bool more( const std::string& text )
{
    if( tolower( takeInChr( "More " …
rproffitt commented: Call your things by names that make sense is always a good idea. +12
David W 131 Practically a Posting Shark

Also ... in C++ you usually do NOT want redundant parameters in a class!

For example, in a circle, if you know one of: radius, diameter, circumference, area
you can calculate all the other ...

And note that PI (pi) is a constant value defined as the ratio of the circumference of any circle to its diameter,

You may like to see this demo code that also loops until
the user inputs valid numeric input
and also
as long as more() returns true.

// test_class_Circle.cpp //  // 2017-07-30 //

// you had ...

/*
#include "stdafx.h"
#include <iostream>
using namespace std;

class Circle
{
public:
    Circle(double radius, double diameter, double circumference);
    double pi = 3.14;
    double radius = 0;
    double diameter = radius * 2;
    double circumference = 2 * pi * radius;
    double pi * radius * radius;
};

void main()
{
    cout << "enter radius radius" << endl;
    cin << Circle.radius;
    cout << Circle.diameter;
    cout << Circle.circumference;
    cout << Circle.area;
    system("pause");
}
*/

// This is a nice student way it could/should be done in C++ //

#include <iostream>
#include <string>
#include <cmath> // re. acos //

const double PI = acos(-1.0 );

class Circle
{
private:
    double radius;
public:
    // default ctor...
    Circle() : radius(0) {}
    // ctor with passed in radius ...
    Circle( double radius ) : radius(radius) {}

    double get_radius() const { return radius; }
    double get_diameter() const { return radius * 2; }
    double get_circumference() const { return 2.0 * …
David W 131 Practically a Posting Shark

Sometimes a table-lookup method is a nice way to handle problems like this.

You might like to see the examples here:

http://developers-heaven.net/forum/index.php/topic,134.msg709.html#msg709

David W 131 Practically a Posting Shark

You may like to try someting like this to get valid input and to prevent program crashing on accidental input of an invalid type.

#include <stdio.h>

#define ROWS 5
#define COLS 10
#define COST_PER_SEAT 150

/* Simple input of an integer...  i.e. NO range checking done */
int takeInInt( const char* prompt )
{
    int testInt;
    for( ; ; ) { /* an example of a C/C++ forever loop ... until 'return' */
        fputs( prompt, stdout );
        fflush( stdout );
        if( scanf( "%d", &testInt ) && getchar() == '\n' ) {
            return testInt;
        }
        /* else ...*/
        while( getchar() != '\n' ); /* 'flush' stdin ... as we go */
        puts( "Invalid input! Integers only please ..." );
    }
}

int takeInIntMinMax( const char* prompt, int min, int max )
{
    int testInt;
    for( ; ; ) { /* an example of a C/C++ forever loop ... until 'return' */
        fputs( prompt, stdout );
        fflush( stdout );
        if( scanf( "%d", &testInt ) && getchar() == '\n' ) {
            if( testInt >= min && testInt <= max ) {
                return testInt;
            } else {
                printf("Valid input range is %d..%d\n", min, max);
                continue;
            }
        }

        /* else ...*/
        while( getchar() != '\n' ); /* 'flush' stdin ... as we go */
        puts( "Invalid input! Integers only please ..." );
    }
}

void seatDisplay(int a[ROWS][COLS]) { /* this function shows the seat plan */
    int i, j;
    for (i = 0; i < ROWS; i++) {
        for (j = 0; j < COLS; …
David W 131 Practically a Posting Shark

You seem to have two distinct parts to your project:

1) Code and test a class String

2) Use that class (and perhaps some of its methods) to process lines of words.

It may be helpful to start with part 2) and there, using the C++ string until 2) is ALL working properly.

Then, after all tests ok, sub in slight changes in code to 2) to use you own 'home grown' String class. (The methods you need in part 2) may guide what methods you need to code in your part 1) class String coding project.

David W 131 Practically a Posting Shark

Where in your code is the problem ... what lines ? What are the error messages?

If you have a static method in class A
you can call like this:

A.yourAstaticMethod(anyArgsGohere...);

Otherwise you need to firstly create an object of class A
A a; // call default ctor...
a.yourAmethod(anyArgsGoHere...);

David W 131 Practically a Posting Shark

@ Jemone_1
You said:

Yes I can use functions but I choose to have it working fully before I implement them

You have it backwards ...
well named functions (procedures) are your friend to expedite logic flow ...

and to break up your project into discrete logical tasks.

And re.
@tinstaafl's map pf struct idea ...
an excellent idea ...
but it may be a little advanced for you at this stage.

You may like to just use an array of 12 struct's instead?

You will also need a functon to tell if it is a leap year
and to then add 1 to the days
if the year is a leap year and the month is the 2nd month.
(If you need help, there are many ways to code for this, and someone here will be glad to help you if you can't find a good working example to help you get started with the logic.)

If you use an array of 12 struct elements ...
a fuction to do a simple liner search for the matching month,
could suffice here.

A nice looking project ... when is it due?

David W 131 Practically a Posting Shark

@ Dean_5, are you a Java programmer?

You said:

... C++ doesn't allow string comparison via "==" ...

Please take a look at:
http://www.cplusplus.com/reference/string/string/operators/

David W 131 Practically a Posting Shark

It is now past 17:30 EST ... and you will need to ask for an extension if you still need help with your school project ...

In the future ...

if you wish help at this very willing to help, help site,

please firstly supply us with the code you have tried already ...

and indicate where you are having issues ...

and we will then see what we might do to help you on your way.

Shalom shalom,
David

David W 131 Practically a Posting Shark

b. extend ... to handle input integers with an arbitrary number of digits.

How do you plan to handle very long integers?

Here is some C++ code that may help:

// incrementEachDigit.cpp //  // 2016-10-28 //

// compile with a C++ 11 or better compiler ... //

#include <iostream>
#include <string>
#include <cctype>

using namespace std;

string takeInLine( const string& prompt )
{
    cout << prompt;
    string line;
    getline( cin, line );
    return line;
}

bool isValidPosInt( const string& str )
{
    for( auto ch : str )
    {
        if( !isdigit(ch) ) return false;
    }
    // if reach here, then ...
    if( str.size() > 0 ) return true;
    // else ...
    return false;
}

string takeInValid4Dig()
{
    while( true )
    {
        string iStr = takeInLine( "Enter a 4 digit int between 1000 and 9999: " );
        if( isValidPosInt(iStr) )
        {
            int i = stoi( iStr );
            if( i >= 1000 && i <= 9999 ) return iStr;
            // else ...
            cout << "Only values in range 1000..9999 accepted here.\n";
        }
        else cout << "Only positive integers are accepted here.\n";
    }
}

string& lopOffAny4DigOverFlow( string& str )
{
    if( str.size() == 5 )
        str.erase(0, 1);
    return str;
}

string takeInValidPosInt()
{
    while( true )
    {
        string iStr = takeInLine( "Enter a positive int: " );
        if( isValidPosInt(iStr) )
            return iStr;
        else
            cout << "Only positive integers are accepted here.\n";
    }
}

string& inc( string& str )
{
    int carry = 0, end = str.size()-1, over;
    for( ; end >= …
David W 131 Practically a Posting Shark

In Python, that easily handles for you, values of type int, to be any length,
you might simply code like this:

# incrementEachDigit.py #  # 2016-10-28 #

def takeInValid4Dig():
    while True:
        try:
            i = int(input( "Enter a 4 digit int between 1000 and 9999: " ))
            if 1000 <= i <= 9999:
                return i
            else:
                print( "Please note that value input MUST BE in range 1000..9999" )
        except ValueError:
            print( "Input must be an integer." )

def lopOffAnyOverFlow( i ):
    iStr = str(i)
    if len(iStr) == 5:
        return int(iStr[1:])
    return i

i = takeInValid4Dig()
print( "You entered", i )
i += 1111
print( "After adding 1111, the number i is:", i )
i = lopOffAnyOverFlow( i )
print( "After loping off any overflow, the number i is:", i )

print() # a blank line #

def takeInValidPosInt():
    while True:
        try:
            i = int(input( "Enter a positive integer: " ))
            if i >= 0:
                return i
            else:
                print( "Please note that value input MUST BE 0 or greater." )
        except ValueError:
            print( "Input must be an integer." )          

i = takeInValidPosInt()
print( "You entered", i )
iStr = str(i)
iLen = len(iStr)
ones = "1"*iLen

i += int(ones)
print( "After adding {}, the number i is: {}".format( ones, i ) )
David W 131 Practically a Posting Shark

One quick way to handle this, that easily extends to 'integers' of any length, is to input your numbers as strings ...

and then to code a function to increment each 'digit' in this string as proscribed ...

with a carry term to the 'next left' digit for the case of the incremented 'digit value' becoming 10.

I could show you an example coded in C, C++, Python or Java?

For now, you might like to look at a BIG INT demo that uses strings as 'numbers':

http://developers-heaven.net/forum/index.php/topic,426.0.html

David W 131 Practically a Posting Shark

This discussion is useful ... maybe even a little fruitful ...

and perhaps is typical of many little jobs getting their start ...

starting out with a fairly simple and narrow focus in mind ...

but later, perhaps, the job gets expanded, to keep the programmer(s) employed :)

But more seriously here,
I fail to see the need to expand the focus I have suggested,
since the idea (and initial student Console code presented) here ...
was just to ease absolute newbies coding Console IO,
and so that their programs would not crash on illegal types of data input.

Once a student progresses some, typically, won't they be encouraged to code their own error handling routines for file IO, using the latest Java NEW IO (nio) ?

Shalom shalom,
David

David W 131 Practically a Posting Shark

Just to confirm the ease I suggested ...
you might like to see this quickly coded Python example:

# findVolForSphereGivenRadius.py #  # 2016-10-02 #

def takeInFloat( prompt ):
    while True:
        try:
            return float( input( prompt ) )
        except( ValueError ):
            print( "Only decimal numbers are valid input here. Try again." )

if __name__ == "__main__":
    from math import pi
    PROMPT = "Input a radius to find the volume for that sphere: "
    while True:
        radius = takeInFloat( PROMPT )
        print( "The volume of a sphere with radius {:.2e} is: {:.2e}".
               format(radius, 4/3.0*pi*radius**3 ) )

        if input( "More (y/n) ? " ).lower() == "n":
            break
David W 131 Practically a Posting Shark

Is there a clue in the Dani user name that has a C++ in it, as in:

Linzi c++

Maybe it's some kind of generic code ?

So ... to answer the request about coding an input request:

int radius = takeInInt( "Enter your desired radius: " ); // 'takeInInt' is user defined/coded //

You could then put all this code into some function, say we name it: getVolume();

then you could code a big main loop like this:

do
{
    getVolume();
}
while( more() );

Oh .. you also need to code for the function more, before you can call it in your C++ or C program.

But ... if you are looking for a nice language to start your coding of this little programming problem ... you will appreciate coding it easily, in Python.

David W 131 Practically a Posting Shark

As suggested above, you seem to be a bit confuzzed?

Working with C++ binary files can be a little tricky,
especially at the beginning.

I'm not sure what you were supposed to do here,
but here is a little demo class
to show how one might append int values
to the end of a binary file of integers,
and to read then all back from this 'random access type bin file',
in reverse order;

// classBinary.cpp //

// using C++ 11 or better compiler //

#include <string>
#include <fstream>
#include <iostream>
#include <climits>

using namespace std;

#define debugging true

class Binary
{
private:
    string fname;
    size_t len;

    static const unsigned BYTES_IN_INT = sizeof(int);

public:
    //ctor.. with a default fname given here //
    Binary( const string& afname="BinaryFile.bin" ) : fname(afname)
    {
        ifstream fio( fname, ios::binary );
        if( fio )
        {
            fio.seekg( 0, ios::end );
            len = fio.tellg()/ BYTES_IN_INT;
#if debugging
            cout << "Opening len is: " << len << '\n';
#endif
            fio.close();
        }
        else len = 0;
    }

    void appendBin( int val );
    int readBin( streampos pos = 0 );
    size_t size() const { return len; }
    string name() const { return fname; }
} ;

void Binary::appendBin( int val )
{
    ofstream fio( fname, ios::app | ios::binary );
    if( fio )
    {
        fio.write( (char*)&val, BYTES_IN_INT );
        ++len;
        fio.close();
    }
    else cout << "Error opening, to write,  file: " << fname << "\n";
}

// returns INT_MIN if NO value swas read
int Binary::readBin( …
David W 131 Practically a Posting Shark

We seem to have a little communication problem here ?

I am NOT at all concerned here about getting/handling any input from a file ,

neither by opening a file and reading it ...

nor by redirecting input for the program to be from a file.

That (student) task, if need and time permits,
could possibly be handled by an other FileIO type class, or by the time a student gets to file IO handl;ing, probably by directly using,
at first the scanner class,
https://docs.oracle.com/javase/tutorial/essential/io/scanning.html
than later, perhaps, by using Java's latest nio (New I O) routines.
http://www.javapractices.com/topic/TopicAction.do?Id=42

Recall these opening comments:

valid and crash proof, user (Console type) input, (and also handle Console output.)

and:

there is no redirected input from file to be concerned about here, since these takeIn 'methods' all print to console the programmer formed prompt that guides their desired line or (line) numeric input.

Thus, there exists no need here, to be concerned about handling the EOF case, since NO file handling is to be done by this class.

Note also that ...
we are here, exclusively using, Java's nextLine() calls to take in the whole line,
on ALL the prompted requests for (line) input.

This desired line input behaviour here, also includes handling,
'eating the end of line whitespace chararcters'.

(I presume the Java Scanner class nextLine() call is already well tested and safe for taking in a …

David W 131 Practically a Posting Shark

I suggest a more limited goal here ...

for example, there is no redirected input from file to be concerned about here,
since these takeIn 'methods' all print to console
the programmer formed prompt that guides their desired line
or (line) numeric input.

I have found these few functions (example C++ prototypes listed below):

string takeInLine( const string& prompt );
int takeInInt( const string& prompt );
double takeInDouble( const string& prompt );
bool more();

to vastly ease and speed up coding of many C, C++ and Python student type problems and facilitate crash proof input ...

and these methods can easily be enhanced
to have added passed in parameters,
to validate the range of numbers accepted for input,
if that needs to be limited.

For example:

int takeInInt( const string& prompt, int min, int max );

Here is a Python version to help illustrate this concept:

# file name: TakeInIntFloat.py #

# this version: 2016-09-30 #

def takeInInt( prompt ):
    while( True ):
        try:
            return int( input( prompt ))
        except ValueError:
            print( "Only integer numbers are accepted here." )

def takeInFloat( prompt ):
    while( True ):
        try:
            return float( input( prompt ))
        except ValueError:
            print( "Only decimal nubers are accepted here." )

def more( default="y" ):
    reply = input( "More (y/n) ? " ).lower()
    if default.lower() == "y":
        return reply != "n"
    else:
        return reply == "y"

if __name__ == "__main__":
    while True:
        name   = input(       "Enter this user name :  " ) …
David W 131 Practically a Posting Shark

Here is another Dani student contributed example problem, slightly reworked here to illustrate using the above class Console ...

This example also uses the following class Investment:

public class Investment {

    private double monthlyInvestment;
    private double yearlyInterestRate;
    private int years;

    // default ctor...
    public Investment() {

        monthlyInvestment = 0.0;
        yearlyInterestRate = 0.0;
        years = 0;
    }

    // passed in values ctor...
    public Investment( double monthlyInvestment, double yearlyInterestRate, int years ) {

        this.monthlyInvestment = monthlyInvestment;
        this.yearlyInterestRate = yearlyInterestRate;
        this.years = years;
    }

    void takeIn()
    {
        monthlyInvestment  = Console.takeInDouble( "Enter next monthly investment    : " );
        yearlyInterestRate = Console.takeInDouble( "Enter this yearly interest rate  : " );
        years              = Console.takeInInt(    "Enter investment number of years : " );
    }

    public double getFutureValue() {

        double monthlyInterestRate = yearlyInterestRate/12.0/100.0;
        int months = years * 12;
        double futureValue = 0.0;
        for( int i = 1;i <= months; i++ ) {

           futureValue = (futureValue+monthlyInvestment) * (1+monthlyInterestRate);
        }
        return futureValue;
    }

    @Override
    public String toString() {

        return String.format( "Inv/Mo: monthlyInvestment(%8.2f), " +
                              "yearlyInterestRate(%5.2f%%), Years(%3d)" + 
                              "\n        Future value($%,10.2f)", 
                              monthlyInvestment, 
                              yearlyInterestRate, years,
                              getFutureValue() );
    }
}

Now the 'main' program file:

import java.util.ArrayList;

public class FutureValue {

    public static void main(String[] args) {

        // displayLine a welcome message //
        Console.println( "Welcome to the Future Value Calculator" );
        Console.println();

        ArrayList< Investment > investmentList = new ArrayList <> ();

        do{
            // get empty new investment obj.
            Investment inv = new Investment();

            // get input from user
            inv.takeIn();

            // Ok ... add this new obj. to the list ...
            investmentList.add( inv …
David W 131 Practically a Posting Shark

This thread will be an attempt to develope a SIMPLE (and good enough) class
for beginning Java students, to ease their coding
for valid and crash proof, user (Console type) input,
(and also handle Console output.)

We assume here that beginning students need not worry much,
about obtaining the fastest possible IO,
with respect to the console,
in their typical beginning student type problems,

(Note that IO is often the big bootle-neck
to the total time it takes to execute a typical student type program,
since printing to screen is slow,
and there are even longer waits for a user to enter prompted data,
and thus the very significant added time to wait here,
for user to finally press the (data) Enter key.)

Thus, we are NOT overly concerned here about speed.

Simplicity and ease of understanding the code is the aim here ...

And thus, beginning coders can fairly easily adapt,
(i.e. easily add new methods),
so that this IO class will be very useful
to ease their IO coding in many,
if not most all of,
their student coding problems.

Credits:

With thanks to 'PulsarScript' for:

https://www.daniweb.com/programming/software-development/threads/506093/java-output

and to 'sarah_15' for:

https://www.daniweb.com/programming/software-development/threads/506097/java-program

and to Dani's own 'JC' for his inspiration for this thread.

Ok ... here is a simple Console class
that students might like to use
to ease and simplify handling (most) all (of) their Console IO:

David W 131 Practically a Posting Shark

Yah ... sorry PulsarScript ... I think that JC suggested that ... (starting a new thread) ... way back :(

Thanks for your post that 'got the ball rolling'.

So asap I will start a new thread.

Shalom,
dwz

David W 131 Practically a Posting Shark

Also ...

I have been thinking about a simpler class for beginning students to use to handle console io, for begining student type io problems taking in numeric values via line input, (as in Python.)

You may like to see the demo below:

// this version: 2016-09-28 //

import java.util.Scanner;

public class Console {

    private static Scanner sc = new Scanner( System.in );

    public static String takeInLine( String prompt ) {
        System.out.print( prompt );
        return sc.nextLine();
    }

    public static int takeInInt( String prompt ) {
        while( true ) {
            try {
                return Integer.parseInt( takeInLine( prompt ) );
            } catch( NumberFormatException e ) {
                System.out.println( "Error! Invalid integer. Try again." );
            }
        }
    }

    public static long takeInLong(String prompt) {
        while( true ) {
            try {
                return Long.parseLong( takeInLine( prompt ) );
            } catch( NumberFormatException e ) {
                System.out.println( "Error! Invalid long. Try again." );
            }
        }
    }

    public static double takeInDouble(String prompt) {
        while( true ) {
            try {
                return Double.parseDouble(takeInLine( prompt ) );
            } catch( NumberFormatException e ) {
                System.out.println( "Error! Invalid decimal. Try again." );
            }
        }
    }

    // Call as: more( "Y" ); // to have default case of 'Yes more' //
    // Call as: more( "N" ); // to have default case of 'No more'  //
    public static boolean more( String defaultStr ) {
        String reply = takeInLine( "More (y/n) ? " );
        if( defaultStr.equalsIgnoreCase( "Y" ) ) {
            if( reply.equalsIgnoreCase( "N" ) ) {
                return false;
            } else {
                return true;
            }
        } else { …
David W 131 Practically a Posting Shark

Great points James for Java students to utilize :)

Also ... I meant to ask you to clarify more your suggestion above ... about and alt 'InputStream' constructor ... Perhaps you could give an example of it ... and it's use?

David W 131 Practically a Posting Shark

Thank you James for your comments and suggestions:

FutureValue line 32 - the toString() is redundant because print and println do that to their arguments anyway

Good catch ... I missed updating that from some earlier 'test code' I was using,

TakeInLine: Lines 74 and 95 should be System.out - some users will have a default logging setup that redirects System.err to a log file

Great 'heads up'.

the loop constructs can be much simpler...

Yes I know ... and thanks for providing students with nice clean demo code that many may prefer to use in 'their version' ... my goal here was to show one old school preferred coding style where some stylists like to only exit at the bottom of a function ... neither would some like to jump out of a try ... catch struture.

{
   // block coding style to help coder see that the 'start' { and 'stop' } of block 
   // both have been coded //
}

I must confess to hanging on to my C and C++ block coding style ... as I begin to dable in Java :)

David W 131 Practically a Posting Shark

With respect to a custom TakeIn class to aid valid student user input from the keyboard, i put together the following TakeInLine class awhile ago, that you may like to see and use instead, used below, in a rework of the OP's FutureValue problem:

1st file:

// TakeInLine.java //  // revised: 2016-09-26 //

import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class TakeInLine
{
    // Create a BufferedReader using System.in ... //
    BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );

    String takeInLine( String msg )
    {
        System.out.print( msg );
        String line = null;
        try
        {
            line = br.readLine();
        }
        catch( IOException e )
        {
            System.err.println( e );
            System.err.println( "UNEXPECTED string input error." );
            line = ""; // default here to empty line ... //
        }
        return line;
    }

    char takeInChr( String msg )
    {   
        String line = takeInLine( msg );
        if( line.length() > 0 )
            return (char)line.charAt(0);
        // else ...
        return (char)0; 
    } 

    int takeInInt( String msg )
    {   
        int iVal = 0;
        boolean loop = true;
        while( loop )
        {
            String line = takeInLine( msg );
            try
            {
                iVal = Integer.parseInt( line );
                loop = false;
            }
            catch( NumberFormatException e )
            {
                System.err.println( "Error! " + e );
                System.err.println( "Only valid 'int' numbers are accepted, so try again." );
            };
        }
        return iVal;
    }

    long takeInLng( String msg )
    {   
        long longVal = 0;
        boolean loop = true;
        while( loop )
        {
            String line = takeInLine( msg );
            try
            {
                longVal = Long.parseLong( line );
                loop = false; …
David W 131 Practically a Posting Shark

And ... If you prefer to use private data members in your Java classes, you could sub in the below three classes (files) where appropriate ...

public class Customer
{
    private static Console con = new Console();

    private int number = 0;
    private String name = "";

    public int getNumber()  { return number; }
    public String getName() { return name; }

    public void takeInInfo()
    {
        number = con.getInt(  "Enter customer number : " );
        name = con.getString( "Enter customer name   : " ).toUpperCase();
    }
}

And ...

public class Item
{
    private static Console con = new Console();

    private String type = "";
    private int quantity = 0;
    private double price = 0.0;

    public double extended() { return quantity * price; }

    public void takeInInfo()
    {
        type = con.getString(  "Enter type     : " );
        quantity = con.getInt( "Enter quantity : " );
        price = con.getDouble( "Enter price    : " );
    }
}

And ...

 public class Invoice
{  
    private static final double  DISCOUNT_BEGINS = 500.00; 
    private static final double  DISCOUNT_RATE   = 0.05;
    private static final double  NET_TAX_RATE    = 0.0825;

    private static String HEADER = "A NEW CUSTOMER INVOICE BEGINS ...";

    // Note: these next two obj's get new values on each pass in loops below //
    private static Customer cust = new Customer();
    private static Item item     = new Item();

    public static void main(String[] args)
    {
        //Outer loop for Customer input ...
        do 
        {
            // Note: in the below format string, the %n means print a newline //
            System.out.format( …
David W 131 Practically a Posting Shark

Since you seem a little confuzzed ...

the following may help to jump-start your Java coding ...

Firstly ... recall in Java we like to use classes ... but here I am using classes more like we use a C++ struct ... this is to make the coding simpler ...
(i.e. NO need here to code for getters )

So I borrowed and EDITED a bit the Console class from the other program I referred you to earlier ...

So in the first file called: "Console.java", you could use these input methods ...

import java.util.Scanner;

public class Console {

    private static Scanner sc = new Scanner(System.in);

    public static String getString(String prompt) {
        System.out.print(prompt);
        String s = sc.nextLine();
        return s;
    }

    public static int getInt(String prompt) {
        int i = 0;
        while (true) {
            System.out.print(prompt);
            try {
                i = Integer.parseInt(sc.nextLine());
                break;
            } catch (NumberFormatException e) {
                System.out.println("Error! Invalid integer. Try again.");
            }
        }
        return i;
    }

    public static double getDouble(String prompt) {
        double d = 0;
        while (true) {
            System.out.print(prompt);
            try {
                d = Double.parseDouble(sc.nextLine());
                break;
            } catch (NumberFormatException e) {
                System.out.println("Error! Invalid decimal. Try again.");
            }
        }
        return d;
    }
}

Then you could use these next two classes (each file name is the same as the class name with a .java at the end of the file name as per this: 'FileName.java':

 class Customer
{
    static Console con = new Console();

    int number = 0;
    String name = "";

    void takeInInfo()
    {
        number = con.getInt(  "Enter customer …
David W 131 Practically a Posting Shark

You could use some class methods to aid console string input as per here;

https://www.daniweb.com/programming/software-development/threads/506093/java-output

Also a class for Customer with methods
and a class for Item with methods

maybe each could have takeInInfo methods also ?

Then all you need is a loop with in a loop as per your instructions to take in each customer ... and for each customer ... to take in all the items requested ... then to process data for for each customer ... as you go ... and output nicely formatted output

David W 131 Practically a Posting Shark

Try these three files:

1st:

import java.util.Scanner;

public class Console {

    private static Scanner sc = new Scanner(System.in);

    public static void displayLine() {
        System.out.println();
    }

    public static void displayLine(String s) {
        System.out.println(s);
    }

    public static String getString(String prompt) {
        System.out.print(prompt);
        String s = sc.nextLine();
        return s;
    }

    public static int getInt(String prompt) {
        int i = 0;
        while (true) {
            System.out.print(prompt);
            try {
                i = Integer.parseInt(sc.nextLine());
                break;
            } catch (NumberFormatException e) {
                System.out.println("Error! Invalid integer. Try again.");
            }
        }
        return i;
    }

    public static double getDouble(String prompt) {
        double d = 0;
        while (true) {
            System.out.print(prompt);
            try {
                d = Double.parseDouble(sc.nextLine());
                break;
            } catch (NumberFormatException e) {
                System.out.println("Error! Invalid decimal. Try again.");
            }
        }
        return d;
    }
}

2nd:

public class Investment {
    private double monthlyInvestment;
    private double yearlyInterestRate;
    private int years;

    // default ctor...
    public Investment() {
        this.monthlyInvestment = 0.0;
        this.yearlyInterestRate = 0.0;
        this.years = 0;
    }
    // passed in values ctor...
    public Investment(double monthlyInvestment, double yearlyInterestRate, int years) {
        this.monthlyInvestment = monthlyInvestment;
        this.yearlyInterestRate = yearlyInterestRate;
        this.years = years;
    }

    public double getMonthlyInvestment() {
        return monthlyInvestment;
    }

    public void setMonthlyInvestment(double monthlyInvestment) {
        this.monthlyInvestment = monthlyInvestment;
    }

    public double getYearlyInterestRate() {
        return yearlyInterestRate;
    }

    public void setYearlyInterestRate(double yearlyInterestRate) {
        this.yearlyInterestRate = yearlyInterestRate;
    }

    public int getYears() {
        return years;
    }

    public void setYears(int years) {
        this.years = years;
    }

    public double calculateFutureValue()
    {
        double monthlyInterestRate = yearlyInterestRate/12.0/100.0;
        int months = years * 12;
        double futureValue = 0.0;
        for( int i = 1;i <= months; i++ ) {
           futureValue = (futureValue+monthlyInvestment) …
David W 131 Practically a Posting Shark

It is good for you to learn, as early as possible, some simple 'student type' ways to get numeric imput ...

from a keyboard user,

so that the running program will nor crash if invalid data was entered.

The following little demo may help to get you started in that direction.

// fill2Darray.cpp //


/*
    function definition, fillArray,  fills int_array.

    Repeatedly prompt the user to enter an integer at the keyboard.

    (Input values should be stored in row order).

   *here* the fillArray has TWO arguments: 2Dary & num_rows

    'Protect' arrray values from being changed by the function when necessary.
*/

#include <iostream>


// set what you need here ...
const int NUM_COLS = 4;


// An example od a 'student way' to get valid user input
// from keyboard so program will NOT crash
// IF user enters invalid data. //
void fill2Dary( int matrix[][NUM_COLS], const size_t num_rows )
{
    for( size_t r = 0; r < num_rows; ++ r )
    {
        std::cout << "Enter " << NUM_COLS << " integers on the next line, to fill row "
                  << (r+1) << ", then press the 'Enter' key:\n";
        for( size_t c = 0 ; c < NUM_COLS ;  )
        {
            if( std::cin >> matrix[r][c] ) ++c;
            else
            {
                std::cin.clear();
                std::cin.sync();
                std::cout << "Imvalid entry. Please enter whole row "
                          << (r+1) << " again ...\n";
                c = 0;
            }
        }
        std::cin.sync(); // 'flush' any wxtra entries entered at end of row ... //
    }
}


template < typename T > …
David W 131 Practically a Posting Shark

Here is a little more general way one might handle a problem like this ...
(the code also demo's using templates in C++.)

// print_a_col.cpp //


#include <iostream>

using std::ostream;


// set here what you need ...

const size_t NUM_COLS = 4;


// NOTE: below we pass in ALL parameters as const ...
// EXCEPT ostream ... which is modified here. //

template < typename T >
void output( const T matrix[][NUM_COLS],
             const size_t num_rows,
             const size_t col_to_print,
             std::ostream& os = std::cout,
             const char end = '\n' )
{
    if( col_to_print < NUM_COLS )
        for( size_t r = 0; r < num_rows; ++ r )
        {
            os << matrix[r][col_to_print] << end;
        }
}


int main()
{
    using std::cout;

    const int mat[][NUM_COLS] =
    {

        { 1, 3, 3, 4 },
        { 5, 6, 7, 8 }
    } ;
    const int num_rows = sizeof mat / sizeof(int) / NUM_COLS;

    cout << "printing col with index 0: \n";
    output( mat, num_rows, 0 );

    cout << "printing col with index 1: \n";
    output( mat, num_rows, 1, std::cout, ' ' );

    cout << "\nAnd num_rows is " << num_rows << '\n';
}
David W 131 Practically a Posting Shark
David W 131 Practically a Posting Shark

I might start off with a very simple bottom up re-design with planes coming into a queue and departing from the same queue in fifo order ...

with maybe something like ... ?

struct Plane
{
    int id;
    string from;
    string arrived;
    string to;
    string departed;
} ;

struct Gates
{
    int id;
} ;

then using STL queue containers

one for gates of in-coming flights
moving to 
next one in queue of boarding gates
moving to
next one in queue for gates of out-going flights

also ...
one for planes coming in and departing fifo order

Then when that is all working ... go from there ?
David W 131 Practically a Posting Shark

In C++, its best NOT to use C type strings.

Use C++ string instead.

The C++ string will size itself to be the right size to hold your string and can be as big as available memory for a C++ string

See:
http://www.cplusplus.com/reference/string/string/
and:
http://www.cplusplus.com/reference/string/string/max_size/

David W 131 Practically a Posting Shark

In C++, best NOT to use C type strings.

Use C++ string instead.

The C++ string will size itself to be the right size to hold your string and can be as big as available memory for a C++ string

See:
http://www.cplusplus.com/reference/string/string/
and:
http://www.cplusplus.com/reference/string/string/max_size/

David W 131 Practically a Posting Shark

I would start fresh and use a C++

typedef vector< vector < double > > Matrix;

then code something, beginning like the following,
to exploit the power built into C++ ...

void takeIn( Matrix& mat );
Matrix& operator += ( Matrix& a, const Matrix& b );
Matrix operator + ( const Matrix& a, const Matrix& b )
{
   Matrix tmp = a;
   return tmp +=  b;
}
// etc... as you need ... 
// make sure you define all the functions 
// before you call them //
David W 131 Practically a Posting Shark

Maybe you want this?

while(getline(infile,substance[index],','))
{
    // getline(infile,substance[index],','); // done above //
    infile >> molWeight[index];
}

It is hard to tell what you want without some sample data file.

Perhaps the following example of reading a csv data file might help?

// fileReadWriteStudent_csv.cpp //

#include <iostream>
#include <iomanip> // re. setw
#include <fstream>
#include <sstream> // re. stringstream objects //
#include <string>

using namespace std;


const char* FILE_IN  = "Students_in_csv.txt";
/*
1001,Joe Toe Smith,33
1002,Ann Fran Books,44
1003,Harry Larry Sanders,11
*/
const char* FILE_OUT = "Students_adjusted.txt";

const int ADJUST = 50;


struct Student
{
    int id;
    string name;
    int score;

    istream& takeIn( istream& is )
    {
        string line;
        getline(is, line);
        istringstream iss( line ); // form iss obj. from line //
        char comma;
        iss >> id >> comma;
        getline( iss, name, ',' );
        iss >> score;

        return is;
    }

    void print( ostream& os ) const
    {
        int score_adj = score + ADJUST;
        if( score_adj > 100 ) score_adj = 100;
        os << setw(4) << setfill('0') << id  << ' '
           << setfill('.') << left << setw(30) << name << ' '
           << setfill(' ') << right << setw(3) << score_adj << endl;
    }

} ;



int main()
{
    ifstream fin( FILE_IN );
    ofstream fout( FILE_OUT );
    if( fin && fout )
    {
        Student stud;
        while( stud.takeIn( fin ) )
        {
            // do any processing here that you wish on this 'word' ... for example
            // just print it to screen and to file, each 'word' on a new line …
David W 131 Practically a Posting Shark

Note the words 'local' ... and 'copy' (of pointer/address) ...

This is the crux of your problem here.

int a = 1, b = 2;
int* x = &a;
int* y = x; /* an alias (i.e. a copy) of x */
x = &b;
/* what is *y = ? now */
/* what is *x = ? now */

Compile and run ...

#include <stdio.h>

int main()
{
    int a = 1, b = 2;
    int* x = &a;
    int* y = x; /* an alias (i.e. a copy) of x */
    x = &b;

    /* what is *y = ? now */
    printf( "*y = %d ", *y );

    /* what is *x = ? now */
    printf( "*x = %d", *x );

    return 0;
}
David W 131 Practically a Posting Shark
#include <stdio.h>

/* Note: inside we do NOT change a or b ... 
     i.e. NO addresses get changed.
      We only change the dereferenced values. */
void swap( int* a, int* b ) /* a, b are 'local copies' ... */
{
    int tmp = *a; /* ok, address pointed to (i.e. &x is here dereferenced) */
    *a = *b; /* x is set to y */
    *b = tmp; /* y is set to tmp, i.e. original value held by x */
}

int main() /* simplified */
{
    int x = 5, y = 10;
    swap( &x, &y ); /* taking addresses */
    printf( "%d %d\n", x, y );
    return 0;
}
David W 131 Practically a Posting Shark

The example involves allocating (sometines changed new starting addresses) new enlarged memory blocks ... to hold a (dynamic) array of a growing number of elements (in the example, the elements are each dynamic C strings ... each string may be of any length). The program shows a way to easily manage all those (changing dynamic) memory needs.

The changes inside, for example, the push_back function, are reflected to the calling scope.

You do NOT reflect the address change inside the below function to the calling scope!

/* pointer_demo5.c */

#include <stdio.h>

int q = 10;


void fun( int* p ) /* Note this 'p' is an 'alias' (i.e. a copy in it's own memory, NOT the same memory as of 'p' outside in 'main' ) */
{
    *p = 15;
    p = &q;
    printf( "%d ",*p );
}



int main()
{
    int r = 30;
    int* p = &r;

    fun(p); /* the 1st thing done inside function 'fun' is to set 'r' in 'main' to 15 */
    /* the next thing done inside ... is to set p to point to global q of 10 */
    /* the next thing is to print q = 10 */


    /* what is (this) 'p' pointing to now ? ... ANSWER: it is *STILL* pointing to 'r' which NOW holds 15 */
    /* WHY? Only a copy inside was changed ... but the changes to that copy were NOT reflected back to the calling scope! */
    printf( "%d", *p );

    return 0;
}
David W 131 Practically a Posting Shark

So ... can you now 'see' what is happening and why ?

In each of ...

1) your original version (address change inside function NOT reflected in calling scope)

and ...

2) each of the 2 recent modified examples that return the address changes inside the function to the calling scope

Here is a practical example:
(Note: you need all 3 files in the same folder to compile the .c file... See the comments in the .h file to obtain link to download copy of file "readLine.h")

/* CvecOfString2.h */ /* this version 2016-02-18 */


#ifndef dwCvec_H
#define dwCvec_H

#include "readLine.h"
/*
    Note: file "readline.h" is available at this next link ...

    http://developers-heaven.net/forum/index.php/topic,2580.msg2864.html#msg2864
*/



/* re-set this starting num of rec's to minimize realloc's */
#ifndef VEC_CHUNK_SIZE
#define VEC_CHUNK_SIZE 8
#endif

typedef struct myCvecOfString
{
    char** ary;
    int size;
    int cap; /* capacity*/
} CvecOfString;


/* with these, an address is passed, so NO copy made and/or original updated */
void initCvecOfString( CvecOfString* ); /* sets ary to NULL and size, cap to 0 */
void push_backCvecOfString( CvecOfString*, char* );
void enlargeCvecOfString( CvecOfString* );
void reserveCvecOfString( CvecOfString*, int );
void clearCvecOfString( CvecOfString* );


void initCvecOfString( CvecOfString* cv )
{
    cv->ary = NULL;
    cv->size = cv->cap = 0;
}

void push_backCvecOfString( CvecOfString* cv, char* str )
{
    if( cv->size == cv->cap ) enlargeCvecOfString( cv );

    /* now add in new Rec ... */
    cv->ary[cv->size] = str; /* just copy pointer over */

    ++ cv->size;
}

/* new array …
David W 131 Practically a Posting Shark

r_address = func1( r_address );

Note in the above func1, we are (now) returning
(via the return statement in func1)
the changed address.

So then ...
after the returned new address value ...
the name 'r_address' is a 'mis-nomer'.

If you ran the code example ... and studied the output ... you would see this confirmed.

Below is a (simplified, but) related example ... do you 'see' how it is 'related'?
(Hint ... pointer keeps holding new addresses.)

/* pointer_demo4.c */


#include <stdio.h>



int main()
{
    const int ary[] = { 1, 2, 3 };
    const int ary_size = sizeof ary / sizeof *ary;

    const int* p = ary; /* p now holds address to first byte in ary ... */

    printf( "At START: p = \n%p \nand &ary[0] = \n%p\n", (void*) p, (void*) &ary[0] );

    int i;
    for( i = 0; i < ary_size; ++ i )
    {
        p = &ary[i]; /* p keeps getting new addresses ... */
        printf( "%d ", *p );
    }

    printf( "At END: p = \n%p \nand &ary[0] = \n%p\n", (void*) p, (void*) &ary[0] );


    return 0;
}
David W 131 Practically a Posting Shark

Ok ... let's suppose that you have had time by now to write and try out some 'debugging' type code ... as per my suggestion above ... but maybe ... you still fail to 'see' the answer to your problem ... and the solution to the very commom and related problem?

What follows is a demo of two ways to handle this (related) problem ... the problem of changing addresses inside functions ... addresses held by passed in pointers ... and the solution to the problem of how to reflect, in the calling scope, this address update.

/* pointer_demo.3 */

#include <stdio.h>


int q_global = 10;

int* func1( int* address_copy ); /* returns any updates to address inside fumction */

void func2( int** pp ); /* a pointer to a pointer */




int main()
{
    /* method 1 */
    int r = 30;
    int* r_address = &r;
    puts( "Method 1 ..." );

    printf( "q_global = %d, &q_global = %p\n", q_global, (void*) &q_global );
    printf( "r = %d, r_address = %p\n", r,  (void*)r_address );

    r_address = func1( r_address );

    printf( "%d\n", *r_address );
    printf( "r = %d, r_address = %p\n", r,  (void*)r_address );


    /* method 2 */
    puts( "\nMethod 2 ..." );
    r = 30;
    r_address = &r;

    printf( "q_global = %d, &q_global = %p\n", q_global, (void*) &q_global );
    printf( "r = %d, r_address = %p\n", r,  (void*)r_address );

    func2( &r_address ); /* NOTE: here we pass in the address of the pointer variable r_address */

    printf( "%d\n", *r_address );
    printf( …
David W 131 Practically a Posting Shark

Your problem is that you suppose you understand ... BUT you do NOT yet!
If you wish to learn about this issue ...
you must first admit that you presently hold some wrong idea(s) here.

I suggest that you write (your own debugging ) code ... to print out all the addresses ... and the values at EACH address ... at each step as the program logic flows.

Then (maybe?) you might see what is happening at each step.

David W 131 Practically a Posting Shark

You are missing completely the idea of 'address' as opposed to the 'value' stored at some address.

A pointer variable ONLY holds addresses!

At machine level ... you can go to an address and get the value there (direct addressing)

Or ... (for indirect addressing )
you can go to an address ... get the address stored there and then go to that address to get the value stored that final address.

David W 131 Practically a Posting Shark

NOT SO! --- > address_copy and r_address should both have the value 10.

address_copy holds an address ... A new address now ... the address of q_global.