Προς το περιεχόμενο

eisagogi int sa java


ligart

Προτεινόμενες αναρτήσεις

Δημοσ.

Nomizo iparxei pio eukolos tropos na to kaneis. Prepei na dimiourgiseis ena input stream kai na to kaneis link me to Standard Input.

p.x.

 

import java.io.*;

 

String inBuf;

DataInputStream inStream = new DataInputStream(System.in);

 

System.out.println("Dose Arithmo");

inBuf = inStream.readLine();

option = Integer.parseInt(inBuf);

 

Aplos prepei na kaneis casting sto String pou diavazeis kai na to kaneis Int. Me auto ton tropo mporis na diavaseis kai sti sinexeia oti allo thes, long, double, byte etc etc

Δημοσ.
Nomizo iparxei pio eukolos tropos na to kaneis. Prepei na dimiourgiseis ena input stream kai na to kaneis link me to Standard Input.

p.x.

 

import java.io.*;

 

String inBuf;

DataInputStream inStream = new DataInputStream(System.in);

 

System.out.println("Dose Arithmo");

inBuf = inStream.readLine();

option = Integer.parseInt(inBuf);

 

Aplos prepei na kaneis casting sto String pou diavazeis kai na to kaneis Int. Me auto ton tropo mporis na diavaseis kai sti sinexeia oti allo thes' date=' long, double, byte etc etc[/quote']

 

Δηλαδή ο παραπάνω τρόπος είναι πιο "εύκολος"; Μπαααα.

 

η χρήση της κλάσης java.util.Scanner είναι σαφώς πιο φιλική και "ασφαλής" (σε γλιτώνει από διάφορους ελέγχους, typecast και χειρίζεται η ίδια τα όποια λάθη).

 

Το πρόβλημα είναι πως πρόκειται για νέο αντικείμενο της διανομής J2SE 5.0 και άρα δεν είναι συμβατό με παλαιότερες εκδόσεις της Java.

 

Όσο για την παραπάνω υλοποίηση θα πρότεινα κάτι τέτοιο:

>
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int option = 0;
try { option = Integer.parseInt(in.readLine()); }
catch (IOException e) { System.out.println("Failed to read from Input"); }
catch (NumberFormatException e) { System.out.println("You did not type a number!"); }

εκτός από τα exception που καλό είναι να τα χειρίζεσαι μόνος σου, αν τα περιμένεις να συμβούν, ο InputStreamReader κωδικοποιεί αυτά που διαβάζει από την είσοδο με βάση το default Charset του συστήματος που τρέχει.

Αρχειοθετημένο

Αυτό το θέμα έχει αρχειοθετηθεί και είναι κλειστό για περαιτέρω απαντήσεις.

  • Δημιουργία νέου...