powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / Java [игнор отключен] [закрыт для гостей] / Хелп, плз: онлайновый sun-tutorial вываливается (J2SE build 1.6.0-b105)
8 сообщений из 8, страница 1 из 1
Хелп, плз: онлайновый sun-tutorial вываливается (J2SE build 1.6.0-b105)
    #34369141
J-неофит
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
hi all.

Скачал с java.sun.com сначала Java(TM) SE Runtime Environment (build 1.6.0-b105), а затем
отсюда вот: http://java.sun.com/docs/books/tutorial/uiswing/learn/examples/CelsiusConverter2.java
- простой пример конвертации температуры из шкалы Цельсия в шкалу Фаренгейта.
При запуске (что в эклипсе, что просто через javac) и кликании по кнопке "Convert" выдает исключение `NumberFormatException`.
Объясните, плз, чайнику, что не так. Заранее спасибо за ответы.

ЗЫ. Текст исключения:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "37,0"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1224)
at java.lang.Double.parseDouble(Double.java:510)
at CelsiusConverter2.actionPerformed(CelsiusConverter2.java:91)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6038)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3260)
at java.awt.Component.processEvent(Component.java:5803)
at java.awt.Container.processEvent(Container.java:2058)
at java.awt.Component.dispatchEventImpl(Component.java:4410)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
at java.awt.Container.dispatchEventImpl(Container.java:2102)
at java.awt.Window.dispatchEventImpl(Window.java:2429)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
...
Рейтинг: 0 / 0
Хелп, плз: онлайновый sun-tutorial вываливается (J2SE build 1.6.0-b105)
    #34370362
expp
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
J-неофит java.lang.NumberFormatException: For input string: "37,0"

я не понял, джейнеофиты читать не умеют?
...
Рейтинг: 0 / 0
Хелп, плз: онлайновый sun-tutorial вываливается (J2SE build 1.6.0-b105)
    #34375973
J-неофит
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
exppя не понял, джейнеофиты читать не умеют?
Читать на этом форуме умеют все, даже неофиты.
Только что Вы, уважаемый expp, предлагаете ? Лезть в исходник java.lang.NumberFormatException, чтобы там навести порядок в "... input string: "37,0" ?!
Я ж говорю: I'm CHAYNICK, прошу помощи разобраться в sun'овском примере, который НЕ работает.
...
Рейтинг: 0 / 0
Хелп, плз: онлайновый sun-tutorial вываливается (J2SE build 1.6.0-b105)
    #34375983
zalexaka
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Код: plaintext
tempCelsius =  new  JFormattedTextField( new  DecimalFormat("##0.0#"));
О каком по вашему разделителе целой и дробной частей говорит указанный формат?
Теперь вспоминайте какой разделитель использовали при вводе. А уж после глянув на
Код: plaintext
java.lang.NumberFormatException:  For  input string: "37,0"
делайте выводы за вас их никто делать не будет. Удачи.
...
Рейтинг: 0 / 0
Хелп, плз: онлайновый sun-tutorial вываливается (J2SE build 1.6.0-b105)
    #34376582
expp
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
J-неофит exppя не понял, джейнеофиты читать не умеют?
Читать на этом форуме умеют все, даже неофиты.
Только что Вы, уважаемый expp, предлагаете ? Лезть в исходник java.lang.NumberFormatException, чтобы там навести порядок в "... input string: "37,0" ?!
Я ж говорю: I'm CHAYNICK, прошу помощи разобраться в sun'овском примере, который НЕ работает.

прошу прощения ваше величесство, но я всего лишь пытался привлечь ваше внимание к третьему символу в строке "37,0". Не будете ли вы так любезны ввести точку в место запятой. К сожалению ещё не всё прогрессивное человечество использует этот единственно верный символ разделения целой и дробной частей чисел с плавающей точкой, есть ещё и некоторые отморозки которые надеются увидеть там (что бы вы думали?) точку!!! Обычно с подобные проблемы преодолевают секретарши и студенты в екселе. Кстати, перых с профессиональным праздником.
...
Рейтинг: 0 / 0
Хелп, плз: онлайновый sun-tutorial вываливается (J2SE build 1.6.0-b105)
    #34378050
