Меню

For input string ошибка перевод

glebasik0

0 / 0 / 0

Регистрация: 10.04.2017

Сообщений: 8

1

03.11.2017, 05:41. Показов 14144. Ответов 2

Метки нет (Все метки)


Считываю из файла строку: asdasdasd112 sada 1 123dfdsd
Выбрал только цифры, получилось так: 112 1 123
Пытаюсь убрать лишние пробелы, а у меня выдаёт эту ошибку: java.lang.NumberFormatException: For input string: «»
Ошибка возникает в этой части кода:

Java
1
2
3
4
5
6
7
8
9
10
11
12
            int s = 0;
            int j = 0;
            List<String> ListChisel = new ArrayList<String>();
            ListChisel = Arrays.asList(massPosled2);
            for (int i = 0; i < ListChisel.size(); i++) {
                if (Character.isSpaceChar(Integer.parseInt(ListChisel.get(i)))){
                    ListChisel.remove(i);
                    j++;
                } else{
                    s++;
                }
            }

Но на всякий случай вот весь код:

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
package com.company;
 
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 
public class Main {
 
    public static void main(String args[]) throws IOException {
        FileInputStream fileIn = null;
 
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            File f = new File("in.txt");
            BufferedReader fin = new BufferedReader(new FileReader(f));
            String line = fin.readLine();
            System.out.println(line);
 
            String num = "";
 
            char[] c = line.toCharArray();
            System.out.println(c);
            for (int i = 0; i < c.length; i++){
                if(Character.isDigit(c[i])||c[i]==' '){
                    num+=c[i];
                }else {
 
                }
            }
 
            String chisla = num.toString();
            String massPosled[] = chisla.split(" ");
            String massPosled2[] = new String[massPosled.length];
            for (int i = 0; i < massPosled.length; i++) {
                if (massPosled[i] == "") {
 
                } else {
                    massPosled2[i] = massPosled[i];
                    System.out.println(massPosled2[i]);
                }
            }
 
            int s = 0;
            int j = 0;
            List<String> ListChisel = new ArrayList<String>();
            ListChisel = Arrays.asList(massPosled2);
            for (int i = 0; i < ListChisel.size(); i++) {
                if (Character.isSpaceChar(Integer.parseInt(ListChisel.get(i)))){
                    ListChisel.remove(i);
                    j++;
                } else{
                    s++;
                }
            }
 
 
        }finally {
            if (fileIn != null) {
                fileIn.close();
            }
        }
    }
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



al1as

386 / 74 / 31

Регистрация: 13.04.2012

Сообщений: 127

03.11.2017, 07:00

2

Я бы вообще весь ваш код с заполнением листа после 17 строки заменил на:

Java
1
2
3
4
5
6
Matcher matcher = Pattern.compile(".*?(\d+)").matcher(line);
            
List<String> ListChisel = new ArrayList<>();
while (matcher.find()) {
    ListChisel.add(matcher.group(1));
}

А у вас ошибка в 36 строке: строки нужно сравнивать через equals. После этого у вас в массиве на месте пустого символа окажется элемент null. Избавиться от него при создании листа можно такой строкой

Java
1
List<String> ListChisel = Arrays.stream(massPosled2).filter(Objects::nonNull).collect(Collectors.toList());

Либо вручную создавать лист и при добавлении элементов проверять на null (но не использовать Arrays.asList(), т.к. он создает лист фиксированного размера, и удалить из него ничего не выйдет).

Добавлено через 9 минут
Если будете пробовать мой вариант, не забудьте добавить импорты:

Java
1
2
import java.util.regex.Matcher;
import java.util.regex.Pattern;



0



746 / 493 / 285

Регистрация: 10.09.2015

Сообщений: 1,530

03.11.2017, 12:58

3

