java String 2 Float

hellonoam

New member
java String 2 Float

אני מנסה להפוך STRING ל FLOAT אבל אני לא מצליח זה עובד רק כשהמספר שלם עבור 1.5 אני מקבל שגיעה.
try{ System.err.println(Float.valueOf(_angle.getText()).floatValue()); } catch(Exception e){ System.err.println("error"); }​
זה עובד רק כשהמספר שלם. אם המספר לא שלם או שהוא לא מספר אני מקבל שגיעה לא השגיעה שאני כתבתי(התוכנית לא מגיעה catch) מה אני צריך לשנות כדי להפוך STRING עם נקודה לFLOAT ואיך לתקן את ה CATCH שלי כדי שהוא יגיע לשם במקרה של טעות? תודה
 

melatonin

New member
קודם כל

"שגיאה", ולא "שגיעה" ולעניין: דבר ראשון, אם אתה רוצה לקבל float ולא Float, מומלץ להשתמש ב Float.parseFloat(String) במקום ב valueOf. לי זה עובד בסדר גמור על מספרים שלמים ולא שלמים (גם עם valueOf וגם עם parseFloat). ה try catch שלך נראה בסדר גמור, והוא עובד אצלי. איזה exception אתה מקבל?
 

voguemaster

New member
כמה דברים

דבר ראשון הדרך הנכונה לעשות את זה היא:
float f; try { f = Float.parseFloat(_angle.getText()); } catch(NumberFormatException nfe) { System.out.println("Error parsing float!"); } System.out.println("The angle is: "+f);​
אחרי זה, שים לב למה שאתה עשית בשורת ההדפסה שלך. לקחת את המחרוזת מתוך angle_, שמת אותה בתור פרמטר ל-valueOf. עד כאן זה בסדר. valueOf החזירה לך אובייקט חדש מסוג Float ועליו קראת ל-floatValue. פה יש עוד בעיה. הפונק' println מקבלת כארגומנט מחרוזת. אתה העברת לה טיפוס float פשוט בסופו של דבר. זה לא יעבוד לך לעולם בצורה הזו ומפתיע שבכלל זה התקמפל לך. אם אתה רוצה להדפיס מספר בלבד בלי שום טקסט לפניו הדרך היא:
System.out.println(""+num);​
 

melatonin

New member
מה? מאיפה הבאת את זה?

באמת. זה ג'אווה. נראה לך שהיו מספקים println רק ל String?
void println() Terminate the current line by writing the line separator string. void println(boolean x) Print a boolean and then terminate the line. void println(char x) Print a character and then terminate the line. void println(char[] x) Print an array of characters and then terminate the line. void println(double x) Print a double and then terminate the line. void println(float x) Print a float and then terminate the line. void println(int x) Print an integer and then terminate the line. void println(long x) Print a long and then terminate the line. void println(Object x) Print an Object and then terminate the line. void println(String x) Print a String and then terminate the line.​
 
למעלה