SunScreenCert
asked on
Programming tips
There once was a wise servant who saved the life of a princess. The king promised to pay whatever the servant could dream up. Knowing that the king loved chess, the servant told the king he would like to have grains of wheat. One grain on the first square of a chess board. Two grains on the next. Four on the third, and so on.
There are 64 squares on a chessboard.
Write a program that shows how many grains were on each square and the total number of grains.
In other words, I want to type
java Grains
and see
square 1: 1 grain
square 2: 2 grains
square 3: 4 grains
square 4: 8 grains
etc.
public class Chess {
public static void main(String[] args) {
try{
int enteredNumber = Integer.parseInt(args[0]);
if( enteredNumber < 1 || enteredNumber > 64){
System.out.print("invalid numbers");
System.exit(0);
}
int numberOfSquares = (int)Math.pow(2, (enteredNumber - 1));
System.out.println(numberO fSquares);
}catch(NumberFormatExcepti on e){
e.printStackTrace();
}
}
}
There are 64 squares on a chessboard.
Write a program that shows how many grains were on each square and the total number of grains.
In other words, I want to type
java Grains
and see
square 1: 1 grain
square 2: 2 grains
square 3: 4 grains
square 4: 8 grains
etc.
public class Chess {
public static void main(String[] args) {
try{
int enteredNumber = Integer.parseInt(args[0]);
if( enteredNumber < 1 || enteredNumber > 64){
System.out.print("invalid numbers");
System.exit(0);
}
int numberOfSquares = (int)Math.pow(2, (enteredNumber - 1));
System.out.println(numberO
}catch(NumberFormatExcepti
e.printStackTrace();
}
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.