(Character.isSpaceChar(Integer.parseInt(ListChisel .get(i)) — ты пытаешься пробел перевести в число, вот тебе и ошибка



0



1. Введение

Java выдает NumberFormatException — непроверенное исключение — когда не может преобразовать String в числовой тип.

Поскольку он не отмечен, Java не заставляет нас обрабатывать или объявлять его.

В этом кратком руководстве мы опишем и продемонстрируем, что вызывает исключение NumberFormatException в Java и как его избежать или как справиться с этим .

NumberFormatException вызывают различные проблемы . Например, некоторые конструкторы и методы в Java вызывают это исключение.

Мы обсудим большинство из них в следующих разделах.

2.1. Нечисловые данные, передаваемые в конструктор

Давайте посмотрим на попытку построить объект Integer или Double с нечисловыми данными.

Оба этих оператора вызовут исключение NumberFormatException :

Integer aIntegerObj = new Integer("one"); Double doubleDecimalObj = new Double("two.2");

Давайте посмотрим на трассировку стека, которую мы получили, когда передали недопустимый ввод «one» в конструктор Integer в строке 1:

Exception in thread "main" java.lang.NumberFormatException: For input string: "one" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.(Integer.java:867) at MainClass.main(MainClass.java:11)

Это вызвало исключение NumberFormatException . Конструктору Integer не удалось внутренне понять ввод с помощью parseInt () .

Java Number API не разбирает слова на числа, поэтому мы можем исправить код, просто изменив его на ожидаемое значение:

Integer aIntegerObj = new Integer("1"); Double doubleDecimalObj = new Double("2.2");

2.2. Анализ строк, содержащих нечисловые данные

Подобно поддержке синтаксического анализа в конструкторе Java, у нас есть специальные методы синтаксического анализа, такие как par seInt (), parseDouble (), valueOf () и decode () .

Если мы попробуем сделать такие же преобразования с помощью этих:

int aIntPrim = Integer.parseInt("two"); double aDoublePrim = Double.parseDouble("two.two"); Integer aIntObj = Integer.valueOf("three"); Long decodedLong = Long.decode("64403L");

Тогда мы увидим такое же ошибочное поведение.

И мы можем исправить их аналогичным образом:

int aIntPrim = Integer.parseInt("2"); double aDoublePrim = Double.parseDouble("2.2"); Integer aIntObj = Integer.valueOf("3"); Long decodedLong = Long.decode("64403");

2.3. Передача строк с посторонними символами

Или, если мы попытаемся преобразовать строку в число с посторонними данными на входе, такими как пробелы или специальные символы:

Short shortInt = new Short("2 "); int bIntPrim = Integer.parseInt("_6000");

Тогда у нас будет та же проблема, что и раньше.

Мы можем исправить это с помощью небольших манипуляций со строками:

Short shortInt = new Short("2 ".trim()); int bIntPrim = Integer.parseInt("_6000".replaceAll("_", "")); int bIntPrim = Integer.parseInt("-6000");

Обратите внимание, что здесь, в строке 3, разрешены отрицательные числа с использованием символа дефиса как знака минус.

2.4. Форматы номеров для конкретных регионов

Давайте посмотрим на особый случай номеров, зависящих от локали. В европейских регионах запятая может представлять десятичный знак. Например, «4000,1» может представлять десятичное число «4000,1».

По умолчанию мы получим NumberFormatException , пытаясь разобрать значение, содержащее запятую:

double aDoublePrim = Double.parseDouble("4000,1");

Нам нужно разрешить использование запятых и избежать исключения в этом случае. Чтобы это стало возможным, Java должна понимать запятую здесь как десятичную дробь.

Мы можем разрешить использование запятых для европейского региона и избежать исключения, используя NumberFormat .

Давайте посмотрим на это в действии на примере Locale для Франции:

NumberFormat numberFormat = NumberFormat.getInstance(Locale.FRANCE); Number parsedNumber = numberFormat.parse("4000,1"); assertEquals(4000.1, parsedNumber.doubleValue()); assertEquals(4000, parsedNumber.intValue()); 

3. Передовой опыт

Давайте поговорим о нескольких хороших практиках, которые могут помочь нам справиться с NumberFormatException :

  1. Не пытайтесь преобразовывать буквенные или специальные символы в числа — API чисел Java не может этого сделать.
  2. Возможно, мы захотим проверить входную строку с помощью регулярных выражений и выбросить исключение для недопустимых символов .
  3. Мы можем очистить ввод от предсказуемых известных проблем с помощью таких методов, как trim () и replaceAll () .
  4. В некоторых случаях вводимые специальные символы могут быть допустимыми. Для этого мы выполняем специальную обработку, например, используя NumberFormat , который поддерживает множество форматов.

4. Вывод

В этом руководстве мы обсудили NumberFormatException в Java и его причины. Понимание этого исключения может помочь нам создавать более надежные приложения.

Кроме того, мы изучили стратегии, позволяющие избежать исключения с некоторыми недопустимыми входными строками.

Наконец, мы увидели несколько передовых методов работы с NumberFormatException .

Как обычно, исходный код, используемый в примерах, можно найти на GitHub.


Вопрос:

Я получаю эту ошибку, когда запускаю следующий код и вводя 5×5 для размера. Не знаете почему?

Когда я вхожу в 10×10, кажется, что он работает нормально, но я не уверен, что результат правильный.

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)"

Вот мой код

    import java.util.Scanner;

public class CheckerBoard {

public static void main(String [] args){

Scanner userInput = new Scanner(System.in);

System.out.println("What two colors would you like your board to be?");

String colorOne = userInput.next();
String colorTwo = userInput.next();

do {
System.out.println("How big should the checker board be? (Square sizes only please)" + "n"
+ "Please enter it like 4x4 with whatever numbers you choose.");

String boardSize = userInput.next();

int intOne = Integer.parseInt(boardSize.substring(0,boardSize.indexOf("x")));
System.out.println(boardSize.indexOf("x"));
int intTwo = Integer.parseInt(boardSize.substring(boardSize.indexOf("x")+1, boardSize.length()-1));
System.out.println(intOne);

} while(false);
}
}

//keep in mind that this program is not done yet, this is just a current issue I am having atm.

Лучший ответ:

Проблема здесь:

int intTwo = Integer.parseInt(boardSize.substring(boardSize.indexOf("x")+1, boardSize.length()-1));

Вы берете подстроку от x до length - 1. Вы должны перейти от x к length потому что substring не включает второй индекс.

Итак, вы получили ошибку на 5x5 потому что после x есть только один символ. Таким образом, вы пытались parseInt пустую строку. У вас не было исключения на 10x10, но вы использовали только 10x1.

Таким образом, вы должны изменить эту строку следующим образом:

int intTwo = Integer.parseInt(boardSize.substring(boardSize.indexOf("x")+1, boardSize.length()));

Ответ №1

Я считаю, что более безопасный способ сделать это – раскол на x

String boardSize = userInput.next();
String[] split = boardSize.split("x");
int intOne = Integer.parseInt(split[0]);
int intTwo = Integer.parseInt(split[1]);

Очевидно, санируйте для BAD INPUT!

Ответ №2

В вашем коде не учитывается, что строка boardSize может быть пуста, когда выполняется строка;

int intOne = Integer.parseInt(boardSize.substring(0,boardSize.indexOf("x")));

Когда вы выполняете “indexOf”, ища то, чего не существует, вы получите -1 назад, что является недопустимым как аргумент вашей подстроки.

Ответ №3

Вы пробовали это?

        int intTwo = Integer.parseInt(boardSize.substring(boardSize.indexOf("x")+1, boardSize.length()));

Вероятно, чем дольше вы посмотрите, тем решите проблему синтаксического анализа.

Ответ №4

+ Изменить
int intTwo = Integer.parseInt(boardSize.substring(boardSize.indexOf("x")+1, boardSize.length()-1));
в
int intTwo = Integer.parseInt(boardSize.substring(boardSize.indexOf("x")+1, boardSize.length()));
Помните, что второй индекс, переданный в String.substring, не будет включен в возвращаемое значение.

  • 1
    INS

    5) Военный термин: Indian Navy Ship, immediate nuclear support, improved navigational satellite, improved night sight, inertial navigation system, infantry night sight, information system, initial navigation system, integrated navigation system, interchangeable — substitute items, internal navigation system, international navigation system, insurgent

    19) AMEX. Intelligent Systems Corporation

    Универсальный англо-русский словарь > INS

  • 2
    Ins

    5) Военный термин: Indian Navy Ship, immediate nuclear support, improved navigational satellite, improved night sight, inertial navigation system, infantry night sight, information system, initial navigation system, integrated navigation system, interchangeable — substitute items, internal navigation system, international navigation system, insurgent

    19) AMEX. Intelligent Systems Corporation

    Универсальный англо-русский словарь > Ins

  • 3
    ins

    5) Военный термин: Indian Navy Ship, immediate nuclear support, improved navigational satellite, improved night sight, inertial navigation system, infantry night sight, information system, initial navigation system, integrated navigation system, interchangeable — substitute items, internal navigation system, international navigation system, insurgent

    19) AMEX. Intelligent Systems Corporation

    Универсальный англо-русский словарь > ins

  • 4
    well

    4. отстойник, зумпф

    multiple string small diameter well — скважина, пробуренная для одновременной и раздельной эксплуатации нескольких продуктивных горизонтов, в которую спущено две и более эксплуатационных колонн малого диаметра

    well out of control — скважина, фонтанирование которой не удаётся закрыть; открыто фонтанирующая скважина

    well producing from … — эксплуатационная скважина, проведенная на (такой-то) пласт

    * * *

    to blow a well — открывать фонтанирующую скважину на короткое время (для удаления воды, песка);

    to bump off a well — отсоединять насосную скважину от группового привода;

    to flow a well hard — эксплуатировать фонтанирующую скважину с максимально возможным дебитом;

    to hand off a well — отсоединять насосную скважину от группового привода;

    to kill a well — глушить скважину (уравновешивать пластовое давление);

    to mud a well up — подавать буровой раствор в скважину (после бурения с продувкой);

    to plug up a well — устанавливать в скважину цементную пробку (с целью её ликвидации);

    to pull a well — ликвидировать скважину с извлечением лифтовых труб и насосного оборудования;

    to put a well on the pump — 1. начинать насосную эксплуатацию скважины; 2. устанавливать насосный подъёмник в скважине

    to rock a well — возбуждать приток в скважине попеременным открытием и закрытием устья;

    to shut in a well — закрывать скважину, останавливать скважину (устьевой задвижкой);

    to strip a well — попеременно двигать колонны насосных штанг и лифтовых труб в скважине (для предотвращения скопления парафина);

    * * *

    скважина; колодец

    * * *

    * * *

    2) резервуар; компенсационный колодец, отстойник, зумпф

    well kicked off natural — скважина, начавшая фонтанировать без возбуждения, без тартания и без кислотной обработки;

    well off — простаивающая скважина;

    well out of control — открыто фонтанирующая скважина; скважина, фонтанирование которой не удается остановить ;

    to bump off a well — отсоединять насосную скважину от группового привода;

    to case a well — крепить скважину обсадными трубами, обсаживать ствол скважины;

    to complete a well — 1) подготавливать скважину к эксплуатации 2) заканчивать скважину;

    to dual a well — 1) эксплуатировать одновременно два горизонта в скважине 2) использовать силовую установку одной скважины для эксплуатации другой;

    to flow a well hard — эксплуатировать фонтанирующую скважину с максимально возможным дебитом;

    to hand off a well — отсоединять насосную скважину от группового привода;

    to line a well — крепить скважину обсадными трубами, обсаживать ствол скважины;

    to pull a well — ликвидировать скважину с извлечением насосно-компрессорных труб и насосного оборудования;

    to put a well on the pump — 1) начинать насосную эксплуатацию скважины 2) устанавливать насосный подъёмник в скважине;

    to rock a well — возбуждать приток в скважине попеременным открытием и закрытием устья;

    to shut in a well — закрывать скважину; останавливать фонтанирование; останавливать скважину ;

    to strip a well — попеременно двигать колонны насосных штанг и насосно-компрессорных труб в скважине ;


    — abandoned condensate well
    — abandoned gas well
    — abandoned oil well
    — abandoned oil-and-gas well
    — abnormal-pressure well
    — absorption well
    — Abyssinian well
    — adjacent well
    — adjoining well
    — appraisal well
    — artesian well
    — barefooted well
    — barren well
    — base well
    — beam well
    — beam-pumped well
    — belching well
    — benchmark well
    — blow well
    — blowing well
    — blowout well
    — blue sky exploratory well
    — borderline well
    — bore well
    — Braden head gas well
    — breakthrough well
    — breathing well
    — brought-in well
    — cable-tool well
    — cased well
    — cased-through well
    — cemented-up well
    — center well
    — closed-in well
    — close-spaced wells
    — cluster well
    — commercial well
    — completed well
    — condensate well
    — confirmation well
    — connected well
    — controlled directional well
    — converted gas-input well
    — cored well
    — corner well
    — corrosive well
    — cratering well
    — crooked well
    — curved well
    — dead well
    — declined well
    — deep well
    — deflected well
    — development well
    — development gas well
    — development test well
    — deviated well
    — deviating well
    — dewatering well
    — directional well
    — directionally drilled well
    — discovery well
    — disposal well
    — diving well
    — down-dip well
    — drain-hole well
    — drawn well
    — drawned-out well
    — drill well
    — drill ship well
    — drill ship center well
    — drilled well
    — drilled gas-input well
    — drilled water-input well
    — drilling well
    — driven well
    — drowned well
    — dry well
    — dual well
    — dual-completion well
    — dual-completion gas well
    — dual-completion oil well
    — dually-completed well
    — dual-pumping well
    — dual-zone well
    — edge well
    — exception well
    — exhausted well
    — exploratory well
    — extension well
    — field well
    — field development well
    — fill-in well
    — flank well
    — flooded well
    — flowing well
    — flowing producing oil well
    — fresh-water well
    — fully penetrating well
    — gas well
    — gas-injection well
    — gaslift well
    — geophysical well
    — geothermal well
    — gurgling well
    — gusher well
    — hand dog well
    — head well
    — high-flow-rate well
    — high-pressure well
    — horizontal well
    — hydrodynamically imperfect well
    — hydrodynamically perfect well
    — hypothetical well
    — image well
    — imperfect well
    — inactive well
    — inclined well
    — individual well
    — infill well
    — injection well
    — injured well
    — input well
    — inspection well
    — intake well
    — intracontour well
    — isolated-branched well
    — jack well
    — junked well
    — key well
    — kicking well
    — killed well
    — killer well
    — leaking well
    — line well
    — low pressure well
    — marginal well
    — medium-depth well
    — monitor well
    — most probably well
    — mudded well
    — mudded-up well
    — multipay well
    — multiple-completion well
    — multiple-string small diameter well
    — multiple-zone well
    — multistring well
    — natural well
    — neighboring well
    — noncommercial well
    — nonproducing well
    — nonproductive well
    — observation well
    — off-pattern injection well
    — off-structure well
    — offset well
    — offshore well
    — oil well
    — old well drilled deeper
    — old well plugged back
    — old well worked-over
    — old abandoned well
    — on-structure well
    — on-the-beam well
    — on-the-pump well
    — open hole well
    — orifice well
    — out-of-control well
    — outpost extension well
    — output well
    — overhauled well
    — partially penetrating well
    — paying well
    — perfect well
    — perforated well
    — perimeter well
    — piestic well
    — pinch-out well
    — pioneer well
    — pipe well
    — planned well
    — platform well
    — plugged-and-abandoned well
    — pressure well
    — pressure-observation well
    — pressure-relief well
    — producing well
    — producing oil well
    — producing oil-and-gas well
    — production well
    — prolific well
    — prospect well
    — pumped well
    — pumper well
    — pumping well
    — pumping producing oil well
    — purposely deviated well
    — purposely slanted well
    — quadruple completion well
    — recipient wells
    — recovery well
    — relief well
    — returned well to production
    — rod-line well
    — running well
    — salt-dome well
    — salt-up well
    — salt-water well
    — salt-water disposal well
    — salt-water injection well
    — sand well
    — sand-clogged well
    — sanded well
    — sanded-up well
    — sanding-up well
    — sand-plugged well
    — sand-producing well
    — sand-up well
    — sandy well
    — satellite well
    — seabed well
    — selective water-injection well
    — service well
    — shallow well
    — shut-in well
    — shut-in gas well
    — shut-in oil well
    — side well
    — single well
    — single-completion well
    — single-jacker well
    — single-string well
    — slanted well
    — slim hole well
    — special well
    — staggered wells
    — steam well
    — steam-injection well
    — step-out well
    — straight well
    — stratigraphic well
    — stratigraphic test well
    — stripped well
    — stripper well
    — strong well
    — structure test well
    — subsalt well
    — sunken well
    — superdeep well
    — supply well
    — surging well
    — suspended well
    — temporarily abandoned well
    — temporarily shut-in well
    — test well
    — triple-completion well
    — tubed well
    — turnkey well
    — twin well
    — two-casing well
    — two-string well
    — ultradeep well
    — underwater well
    — unloading well
    — unprofitable well
    — untubed well
    — upstream well
    — vertical well
    — waste disposal well
    — water well
    — water-dependent well
    — water-disposal well
    — water-free well
    — water-injection well
    — water-producing well
    — water-supply well
    — wet well
    — wide-spaced wells
    — wild well
    — wild gas well
    — wildcat well
    — worked-over well
    — workover well

    * * *

    Англо-русский словарь нефтегазовой промышленности > well

  • 5
    Well

    Англо-русский словарь нефтегазовой промышленности > Well

  • 6
    data

    Большой англо-русский и русско-английский словарь > data

  • 7
    operation

    1. n действие, работа; функционирование

    to be in operation — быть в эксплуатации; действовать, функционировать, работать

    2. n процесс

    3. n действие, воздействие

    4. n торговая или финансовая операция; сделка

    5. n мед. хирургическая операция

    6. n обыкн. l

    7. n работы, операции

    8. n воен. операция, боевые действия, бой; сражение

    9. n разработка, эксплуатация

    10. n тех. операция, цикл обработки

    11. n мат. действие, операция

    Синонимический ряд:

    1. administration (noun) administration; control; controlling; guidance; maintenance; order; ordering; superintendence; supervision

    2. affair (noun) affair; agency; business; course; maneuver; manoeuvre; transaction

    3. effect (noun) action; effect; efficacy; force; influence; virtue

    4. procedure (noun) act; deed; doing; execution; handling; manipulation; procedure

    5. promoting (noun) advancement; compelling; enforcement; enforcing; promoting

    6. surgery (noun) acupuncture; biopsy; dismemberment; dissection; excision; removal; section; surgery; vivisection

    7. use (noun) appliance; application; employment; exercise; exercising; exertion; implementation; play; usage; usance; use; utilisation

    8. working (noun) behaviour; functioning; performance; reaction; working

    Антонимический ряд:

    failure; ineffectiveness; inutility; rest; uselessness

    English-Russian base dictionary > operation

  • 8
    queue

    1. n коса; косичка

    2. n геральд. хвост

    3. n очередь, хвост

    4. n вереница экипажей машин

    5. n ёмкость для вина

    6. n мат. система массового обслуживания

    7. v заплетать косу

    8. v стоять в очереди или становиться в очередь

    Синонимический ряд:

    1. hairstyle (noun) braid; hairstyle; pigtail; plait; plat; pony tail; twist

    2. line (noun) column; cordon; echelon; file; line; progression; range; rank; row; sequence; series; string; tier

    Антонимический ряд:

    disperse; scatter

    English-Russian base dictionary > queue

  • 9
    wire

    1. n проволока

    2. n электрический провод

    inhibit wire — провод запрета; шина запрета; обмотка запрета

    3. n телеграфный или телефонный провод

    4. n телеграфная или телефонная связь

    5. n амер. разг. телеграмма

    6. n l

    7. n механизм управления куклами в кукольном театре

    8. n тайные пружины, скрытые силы, руководящие действиями лиц или организаций

    to pull the wires — нажимать на тайные пружины, пустить в ход связи; тайно влиять

    9. n линия финиша на скачках

    10. n разг. трос

    11. n редк. струна

    12. n редк. проволочная сетка

    13. n заграждение или ограда из проволоки

    under wire — обнесённый колючей предупреждение, тайный сигнал

    14. n охот. проволочный силок

    15. n разг. жесткошёрстный терьер

    16. n сл. ловкий карманник

    17. v связывать или скреплять проволокой

    18. v прокладывать или монтировать проводку

    19. v воен. прокладывать линию проводной связи

    20. v телеграфировать

    wire off — телеграфировать; посылать деньги телеграфом

    21. v воен. устанавливать проволочные заграждения

    22. v охот. ловить в проволочные силки

    23. v сл. предрешать результаты соревнования

    24. v разг. энергично приниматься, набрасываться

    Синонимический ряд:

    1. cablegram (noun) cablegram; easylink; electronic mail; message; night letter; telegram

    2. line (noun) cable; circuit; electric wire; electrical conductor; filament; line; piano string; soldered connection; strand of metal

    English-Russian base dictionary > wire

