Форум программистов, компьютерный форум, киберфорум
Java SE (J2SE)
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.67/3: Рейтинг темы: голосов - 3, средняя оценка - 4.67
1 / 1 / 3
Регистрация: 27.12.2012
Сообщений: 192

Запросы

02.12.2015, 12:44. Показов 583. Ответов 1
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Подскажите почему на операцию ">" выдает null вместо правильного варианта?
Java
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
public String[] searchInstrument2(String del, String bNum)
        { // данные возвращаются массивом
            int counter = 0; // счетчик
            boolean isSearch = false;
            
            for(MusicInstrument aMusicInstrument : musicInstr) // aMusicInstrument - перебор всего массива
            {
                if (del.equals(">")) {
                if (aMusicInstrument.getAntiquarian().intValue() > Integer.parseInt(bNum))
                {
                    counter++;
                    isSearch = true;
                }
              } else if (del.equals("<"))
                {
                    if(aMusicInstrument.getAntiquarian() < Integer.parseInt(bNum))
                    {
                        System.out.println(aMusicInstrument.getInfo());
                        isSearch = true;
                    }
                }
            }
            String[] result = new String[counter];
            int i = 0;
            for(MusicInstrument aMusicInstrument : musicInstr)
            {
                if (aMusicInstrument.getAntiquarian().intValue() > Integer.parseInt(bNum) && aMusicInstrument.getAntiquarian().intValue() < Integer.parseInt(bNum))
                {
                    result[i] = aMusicInstrument.getInfo();
                    i++;
                }
            }
            return result;
        }
Полный код программы
Кликните здесь для просмотра всего текста
Java
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
public class Work implements search 
{       
        MusicInstrument musicInstr[] = new MusicInstrument[9];
        private MusicInstrument aMusicInstrument;
        public Work()
        {
            //this.musicInstr = new MusicInstrument[9];
            musicInstr[0] = new MusicInstrument("CrystalGrand", 2008, true, 3220000.0, /*80,*/ MusicInstrument.Instrument.Keyboard, "7");
            musicInstr[1] = new MusicInstrument("Клавесин", 1679, false, 390550.0, /*40,*/ MusicInstrument.Instrument.Keyboard, "336");
            musicInstr[2] = new MusicInstrument("Кларнет", 1968, true, 25000.0, /*55,*/ MusicInstrument.Instrument.Wind, "55");
            musicInstr[3] = new MusicInstrument("Гитара", 1964, true, 122500.0, /*90,*/ MusicInstrument.Instrument.String, "51");
            musicInstr[4] = new MusicInstrument("Виолончель",1711, true, 20000000.0, /*100,*/ MusicInstrument.Instrument.String, "304");
            musicInstr[5] = new MusicInstrument("Саксофон", 1941, false, 261750.0, /*35,*/ MusicInstrument.Instrument.Reed, "74");
            musicInstr[6] = new MusicInstrument("Барабанная", 1968, false, 252487.0, /*99,*/ MusicInstrument.Instrument.Drums, "55");
            musicInstr[7] = new MusicInstrument("Труба", 1963, false, 31000.0, /*58,*/ MusicInstrument.Instrument.Reed, "52");
            musicInstr[8] = new MusicInstrument("Электрогитара", 1950, false,2800000.0, /*100,*/ MusicInstrument.Instrument.String, "65");
        }
        
        /*@Deprecated public void createInstrument()
        {
            
        }*/
        
        public void searchInstrument1(int iYearOfCreation, String iPrice)
        {
            boolean isSearch = false;
            for (MusicInstrument aMusicInstrument : musicInstr) {
                    if (aMusicInstrument.getYearOfCreation() > iYearOfCreation && aMusicInstrument.getName().equals(iPrice)) {
                        System.out.println(aMusicInstrument.getInfo());
                        isSearch = true;
                    }
                } if (isSearch != true) System.out.println("Попробуйте заново.");
            }
        
