110 likes | 116 Views
CS1020 Lab 0 Discussion. Probrem 1: HelloWorld. Given 2 bits, determine the result of the given binary operation (AND or OR). Reading inputs: Reading from standard input:. Scanner sc = new Scanner( System.in );. Type 1: read N operations. N = sc.nextInt ();
E N D
Probrem 1: HelloWorld • Given 2 bits, determine the result of the given binary operation (AND or OR). • Reading inputs: • Reading from standard input: Scanner sc = new Scanner(System.in); • Type 1: read N operations • N = sc.nextInt(); • for (inti = 0; i < N; i++) { • operator = sc.next(); • firstBit = sc.nextInt(); • secondBit = sc.nextInt(); • // process the result accordingly • } Problem 1: HelloWorld
Type 2: read until special character ‘0’ while (true) { operator = sc.next(); if (operator.equals(specialCharacter)) break; bit1 = sc.nextInt(); bit2 = sc.nextInt(); // process the result accordingly} • Type 3: read until end of file while (sc.hasNext()) { operator = sc.next(); bit1 = sc.nextInt(); bit2 = sc.nextInt(); // process the result accordingly } Problem 1: HelloWorld
Problem 2: Palindrome • A string S[0…n-1] is palindrome iff • S[0] = S[n-1], S[1] = S[n-2], S[2] = S[n-3], … • i.e. S[i]=S[n-1-i] for every i.
for (int i = 0; i < len; i++) { if (s.charAt(i) != t.charAt(len - i - 1)) { palindrome = false; break; } } Alternatively, just reverse the second string and use the equals() method
Problem 3: Compare • Use compareTo() method (can be used for objects in Java). • When comparing two strings, a and b: intcomparisonResult = a.compareTo(b); The method returns: • 0 if they are lexicographically same • >= 1 if a is lexicographically ‘larger’ than b • <= -1 if a is lexicographically ‘smaller’ than b
Comparing Outputs • Suppose your java classname is Test, the input filename is “test.in” and the correct output filename is “test.out” • Run your program and store your program’s output in “test.tmp” • java Test < test.in > test.tmp • Compare test.out and test.tmp. • diff test.tmptest.out • If diffdoesn’t produce any output, then “test.tmp” and “test.out” are exactly the same (your program produces the correct output)
Comparing Outputs (8 times) • java Test < test1.in > test1.tmp • diff test1.tmp test1.out • java Test < test2.in > test2.tmp • diff test2.tmp test2.out • java Test < test3.in > test3.tmp • diff test3.tmp test3.out • java Test < test4.in > test4.tmp • diff test4.tmp test4.out • ... ... ... ... ... ...
Comparing Outputs (8 times)Faster wayusing a loop for i in {1 .. 8} do java Test < test$i.in > test$i.tmp diff test$i.tmptest$i.out done //YEAY