См. также в других словарях:

  • String metric — String metrics (also known as similarity metrics) are a class of textual based metrics resulting in a similarity or dissimilarity (distance) score between two pairs of text strings for approximate matching or comparison and in fuzzy string… …   Wikipedia

  • String literal — A string literal is the representation of a string value within the source code of a computer program. There are numerous alternate notations for specifying string literals, and the exact notation depends on the individual programming language in …   Wikipedia

  • String (computer science) — In formal languages, which are used in mathematical logic and theoretical computer science, a string is a finite sequence of symbols that are chosen from a set or alphabet. In computer programming, a string is traditionally a sequence of… …   Wikipedia

  • String ribbon — solar cells is proprietary technology developed by Evergreen Solar. Technology descriptionString Ribbon describes a method of producing high grade silicon wafers suitable for the photovoltaics industry. The name describes the manufacturing… …   Wikipedia

  • String exploits — Several implementation / design flaws are associated with string programming, some of those are associated with security exploits. Concatenation problems It is possible to cause String1 + User Input String + String2 to behave in unepected ways by …   Wikipedia

  • Input mask — In computer programming, an input mask often refers to a string expression that a developer defines, which governs what is allowed to be entered into a typical edit box. It can be said to be a template, or set format that entered data must… …   Wikipedia

  • C file input/output — C Standard Library Data types Character classification Strings Mathematics File input/output Date/time Localiza …   Wikipedia

  • Magic string — A magic string is an input that a programmer believes will never come externally and which activates otherwise hidden functionality. A user of this program would likely provide input that gives an expected response in most situations. However, if …   Wikipedia

  • Closest string — In theoretical computer science, closest string is the name of an NP hard computational problem, which tries to find the geometrical center of a set of input strings. To understand the word center it is necessary to define a distance between two… …   Wikipedia

  • Aho–Corasick string matching algorithm — The Aho–Corasick string matching algorithm is a string searching algorithm invented by Alfred V. Aho and Margaret J. Corasick. It is a kind of dictionary matching algorithm that locates elements of a finite set of strings (the dictionary ) within …   Wikipedia

  • printf format string — An example of the printf function. Printf format string (which stands for print formatted ) refers to a control parameter used by a class of functions typically associated with some types of programming languages. The format string specifies a… …   Wikipedia

На чтение 5 мин. Просмотров 26 Опубликовано 15.12.2019

String metric — String metrics (also known as similarity metrics) are a >Wikipedia

String ribbon — solar cells is proprietary technology developed by Evergreen Solar. Technology descriptionString Ribbon describes a method of producing high grade silicon wafers suitable for the photovoltaics industry. The name describes the manufacturing… … Wikipedia

String literal — A string literal is the representation of a string value within the source code of a computer program. There are numerous alternate notations for specifying string literals, and the exact notation depends on the indiv >Wikipedia

String exploits — Several implementation / design flaws are associated with string programming, some of those are associated with security exploits. Concatenation problems It is possible to cause String1 + User Input String + String2 to behave in unepected ways by … Wikipedia

String (computer science) — In formal languages, which are used in mathematical logic and theoretical computer science, a string is a finite sequence of symbols that are chosen from a set or alphabet. In computer programming, a string is traditionally a sequence of… … Wikipedia

Input mask — In computer programming, an input mask often refers to a string expression that a developer defines, which governs what is allowed to be entered into a typical edit box. It can be sa >Wikipedia

String+Alt+Delete — Die Standard Tastenkombination „Strg Alt Entf“ ist nur mit zwei Händen zu erreichen, allerdings hat die einhändig erreichbare AltGr+Strg (rechts)+Entf Kombination dieselbe Wirkung. Benutzer von Personal Computern und anderen Rechnersystemen… … Deutsch Wikipedia

String+Alt+Entfernen — Die Standard Tastenkombination „Strg Alt Entf“ ist nur mit zwei Händen zu erreichen, allerdings hat die einhändig erreichbare AltGr+Strg (rechts)+Entf Kombination dieselbe Wirkung. Benutzer von Personal Computern und anderen Rechnersystemen… … Deutsch Wikipedia

Closest string — In theoretical computer science, closest string is the name of an NP hard computational problem, which tries to find the geometrical center of a set of input strings. To understand the word center it is necessary to define a distance between two… … Wikipedia

Aho–Corasick string matching algorithm — The Aho–Corasick string matching algorithm is a string searching algorithm invented by Alfred V. Aho and Margaret J. Corasick. It is a kind of dictionary matching algorithm that locates elements of a finite set of strings (the dictionary ) within … Wikipedia

C file input/output — C Standard Library Data types Character >Wikipedia

String metric — String metrics (also known as similarity metrics) are a >Wikipedia

String literal — A string literal is the representation of a string value within the source code of a computer program. There are numerous alternate notations for specifying string literals, and the exact notation depends on the indiv >Wikipedia

String (computer science) — In formal languages, which are used in mathematical logic and theoretical computer science, a string is a finite sequence of symbols that are chosen from a set or alphabet. In computer programming, a string is traditionally a sequence of… … Wikipedia