        public void searchInstrument1(int iYearOfCreation, boolean isWorking)
        {
            try
            {
                boolean isSearch = false;
                for (MusicInstrument aMusicInstrument : musicInstr) {
                    if (aMusicInstrument.getYearOfCreation() > iYearOfCreation && aMusicInstrument.getWorking() == isWorking) {
                        System.out.println(aMusicInstrument.getInfo());
                        isSearch = true;
                    }
                }
                if (isSearch != true)
                {
                    throw new NoSuchElementException();
                }
            }
            catch(NoSuchElementException nsex)
            {
                System.out.println("Сгенерировано исключение: " + nsex.toString() + " не найден предмет. Попробуйте заново.");
            }
        }
        
        public String searchName(String iPrice)
        {
            for (MusicInstrument aMusicInstrument : musicInstr)
            {
                try
                {
                    if(aMusicInstrument.getName().equals(iPrice))
                    {
                        return "В наличии";
                    }
                }
                catch (Exception t)
                {
                    return t.toString();
                }
                
            }
            return "Нет в наличии";
        }
        
        public String[] searchInstrument2(String del, String bNum)
        { // данные возвращаются массивом
            int counter = 0; // счетчик
            boolean isSearch = false;
            
            for(MusicInstrument aMusicInstrument : musicInstr) // aMusicInstrument - перебор всего массива
            {
                if (del.equals(">")) {
                if (aMusicInstrument.getAntiquarian().intValue() > Integer.parseInt(bNum))
                {
                    counter++;
                    isSearch = true;
                }
              } else if (del.equals("<"))
                {
                    if(aMusicInstrument.getAntiquarian() < Integer.parseInt(bNum))
                    {
                        System.out.println(aMusicInstrument.getInfo());
                        isSearch = true;
                    }
                }
            }
            String[] result = new String[counter];
            int i = 0;
            for(MusicInstrument aMusicInstrument : musicInstr)
            {
                if (aMusicInstrument.getAntiquarian().intValue() > Integer.parseInt(bNum) && aMusicInstrument.getAntiquarian().intValue() < Integer.parseInt(bNum))
                {
                    result[i] = aMusicInstrument.getInfo();
                    i++;
                }
            }
            return result;
        }
        public void returnInstrument1()
        {
            for(MusicInstrument aMusicInstrument : this.musicInstr) {
                System.out.println(aMusicInstrument.getInfo());
            }
        }
        
        public void returnInstrument1(String num)
        {
            System.out.println(this.musicInstr[Integer.parseInt(num)].getInfo());
        }
        
        public void exit()
        {
            
        }
}
 
class MusicInstrument 
{       
        private String instrumentName;  // название инструмента
        private int instrumentYearOfCreation;   // год выпуска
        private boolean instrumentWorking; // пригодность
        private double instrumentPrice; // цена инструмента
        private Integer instrumentAntiquarian;
                
        public enum Instrument
        {
            Keyboard, String, Wind, Reed, Drums
        }
        
        public Instrument instrument;
 
    public MusicInstrument(String instrumentName, int instrumentYearOfCreation, boolean instrumentWorking, double instrumentPrice, /*Integer Resonator,*/ Instrument Mus, String antiquariat) 
    {
        this.instrumentYearOfCreation = instrumentYearOfCreation;
        this.instrumentName = instrumentName;
        this.instrumentWorking = instrumentWorking;
        this.instrumentPrice = instrumentPrice;
        //this.instrumentResonator = Resonator;
        
        this.instrument = Mus;
        
        int temp = Integer.parseInt(antiquariat);
        this.instrumentAntiquarian = temp;
    }
    
    public int getYearOfCreation() 
    {
        return this.instrumentYearOfCreation;
    }
    
    public String getName() 
    {
        return this.instrumentName;
    }
    
    public String getInfo()
    {
        return  " Название: " + this.instrumentName + " Год: " + this.instrumentYearOfCreation + " Работоспособность: " + this.instrumentWorking + " Цена "
                + this.instrumentPrice;
    }
    
    public boolean getWorking() 
    {
        return this.instrumentWorking;
    }
    
    public Integer getAntiquarian() 
    {
        return this.instrumentAntiquarian;
    }
}
Миниатюры
Запросы  
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
02.12.2015, 12:44
Ответы с готовыми решениями:

Запросы сумм
Задача 1. Запросы сумм Ограничение по времени: 2 секунды Ограничение по памяти: 64 мегабайта В первой строке файла содержатся...

Как делать запросы в файл excel из Java?
Здравствуйте, есть xls файл: нужно сделать так чтобы выводились в консоли фио тех, у кого стаж больше n,я не работал с excel + java,...

Запросы
Ребята помогите правильно сформировать запрос!!! Если пишу запрос без использования переменных то все ОК, а с их использования...

1
1 / 1 / 3
Регистрация: 27.12.2012
Сообщений: 192
06.12.2015, 18:52  [ТС]
Подскажите, как в этом методе использовать endsWith ?
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public String searchFamily (String fam){
            String c = " ";
            boolean isSearch = false;
            for(int s=0; s<musicInstr.length; s++) {
                String m = String.valueOf(musicInstr[s].getInstrument());
                if (m.equalsIgnoreCase(fam)){
                    if(isSearch == false)
                    {
                        c += musicInstr[s].getInfo();
                        isSearch = true;
                    }
                    else c += "\n" + musicInstr[s].getInfo();
                }
            }
            if (isSearch != true) {return "Ничего не найдено";}
            else return c;
        }
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
06.12.2015, 18:52
Помогаю со студенческими работами здесь

Запросы к бд
Добрый день! public class Main { private final Connection connection; private PreparedStatement getStatement; ...

JSF и GET - запросы
Здравствуйте! Меня интересует вопрос: поддерживает ли технология JSF get-запросы? Если да, то как на них переключиться (как я понял...

Sql запросы
public class TrainGateway { private final static String TABLE_NAME = &quot;Train&quot;; private final static String ID = &quot;id&quot;; ...

http запросы
В чем разница http запросов get,put,post и т.д. А конкретно меня интересуют аннотации в spring т.е RequestMapping,GetMapping,PostMapping...

HQL - запросы
Здравствуйте помогите пожалуйста разобраться с HQL - я хочу сделать выборку со всей таблицы по определённому полю. Допустим есть таблица...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Новые блоги и статьи
Отправка уведомления на почту при изменении наименования справочника
Maks 24.03.2026
Программная отправка письма электронной почты на примере изменения наименования типового справочника "Склады" в конфигурации БП3. Перед реализацией необходимо выполнить настройку системной учетной. . .
модель ЗдравоСохранения 5. Меньше увольнений- больше дохода!
anaschu 24.03.2026
Теперь система здравосохранения уменьшает количество увольнений. 9TO2GP2bpX4 a42b81fb172ffc12ca589c7898261ccb/ https:/ / rutube. ru/ video/ a42b81fb172ffc12ca589c7898261ccb/ Слева синяя линия -. . .
Midnight Chicago Blues
kumehtar 24.03.2026
Такой Midnight Chicago Blues, знаешь?. . Когда вечерние улицы становятся ночными, а ты не можешь уснуть. Ты идёшь в любимый старый бар, и бармен наливает тебе виски. Ты смотришь на пролетающие. . .
SDL3 для Desktop (MinGW): Вывод текста со шрифтом TTF с помощью библиотеки SDL3_ttf на Си и C++
8Observer8 24.03.2026
Содержание блога Финальные проекты на Си и на C++: finish-text-sdl3-c. zip finish-text-sdl3-cpp. zip
Жизнь в неопределённости
kumehtar 23.03.2026
Жизнь — это постоянное существование в неопределённости. Например, даже если у тебя есть список дел, невозможно дойти до точки, где всё окончательно завершено и больше ничего не осталось. В принципе,. . .
Модель здравоСохранения: работники работают быстрее после её введения.
anaschu 23.03.2026
geJalZw1fLo Корпорация до введения программа здравоохранения имела много невыполненных работниками заданий, после введения программы количество заданий выросло. Но на выплатах по больничным это. . .
Контроль уникальности заводского номера
Maks 23.03.2026
Алгоритм контроля уникальности заводского (или серийного) номера на примере нетипового документа выдачи шин для спецтехники с табличной частью, разработанного в конфигурации КА2. Данные берутся из. . .
Хочу заставить корпорации вкладываться в здоровье сотрудников: делаю мат модель здравосохранения
anaschu 22.03.2026
e7EYtONaj8Y Z4Tv2zpXVVo https:/ / github. com/ shumilovas/ med2. git
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru