Anyone know what this code is doing?
In an exercise in my book, I've come across an example that doesn't go too far into explaining a section of the code. I don't know what it's called so I'm having a tough time finding it. Here's a clip of it, what I've highlighted in bold and underlined is what's got me stumped...
Code :
public class Sales2
{
public static void main( String[] args )
{
Scanner input = new Scanner( System.in );
// sales array holds data on number of each product sold
// by each salesperson
double[][] sales = new double[ 5 ][ 4 ];
System.out.print( "Enter salesperson number (-1 to end): " );
int person = input.nextInt();
while ( person != -1 )
{
System.out.print( "Enter product number: " ); //
int product = input.nextInt();
System.out.print( "Enter sales amount: " );
double amount = input.nextDouble();
// error-check the input
if ( person >= 1 && person < 5 &&
product >= 1 && product < 6 && amount >= 0 )
[B][U][SIZE="3"] sales[ product - 1 ][ person - 1 ] += amount;[/SIZE][/U][/B]
else
System.out.println( "Invalid input!" );
System.out.print( "Enter salesperson number (-1 to end): " );
person = input.nextInt();
}
Any idea what "sales[ product - 1 ][ person - 1 ] += amount;" is doing? Because I don't, I'm stumped. Anyone know what it is called at the very least? :confused: [-O<
Re: Anyone know what this code is doing?
Wow, I'm dumb, Java = Zero based, so sales[ product -1] [ person -1 ] simply sets the value entered to the correct element in the array... Right?
I think that's right at least.
Re: Anyone know what this code is doing?
You're right, of course. The people and products are indexed from 1 to 4, and the products 1 to 5, so subtracting by 1 allows these indices to be used for the arrays which are indexed from 0 to 3 and from 0 to 4, respectively.