String ribbon — solar cells is proprietary technology developed by Evergreen Solar. Technology descriptionString Ribbon describes a method of producing high grade silicon wafers suitable for the photovoltaics industry. The name describes the manufacturing… … Wikipedia

String exploits — Several implementation / design flaws are associated with string programming, some of those are associated with security exploits. Concatenation problems It is possible to cause String1 + User Input String + String2 to behave in unepected ways by … Wikipedia

Input mask — In computer programming, an input mask often refers to a string expression that a developer defines, which governs what is allowed to be entered into a typical edit box. It can be sa >Wikipedia

C file input/output — C Standard Library Data types Character >Wikipedia

Magic string — A magic string is an input that a programmer believes will never come externally and which activates otherwise h >Wikipedia

Closest string — In theoretical computer science, closest string is the name of an NP hard computational problem, which tries to find the geometrical center of a set of input strings. To understand the word center it is necessary to define a distance between two… … Wikipedia

Aho–Corasick string matching algorithm — The Aho–Corasick string matching algorithm is a string searching algorithm invented by Alfred V. Aho and Margaret J. Corasick. It is a kind of dictionary matching algorithm that locates elements of a finite set of strings (the dictionary ) within … Wikipedia

printf format string — An example of the printf function. Printf format string (which stands for print formatted ) refers to a control parameter used by a >Wikipedia

Перевод по словам

adjective: входной, вводимый, подводимый, поглощенный

noun: ввод, ввод данных, входные данные, потребление, исходные данные, поглощение, вводное устройство, предоставление данных, предоставление сведений

  • input range — входной диапазон
  • input terminal — входная клемма
  • input connector — входной разъем
  • mnemonic input — устройство ввода с мнемоническими обозначениями команд на клавишах
  • screening of input leads — экранирование входных проводников
  • analogue input expander — расширение аналогового входа
  • input impedance — входной импеданс
  • input signal amplitude — амплитуда входного сигнала
  • input power — входная мощность
  • input pattern — входной образ

noun: строка, струна, шнурок, ряд, нитка, вереница, веревка, тетива, бечевка, завязка

verb: нанизывать, натягивать, обманывать, натягивать тетиву, вешать, завязывать, привязывать, шнуровать, водить за нос

Corpus name: OpenSubtitles2018. License: not specified. References: http://opus.nlpl.eu/OpenSubtitles2018.php, http://stp.lingfil.uu.se/~joerg/paper/opensubs2016.pdf

Corpus name: OpenSubtitles2018. License: not specified. References: http://opus.nlpl.eu/OpenSubtitles2018.php, http://stp.lingfil.uu.se/~joerg/paper/opensubs2016.pdf

Corpus name: OpenSubtitles2018. License: not specified. References: http://opus.nlpl.eu/OpenSubtitles2018.php, http://stp.lingfil.uu.se/~joerg/paper/opensubs2016.pdf

Corpus name: OpenSubtitles2018. License: not specified. References: http://opus.nlpl.eu/OpenSubtitles2018.php, http://stp.lingfil.uu.se/~joerg/paper/opensubs2016.pdf

Corpus name: OpenSubtitles2018. License: not specified. References: http://opus.nlpl.eu/OpenSubtitles2018.php, http://stp.lingfil.uu.se/~joerg/paper/opensubs2016.pdf

Corpus name: OpenSubtitles2018. License: not specified. References: http://opus.nlpl.eu/OpenSubtitles2018.php, http://stp.lingfil.uu.se/~joerg/paper/opensubs2016.pdf

Corpus name: OpenSubtitles2018. License: not specified. References: http://opus.nlpl.eu/OpenSubtitles2018.php, http://stp.lingfil.uu.se/~joerg/paper/opensubs2016.pdf

here’s the scenario.
I am dynamically generating the components to be displayed on the JPanel according to the data taken from the database.
The user is prompted to enter an integer number and according to that some calculations are done. The output should be given as a decimal value. Therefore, i have assigned the answer to a double and formatted is using DecimalFormat.

I get an error when i pass my double value to the format() method of DecimalFormat eventhough i didn’t enter any value as 0.

Here’s the error

