Java assignment 2

advertisement
Assignment description.
Language: Java.
Level: Basic.
Price: 50$
Programming Assignment.
a
where a and b are integers and b  0 .
b
Rational numbers can be added, subtracted, multiplied, and divided. You can find
absolute value of a rational number. You can convert a rational number to its floating
point equivalent. You can compare rational numbers. You can reduce a rational number
to its lowest terms.
A rational number is a number in the form of
Write a Java application that will be able to add, subtract, multiply, divide, compare,
convert to floating point, reduce to its lowest terms, and find absolute value for rational
numbers.
Your program should be written in Object Oriented Programming style. It should read a
file called input.txt that contains a pair of rational numbers to a line. (NOTE: that the
line may contain incorrect input). It should parse each line to retrieve two rational
numbers and perform operations on them. Rational numbers will be separated by “and”.
The results must be written to a file called results.txt.
After it has processed the entire file, it should close the input.txt and results.txt files.
From then on your program should accept two rational numbers from the user from
keyboard and output results of operations to console. The program should ask the user if
he/she wishes to terminate the program or not. If the user does not want to terminate the
program, the program should prompt the user for more numbers. You should document
your code. Your program should solve operations efficiently and be able to recover
from bad inputs. Use exception handling mechanism so as not to crash the program.
Here is an input.txt file that you should use for this project.
1234 / 5678
0 / 1
apple / 23
-346 / 74
-232 / 884
1.2 / 31
-5
0
2 / 3
-4 / 5
1
and
and
and
and
and
and
and
and
and
and
8765 / 4321
34 / 675
23 / x
54 / 32
-33 / 222
-1 / 4
1 / 2
3 / 4
0
5
and something
Solution.
RationalNumber.java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RationalNumber {
private final static Pattern p = Pattern.compile( "\\s*(-?\\d*)\\s*/?\\s*(-?\\d*)\\s*"
);
private long enumerator;
private long denominator;
public RationalNumber( long enumerator, long denominator ) {
this.enumerator = enumerator;
this.denominator = denominator;
reduceToLowestTerms();
}
public RationalNumber( String str ) {
Matcher m = p.matcher( str );
if ( !m.matches() )
throw new IllegalArgumentException( "Incorrect number format: "
+ str );
try {
enumerator = Integer.valueOf( m.group( 1 ) ).intValue();
denominator = m.group(2).trim().length() != 0 ? Integer.valueOf(
m.group( 2 ) ).intValue() : 1;
} catch( NumberFormatException e ) {
throw new IllegalArgumentException( "Incorrect number format: "
+ str );
}
reduceToLowestTerms();
}
public long getEnumerator() {
return enumerator;
}
public long getDenominator() {
return denominator;
}
public RationalNumber add( RationalNumber num ) {
long cm = getCommonMultiple( getDenominator(),
num.getDenominator() );
long e1 = getEnumerator() * ( cm / getDenominator() );
long e2 = num.getEnumerator() * ( cm / num.getDenominator() );
return new RationalNumber( e1 + e2, cm );
}
public RationalNumber sub( RationalNumber num ) {
return add( new RationalNumber( -1 * num.getEnumerator(),
num.getDenominator() ) );
}
public RationalNumber mul( RationalNumber num ) {
long newEnum = getEnumerator() * num.getEnumerator();
long newDenom = getDenominator() * num.getDenominator();
return new RationalNumber( newEnum, newDenom );
}
public RationalNumber div( RationalNumber num ) {
long newEnum = getEnumerator() * num.getDenominator();
long newDenom = getDenominator() * num.getEnumerator();
return new RationalNumber( newEnum, num.getDenominator() );
}
public long getCommonMultiple( long d1, long d2 ) {
return nok( d1, d2 );
}
public static long nok(long a,long b) {
return a*b/nod(a,b);
}
private static long nod(long a, long b) {
a = Math.abs( a );
b = Math.abs( b );
while (a*b!=0) {
if (a > b) {
a %= b;
} else {
b %= a;
}
}
return a+b;
}
public boolean isPositive() {
return ( getEnumerator() > 0 && getDenominator() > 0 ) ||
(getEnumerator() < 0 && getDenominator() < 0);
}
public float toFloat() {
return (float)getEnumerator() / getDenominator();
}
public RationalNumber toAbsoluteValue() {
return new RationalNumber( Math.abs(getEnumerator()),
Math.abs(getDenominator()) );
}
public void reduceToLowestTerms() {
int mcd = (int)nod( getEnumerator(), getDenominator() );
enumerator = getEnumerator() / mcd;
denominator = getDenominator() / mcd;
}
public String toString() {
if ( getEnumerator() == 0 )
return "0";
if ( getDenominator() == 1 )
return String.valueOf( getEnumerator() );
return getEnumerator() + "/" + getDenominator();
}
}
Start.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Start {
private final static Pattern p = Pattern.compile( "(.*) and (.*)" );
public static void main(String[] args) {
try {
System.out.println( "The data was read from input.txt file" );
List numbers = readNumbers();
writeResults( numbers );
System.out.println( "Result were saved into results.txt file" );
readFromUser();
} catch( Exception e ) {
System.out.println( "File error: " + e.getMessage() );
}
}
private static void readFromUser() throws Exception {
String line = null;
BufferedReader bf = new BufferedReader( new InputStreamReader(
System.in ) );
String str = "Please, enter the numbers (e1/d1 and e2/d2) >";
System.out.print( str );
while( ( line = bf.readLine() ).length() !=0 ) {
Matcher m = p.matcher( line );
if ( !m.matches() ) {
System.out.println( "Incorrect format - " + line );
}
try {
RationalNumber n1 = new RationalNumber( m.group( 1 ) );
RationalNumber n2 = new RationalNumber( m.group( 2 ) );
System.out.println( operationsReport( new
RationalNumber[]{n1, n2} ) );
} catch( Exception e ) {
System.out.println( e.getMessage() );
}
System.out.print( str );
}
}
private static void writeResults( List nums ) throws Exception {
BufferedWriter bw = new BufferedWriter( new FileWriter( "results.txt" )
);
for ( Iterator iter = nums.iterator(); iter.hasNext(); ) {
RationalNumber[] twoNum = (RationalNumber[])iter.next();
bw.write( operationsReport( twoNum ) );
bw.write( "\n" );
}
bw.close();
}
private static String operationsReport( RationalNumber[] nums ) {
RationalNumber n1 = nums[0];
RationalNumber n2 = nums[1];
StringBuffer buff = new StringBuffer();
buff.append( n1.toString() ).append( " and " ).append( n2.toString()
).append( "\n" );
buff.append( " -first:" ).append( "\n" );
buff.append( " -float value: " ).append( n1.toFloat() ).append( "\n" );
buff.append( " -absolute value: " ).append(
n1.toAbsoluteValue().toAbsoluteValue() ).append( "\n" );
buff.append( " -second:" ).append( "\n" );
buff.append( " -float value: " ).append( n2.toFloat() ).append( "\n" );
buff.append( " -absolute value: " ).append(
n2.toAbsoluteValue().toAbsoluteValue() ).append( "\n" );
buff.append( "
buff.append( "
buff.append( "
buff.append( "
-add: " ).append( n1.add( n2 ).toString() ).append( "\n" );
-sub: " ).append( n1.sub( n2 ).toString() ).append( "\n" );
-mul: " ).append( n1.mul( n2 ).toString() ).append( "\n" );
-div: " ).append( n1.div( n2 ).toString() ).append( "\n" );
return buff.toString();
}
private static List readNumbers() throws Exception {
List res = new LinkedList();
BufferedReader br = new BufferedReader( new FileReader( "input.txt" ) );
String line = null;
int i = 0;
while( (line = br.readLine() ) != null ) {
i++;
Matcher m = p.matcher( line );
if ( !m.matches() ) {
System.out.println( "Line " + i + ": Incorrect format - " +
line );
}
try {
RationalNumber n1 = new RationalNumber( m.group( 1 ) );
RationalNumber n2 = new RationalNumber( m.group( 2 ) );
res.add( new RationalNumber[]{n1, n2} );
} catch( Exception e ) {
System.out.println( "Line " + i + ": " + e.getMessage() );
}
}
br.close();
return res;
}
}
Download