Reading inputs Reading from standard input Probrem 1 HelloWorld Scanner sc new Scanner Systemin Type 1 read N operations N scnextInt for int i 0 i lt N ID: 778526
Download The PPT/PDF document "CS1020 Lab 0 Discussion Given 2 bits, de..." is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
CS1020
Lab 0 Discussion
Slide2Given 2 bits, determine the result of the given binary operation (AND or OR).
Reading inputs:Reading from standard input:
Probrem 1: HelloWorld
Scanner sc = new Scanner(System.in);
Type 1: read N operations
N = sc.nextInt();for (int i = 0; i < N; i++) { operator = sc.next(); firstBit = sc.nextInt(); secondBit = sc.nextInt(); // process the result accordingly}
2
Problem 1:
HelloWorld
Slide3Type 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 filewhile (sc.hasNext()) { operator = sc.next(); bit1 = sc.nextInt(); bit2 = sc.nextInt
(); // process the result accordingly
}
3
Problem 1:
HelloWorld
Slide4A string S[0…n-1] is palindrome
iffS[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.Problem 2: Palindrome
Slide5for (
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
Slide6Use
compareTo( ) method (can be used for objects in Java).
When comparing two strings, a and b:int
comparisonResult = 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
Problem 3: Compare
Slide7ADDITIONAL SLIDES
Slide8Comparing Outputs
8
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.tmpCompare test.out and test.tmp. diff test.tmp test.outIf diff doesn’t produce any output, then “test.tmp
” and “
test.out
”
are
exactly the same (your program
produces the
correct output)
Slide9Comparing Outputs (8 times)
9
java Test < test1.
in > test1.tmpdiff test1.tmp test1.out
java Test < test2.in > test2.tmp
diff test2.tmp test2.outjava Test < test3.in > test3.tmpdiff test3.tmp test3.outjava Test < test4.in > test4.tmpdiff test4.tmp test4.out... ... ...
...
..
.
...
Slide10Comparing Outputs (8 times)
Faster way using a loop10
for
i in {1 .. 8}do
java Test < test$i.in > test$i.tmp
diff test$i.tmp test$i.outdone//YEAY
Slide11END OF FILE