J-неофит
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
exppпрошу прощения ваше величесство, но я всего лишь пытался привлечь ваше внимание к третьему символу в строке "37,0". Не будете ли вы так любезны ввести точку в место запятой
Прошу извинить меня за назойливость, всемилостевейший expp, но всё дело в том, что в ИСХОДНИКЕ (который Вы можете качнуть с http://java.sun.com/docs/books/tutorial/uiswing/learn/examples/CelsiusConverter2.java) этой ЗАПЯТОЙ между 37 и 0 ***НЕТ*** ! Там, в sun'овском примере, как раз ТОЧКА в качестве разделителя.

И я не полный идиот, чтобы не проверить сразу причину этой ошибки в настройках windows (Пуск/панель управления/языки и стандарты/разделитель в числах). Поменяв в этой настройке запятую на точку и перезапустив этот пример, получил ту же самую ошибку.
Более того, когда в поле ввода СПЕЦИАЛЬНО вводишь (при "штатной" настройке дес. разделителя = ",") вместо строки "37 , 0" строку "37 . 0", то компонент JFormattedTextField всё равно сам меняет эту точку на запятую и далее вываливается.
Чем язвить, expp, лучше проверьте пример на своей машине и объясните тому, кто хочет научиться, в чём он неправ. Не все родились на белый свет с таким знанием Явы, как у Вас, к сожалению.
На всякий случай, вот текст этого примера:

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
/**
 * CelsiusConverter2.java is a 1.4 application that demonstrates
 * the use of JButton, JTextFormattedField, and JLabel and 
 * requires the following file:
 *     images/convert.gif
 */

 import  java.awt.*;
 import  java.awt.event.*;
 import  javax.swing.*;
 import  javax.swing.text.NumberFormatter;
 import  java.text.ParseException;
 import  java.text.DecimalFormat;
 import  java.net.URL;

 public   class  CelsiusConverter2  implements  ActionListener {
    JFrame converterFrame;
    JPanel converterPanel;
    JFormattedTextField tempCelsius;
    JLabel celsiusLabel, fahrenheitLabel;
    JButton convertTemp;

     public  CelsiusConverter2() {
        //Create and set up the window.
        converterFrame =  new  JFrame("Convert Celsius to Fahrenheit");
        converterFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        converterFrame.setSize( new  Dimension( 120 ,  40 ));

        //Create and set up the panel.
        converterPanel =  new  JPanel( new  GridLayout( 2 ,  2 ));

        //Add the widgets.
        addWidgets();

        //Set the default button.
        converterFrame.getRootPane().setDefaultButton(convertTemp);

        //Add the panel to the window.
        converterFrame.getContentPane().add(converterPanel, BorderLayout.CENTER);

        //Display the window.
        converterFrame.pack();
        converterFrame.setVisible(true);
    }

    /**
     * Create and add the widgets.
     */
     private   void  addWidgets() {
        //Create the widgets.
        ImageIcon convertIcon = createImageIcon("images/convert.gif",
            "Convert temperature");

        //Create the format for the Celsius text field.
        tempCelsius =  new  JFormattedTextField( new  DecimalFormat("##0.0#"));
        tempCelsius.setFocusLostBehavior(JFormattedTextField.COMMIT_OR_REVERT);

        //Set and commit the default temperature.
         try  {
            tempCelsius.setText("37.0");
            tempCelsius.commitEdit();
        }  catch (ParseException e) {
            //Shouldn't get here unless the setText value doesn't agree
            //with the format set above.
            e.printStackTrace();
        }

        celsiusLabel =  new  JLabel("Celsius", SwingConstants.LEFT);
        convertTemp =  new  JButton(convertIcon);

        fahrenheitLabel =  new  JLabel("Fahrenheit", SwingConstants.LEFT);

        celsiusLabel.setBorder(BorderFactory.createEmptyBorder( 5 , 5 , 5 , 5 ));
        fahrenheitLabel.setBorder(BorderFactory.createEmptyBorder( 5 , 5 , 5 , 5 ));

        //Listen to events from the Convert button and
        //the tempCelsius text field.
        convertTemp.addActionListener( this );
        tempCelsius.addActionListener( this );

        //Add the widgets to the container.
        converterPanel.add(tempCelsius);
        converterPanel.add(celsiusLabel);
        converterPanel.add(convertTemp);
        converterPanel.add(fahrenheitLabel);
    }

     public   void  actionPerformed(ActionEvent event) {
        String eventName = event.getActionCommand();
        //Parse degrees Celsius as a double and convert to Fahrenheit.
         int  tempFahr = ( int )(( Double .parseDouble(tempCelsius.getText()))
                             *  1 . 8  +  32 );

        //Set fahrenheitLabel to the new value and set font color
        //based on the temperature.
         if  (tempFahr <=  32 ) {
            fahrenheitLabel.setText("<html><font Color=blue>" +
                        tempFahr + "° </font> Fahrenheit</html>");
        }  else   if  (tempFahr <=  80 ) {
            fahrenheitLabel.setText("<html><font Color=green>" +
                        tempFahr + "° </font> Fahrenheit</html>");
        }  else  {
            fahrenheitLabel.setText("<html><font Color=red>" +
                        tempFahr + "° </font> Fahrenheit</html>");
        }
    }

    /** Returns an ImageIcon, or null if the path was invalid. */
     protected   static  ImageIcon createImageIcon(String path,
                                               String description) {
        java.net.URL imgURL = CelsiusConverter2. class .getResource(path);
         if  (imgURL !=  null ) {
             return   new  ImageIcon(imgURL, description);
        }  else  {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Make sure we have nice window decorations.
        JFrame.setDefaultLookAndFeelDecorated(true);

        CelsiusConverter2 converter = new CelsiusConverter2();
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater( new  Runnable() {
             public   void  run() {
                createAndShowGUI();
            }
        });
    }
}


...
Рейтинг: 0 / 0
Хелп, плз: онлайновый sun-tutorial вываливается (J2SE build 1.6.0-b105)
    #34378370
A. Fig Lee
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
здесь:
Код: plaintext
1.
 int  tempFahr = ( int )(( Double .parseDouble(tempCelsius.getText()))
                             *  1 . 8  +  32 );

перед преобразованием я бы сначала напечатал че в tempCelcius,
убедившись, что там запятая, я бы при старте программы напечатал все java properties
если и там в сеттингс запятая, я бы проверил - рестартовал ли я окно после установки локал сеттингс
...
Рейтинг: 0 / 0
Хелп, плз: онлайновый sun-tutorial вываливается (J2SE build 1.6.0-b105)
    #34378415
J-неофит
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
2A. Fig Lee: Спасибо, попробую.
...
Рейтинг: 0 / 0
8 сообщений из 8, страница 1 из 1
Форумы / Java [игнор отключен] [закрыт для гостей] / Хелп, плз: онлайновый sun-tutorial вываливается (J2SE build 1.6.0-b105)
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]