i have the following code. i believe is in C++ and i want to translate it in to Java
i already done some myself, but i am new to Java and don't really understand C++
Thanks in advance
The program take in some numbers and find the first and last of the number 12. The program print 0 if the number 12 is not there .For example if the 4th data is the only 12, then the value 4 should be printed for the first and last occurrence.
C++ code
int main(){
int first, last, input;
first = last = 0;
cout %26lt;%26lt; "Enter a list of values, ^d to exit: ";
for (int i=0; cin %26gt;%26gt; input; i++){
if (input == 12 ){
if (first == 0){
first = last = i+1;
}
else last = i+1;
}
}
cout %26lt;%26lt; "First: " %26lt;%26lt; first %26lt;%26lt; endl;
cout %26lt;%26lt; "Last: " %26lt;%26lt; last %26lt;%26lt; endl;
return(0);
}
Java Code
int line;
int frist;
int last;
BufferedReader br;
br = new BufferedReader( new InputStreamReader( System.in ) ); line =Integer.parseInt(br.readLine()) ;
for ( int i=0; i%26lt;number.length; i++ )
if (line==12) {
if(first==0){
Translate some code from C++ to Java?
Buffered reader has to have a try / catch clause. The newer Scanner is much better.
================
import java.util.Scanner;
public class CompareCpluplus {
public static void main(String[] args) {
Scanner scanner =
new Scanner(System.in);
boolean run = true;
while (run) {
System.out.print("Enter a list of numbers, or n to exit: ");
String s = scanner.nextLine();
// check to see if they used commas
String delimiter = (s.indexOf(",") %26gt; -1 ? "," : " ");
String[] ss = s.split(delimiter);
int first = 0;
int last = 0;
for (int i = 0; i %26lt; ss.length; i++) {
if ( Integer.parseInt( ss[i] ) == 12 ||
Integer.parseInt( ss[i] ) == 0 ) {
// ?? weird, always true, first loop
first = last = i + 1;
}
else
last = i + 1;
}
System.out.println("first is: " + first);
System.out.println("last is: " + last);
System.out.println(
"==============");
System.out.print("Do another? ");
run = (!scanner.nextLine().
equalsIgnoreCase("n")) ?
true : false;
}
}
}
============
and, I had to break some lines of code, java doesn't care about white space, but Yahoo! Answers is funny about longWordsWithoutSpaces
Reply:Here's another version:
int f=0, l=0,i=0,val = 0;
BufferedReader br;
br = new BufferedReader( new InputStreamReader( System.in ) );
while (true) {
try {
val = Integer.parseInt(br.readLine());
++i;
if (val == 12) {
f = (f == 0)? i:f;
l = i;
}
} catch (NumberFormatException n) {
break;
}
catch (IOException io) {
break;
}
}
System.out.println("first = " + f + " and last = " + l);
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment