Implicit Type-Casting for
Method's Parameters
A method that takes a double parameter can accept any
numeric primitive type, such as int or float. This is because implicit
type-casting is carried out. However, a method that take a int parameter cannot
accept a double value. This is because the implicit type-casting is always a
widening conversion which prevents loss of precision. An explicit type-cast is
required for narrowing conversion. Read "Type-Casting"
on the conversion rules.
Command-Line Arguments
Java's main(String[] args) method takes an argument:
String[] args, i.e., a String array named args. This is known as
"command-line arguments", which corresponds to the augments provided
by the user when the java program is invoked. For example, a Java program
called Arithmetic could be invoked with additional command-line arguments as
follows (in a "cmd" shell):
java Arithmetic 12 3456 +
Each argument, i.e., "12", "3456" and
"+", is a String. Java runtime packs all the arguments into a String
array and passes into the main() method as args. For this example, args has the
following properties:
args = {"12", "3456",
"+"} // "args" is a
String array
args.length = 3
// length of the array args
args[0] = "12" // Each element of the array is
a String
args[1] = "3456"
args[2] = "+"
args[0].length() = 2
// length of the String
args[1].length() = 4
args[2].length() = 1
Example: The program Arithmetic reads three parameters form
the command-line, two integers and an arithmetic operator ('+', '-', '*', or
'/'), and performs the arithmetic operation accordingly. For example,
java Arithmetic 3 2 +
3+2=5
java Arithmetic 3 2 -
3-2=1
java Arithmetic 3 2 /
3/2=1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
public class Arithmetic {
public static
void main (String[] args) {
int operand1,
operand2;
char
theOperator;
operand1 =
Integer.parseInt(args[0]); // Convert
String to int
operand2 =
Integer.parseInt(args[1]);
theOperator =
args[2].charAt(0); // Consider
only 1st character
System.out.print(args[0] + args[2] + args[1] + "=");
switch(theOperator) {
case ('+'):
System.out.println(operand1 + operand2);
break;
case ('-'):
System.out.println(operand1 - operand2); break;
case ('*'):
System.out.println(operand1 * operand2); break;
case ('/'):
System.out.println(operand1 / operand2); break;
default:
System.out.printf("%nError: Invalid operator!");
}
}
}
|
Bin2Dec
Convert a binary string into its equivalent decimal
number.
Version 1:
/*
* Prompt user for a
binary string, and convert into its equivalent decimal number.
*/
import java.util.Scanner;
public class Bin2Dec {
public static void main(String[] args) {
String binStr; // The input binary string
int binStrLen; // The length of binStr
int dec = 0; // The decimal equivalent, accumulate from 0
// Read input
Scanner in = new Scanner(System.in);
System.out.print("Enter a binary
string: ");
binStr = in.next();
binStrLen = binStr.length();
// Process char by char from the right
(i.e. Least-significant bit)
for (int exp = 0; exp < binStrLen ;
++exp) {
int charPos = binStrLen - 1 -
exp; // charAt(pos)
char binChar = binStr.charAt(charPos);
// 3 cases: '1' (add to dec), '0' (do
nothing), other (error)
if (binChar == '1') {
dec += (int)Math.pow(2, exp); // cast the double result back to int
} else if (binChar != '0') {
System.out.println("Error:
Invalid binary string \"" + binStr + "\"");
System.exit(1); // quit
}
}
// Print result
System.out.println("The equivalent decimal for \"" +
binStr + "\" is " + dec);
in.close();
}
}
binStr : 1
0 1 1 1 0 0 1
charAt(pos) : 0
1 2 3 4 5 6 7 (pos counts from the left)
Math.pow(2, exp) : 7
6 5 4 3 2 1 0 (exp counts from the
right)
binStr.length() = 8
pos + exp = binStr.length() - 1
Version 2:
/*
* Prompt user for a
binary string, and convert into its equivalent decimal number.
* Validate the input
string.
* Repeat the program,
until user chooses to quit.
* Allow blank in the
binary string, e.g., "0100 1000".
*/
import java.util.Scanner;
public class Bin2DecIteractive {
public static void main(String[] args) {
String inStr; // The input binary string
Scanner in = new Scanner(System.in);
boolean done = false; // boolean flag for controlling the loop
while (!done) {
// Prompt for the input string
System.out.print("Enter a binary
string or 'q' to quit: ");
inStr = in.nextLine(); // read entire line including blanks
if (inStr.equals("q")) {
System.out.println("Bye!");
done = true;
} else if (!isValidBinStr(inStr)) {
System.out.println("Error:
Invalid binary string: \"" + inStr + "\", try
again.");
} else {
System.out.println("The
equivalent decimal number for \"" + inStr + "\" is " +
bin2Dec(inStr));
}
}
in.close();
}
// Return true if the given string contains
only binary numbers and blanks.
public static boolean isValidBinStr(String
binStr) {
for (int i = 0; i < binStr.length();
++i) {
char binChar = binStr.charAt(i);
if (binChar != '0' && binChar
!= '1' && binChar != ' ') {
return false; // break on first invalid char
}
}
return true;
}
// Return the equivalent decimal number of
the given binary string.
// Blanks are allowed in the binStr, e.g.,
"0010 1000".
// Assume that the input contains '0', '1'
or ' '.
public static int bin2Dec(String binStr) {
int binStrLen = binStr.length(); // The length of binStr
int dec = 0; // Equivalent decimal number, accumulating
from 0
//
We need to process from the right (i.e. Least-significant bit)
for (int charPos = binStrLen - 1, exp =
0; charPos >= 0; --charPos) {
char binChar = binStr.charAt(charPos);
// 3 cases: '1' (add to dec, ++exp),
'0' (++exp), ' ' (do nothing)
if (binChar == '1') {
dec += (int)Math.pow(2, exp);
++exp;
} else if (binChar == '0') {
++exp;
} // else for ' ' (do nothing)
}
return dec;
}
}
EG 2: Hex2Dec
Convert a hexadecimal string to its decimal equivalence.
/*
* Prompt user for the
hexadecimal string, and convert to its equivalent decimal number
*/
import java.util.Scanner;
public class Hex2Dec {
public static void main(String[] args) {
String hexStr; // The input hexadecimal String
int hexStrLen; // The length of hexStr
int dec = 0; // The decimal equivalent, accumulating
from 0
// Read input
Scanner in = new Scanner(System.in);
System.out.print("Enter a Hexadecimal
string: ");
hexStr = in.next();
hexStrLen = hexStr.length();
// Process char by char from the right
(least-significant digit)
for (int exp = 0; exp < hexStrLen;
++exp) {
int charPos = hexStrLen - 1 - exp;
char hexChar = hexStr.charAt(charPos);
int factor = (int)Math.pow(16, exp);
// 23 cases: '0'-'9', 'a'-'f',
'A'-'F', other (error)
if (hexChar >= '1' &&
hexChar <= '9') {
dec += (hexChar - '0') * factor;
} else if (hexChar >= 'a'
&& hexChar <= 'f') {
dec += (hexChar - 'a' + 10) *
factor;
} else if (hexChar >= 'A'
&& hexChar <= 'F') {
dec += (hexChar - 'A' + 10) *
factor;
} else {
System.out.println("Error: Invalid
hex string \"" + hexStr + "\"");
System.exit(1);
}
}
System.out.println("The equivalent
decimal for \"" + hexStr + "\" is " + dec);
in.close();
}
}
You may use in.next().toLowercase() to reduce the number of
cases. But that modifies the input string.
EG 3: Dec2Hex
Convert a decimal number to its hexadecimal equivalence.
/*
* Prompt user for an
int, and convert to its equivalent hexadecimal number.
*/
import java.util.Scanner;
public class Dec2Hex {
public static void main(String[] args) {
int dec; // The input decimal number
String hexStr = ""; // The equivalent hex String, accumulating
from empty String
int radix = 16; // Hex radix
char[] hexChar = {'0','1','2','3','4','5','6','7','8','9',
'A','B','C','D','E','F'}; // Use this array as lookup table
// Read input
Scanner in = new Scanner(System.in);
System.out.print("Enter a decimal
number: ");
dec = in.nextInt();
//
Repeated division and get the remainder
while (dec > 0) {
int hexDigit = dec % radix;
hexStr = hexChar[hexDigit] +
hexStr; // append in front of the hex
string
dec = dec / radix;
}
System.out.println("The equivalent
hexadecimal number is " + hexStr);
in.close();
}
}
EG 4: Hex2Bin
Convert a hexadecimal number to its binary equivalence.
/*
* Prompt user for a
hexadecimal string, and convert to its binary equivalence.
*/
import java.util.Scanner;
public class Hex2Bin {
public static void main(String[] args) {
String hexStr; // The input hexadecimal String
int hexStrLen; // The length of hexStr
String binStr =""; // The
equivalent binary String, accumulating from empty String
// Lookup table for the binary string
corresponding to Hex digit '0' (index 0) to 'F' (index 15)
String[] binStrs
=
{"0000","0001","0010","0011","0100","0101","0110","0111",
"1000","1001","1010","1011","1100","1101","1110","1111"};
// Read input
Scanner in = new Scanner(System.in);
System.out.print("Enter a
Hexadecimal string: ");
hexStr = in.next();
hexStrLen = hexStr.length();
// Process the string from the left
for (int pos = 0; pos < hexStrLen;
++pos) {
char hexChar = hexStr.charAt(pos);
if (hexChar >= '0' &&
hexChar <= '9') {
binStr +=
binStrs[hexChar-'0']; // index into the
binStrs array
} else if (hexChar >= 'a'
&& hexChar <= 'f') {
binStr += binStrs[hexChar-'a'+10];
} else if (hexChar >= 'A'
&& hexChar <= 'F') {
binStr += binStrs[hexChar-'A'+10];
} else {
System.err.println("Error:
Invalid Hex string \"" + hexStr + "\"");
System.exit(1); // quit
}
}
System.out.println("The equivalent
binary for \"" + hexStr + "\" is \"" + binStr +
"\"");
in.close();
}
}
EG 5: Guess A Number
Guess a number between 0 and 99.
import java.util.Scanner;
public class NumberGuess {
public static void main(String[] args) {
int secretNumber; // Secret number to be guessed
int numberIn; // The guessed number entered
int trialNumber = 0; // Number of trials so far
boolean done = false; // boolean flag for
loop control
// Set up the secret number
// Math.random() generates a double in
[0.0, 1.0)
secretNumber = (int)(Math.random()*100);
Scanner in = new Scanner(System.in);
while (!done) {
++trialNumber;
System.out.print("Enter your
guess (between 0 and 99): ");
numberIn = in.nextInt();
if (numberIn == secretNumber) {
System.out.println("Congratulation");
done = true;
} else if (numberIn < secretNumber) {
System.out.println("Try
higher");
} else {
System.out.println("Try
lower");
}
}
System.out.println("You got in
" + trialNumber +" trials");
in.close();
}
}
No comments:
Post a Comment
Please write your view and suggestion....