java.lang.NumberFormatException: For input string: «∞» at
sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110) at
java.lang.Double.parseDouble(Double.java:538) at
java.lang.Double.valueOf(Double.java:502) at
com.boarding.brdrsbllsys.view.Bills.displayOutput(Bills.java:358) at
com.boarding.brdrsbllsys.view.Bills.btnConfirmActionPerformed(Bills.java:186)
at com.boarding.brdrsbllsys.view.Bills.access$200(Bills.java:27) at
com.boarding.brdrsbllsys.view.Bills$3.actionPerformed(Bills.java:123)
at
javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at
javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at
javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at
javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at
javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6533) at
javax.swing.JComponent.processMouseEvent(JComponent.java:3324) at
java.awt.Component.processEvent(Component.java:6298) at
java.awt.Container.processEvent(Container.java:2236) at
java.awt.Component.dispatchEventImpl(Component.java:4889) at
java.awt.Container.dispatchEventImpl(Container.java:2294) at
java.awt.Component.dispatchEvent(Component.java:4711) at
java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at
java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280) at
java.awt.Window.dispatchEventImpl(Window.java:2746) at
java.awt.Component.dispatchEvent(Component.java:4711) at
java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758) at
java.awt.EventQueue.access$500(EventQueue.java:97) at
java.awt.EventQueue$3.run(EventQueue.java:709) at
java.awt.EventQueue$3.run(EventQueue.java:703) at
java.security.AccessController.doPrivileged(Native Method) at
java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at
java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
at java.awt.EventQueue$4.run(EventQueue.java:731) at
java.awt.EventQueue$4.run(EventQueue.java:729) at
java.security.AccessController.doPrivileged(Native Method) at
java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728) at
java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at
java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at
java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at
java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at
java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

The code snippet the error is generated,

if (gbc.gridx == 1 && gbc.gridy == i + 1) {
                textConstraints.gridx = 1;
                textConstraints.gridy = i + 1;
                newPanel.add(new JLabel(((JTextField) component).getText()), textConstraints);
                int days = Integer.parseInt(((JTextField) component).getText().trim());
                System.out.println("add num of days");

                DecimalFormat df = new DecimalFormat("#.##");

                textConstraints.gridx = 3;
                double a=water / waterdays * days*1.0;
                double boarderWater = Double.valueOf(df.format(a));//error is given in this line
                newPanel.add(new JLabel(boarderWater + ""), textConstraints);
                continue;

            }

Please consider that the variables gbc and textConstraints are GridBagConstraints objects, water is a double variable and waterdays and days are int variables.

What should have been the problem with my code?

here’s the scenario.
I am dynamically generating the components to be displayed on the JPanel according to the data taken from the database.
The user is prompted to enter an integer number and according to that some calculations are done. The output should be given as a decimal value. Therefore, i have assigned the answer to a double and formatted is using DecimalFormat.

I get an error when i pass my double value to the format() method of DecimalFormat eventhough i didn’t enter any value as 0.

Here’s the error

java.lang.NumberFormatException: For input string: «∞» at
sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110) at
java.lang.Double.parseDouble(Double.java:538) at
java.lang.Double.valueOf(Double.java:502) at
com.boarding.brdrsbllsys.view.Bills.displayOutput(Bills.java:358) at
com.boarding.brdrsbllsys.view.Bills.btnConfirmActionPerformed(Bills.java:186)
at com.boarding.brdrsbllsys.view.Bills.access$200(Bills.java:27) at
com.boarding.brdrsbllsys.view.Bills$3.actionPerformed(Bills.java:123)
at
javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at
javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at
javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at
javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at
javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6533) at
javax.swing.JComponent.processMouseEvent(JComponent.java:3324) at
java.awt.Component.processEvent(Component.java:6298) at
java.awt.Container.processEvent(Container.java:2236) at
java.awt.Component.dispatchEventImpl(Component.java:4889) at
java.awt.Container.dispatchEventImpl(Container.java:2294) at
java.awt.Component.dispatchEvent(Component.java:4711) at
java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at
java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280) at
java.awt.Window.dispatchEventImpl(Window.java:2746) at
java.awt.Component.dispatchEvent(Component.java:4711) at
java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758) at
java.awt.EventQueue.access$500(EventQueue.java:97) at
java.awt.EventQueue$3.run(EventQueue.java:709) at
java.awt.EventQueue$3.run(EventQueue.java:703) at
java.security.AccessController.doPrivileged(Native Method) at
java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at
java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
at java.awt.EventQueue$4.run(EventQueue.java:731) at
java.awt.EventQueue$4.run(EventQueue.java:729) at
java.security.AccessController.doPrivileged(Native Method) at
java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728) at
java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at
java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at
java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at
java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at
java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

The code snippet the error is generated,

if (gbc.gridx == 1 && gbc.gridy == i + 1) {
                textConstraints.gridx = 1;
                textConstraints.gridy = i + 1;
                newPanel.add(new JLabel(((JTextField) component).getText()), textConstraints);
                int days = Integer.parseInt(((JTextField) component).getText().trim());
                System.out.println("add num of days");

                DecimalFormat df = new DecimalFormat("#.##");

                textConstraints.gridx = 3;
                double a=water / waterdays * days*1.0;
                double boarderWater = Double.valueOf(df.format(a));//error is given in this line
                newPanel.add(new JLabel(boarderWater + ""), textConstraints);
                continue;

            }

Please consider that the variables gbc and textConstraints are GridBagConstraints objects, water is a double variable and waterdays and days are int variables.

What should have been the problem with my code?

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Fmi 2 ошибка что это
  • For honor произошла ошибка невозможно запустить игру 05020000