Windows java return code

Java: Возврат значений

В модуле «Вызов функций» мы в основном работали с функциями, которые возвращают результат, а не выводят его на экран. Честно говоря, вывод на экран — фактически обучающий элемент. В реальном коде на экран никто ничего не выводит (за исключением утилит командной строки). Функции возвращают данные, которые потребляются другими функциями.

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

Научиться писать функции, которые возвращают информацию — первый шаг на пути к построению по-настоящему полезных программ.

Начнем с тривиального примера: создадим и вызовем функцию, которая принимает два числа и возвращает разность первого и второго. Назовём её sub() , от англ. subtract — «вычесть»:

Обратите внимание: мы знаем, что вызов функции — выражение, поэтому мы передали вызов одной функции в вызов другой функции — System.out.println(sub(10, 7)) .

Возврат задаётся специальной инструкцией return . Cправа от return помещается выражение. Любое выражение. То есть, мы можем делать вычисления сразу после return без создания переменной result :

Задание

Сэм создаёт генеалогические деревья разных семей. Ему постоянно приходится рассчитывать количество места, занимаемое именами родителей на экране.

Создайте функцию App.getParentNamesTotalLength() для Сэма. Она должна принимать один аргумент — имя ребенка, и возвращать количество символов в именах матери и отца суммарно. Функция не должна выводить ничего на экран, только возвращать число.

Для реализации используйте уже существующую функцию Functions.parentFor() :

  • Получение имени матери Functions.parentFor(child, «mother») , где child — имя ребёнка.
  • Получение имени отца Functions.parentFor(child, «father») , где child — имя ребёнка
  • Длину строки str можно получить таким образом: str.length() — это особый способ вызова функций, который мы подробно пока изучать не будем

Вам не нужно вызывать свою функцию, только определить её.

Как обычно, функцию нужно сделать public static , а не просто static , чтобы мы смогли вызвать ее из другого класса.

Как использовать return в java?

Вот вроде понимаю что return что-то возвращает, завершает процессы метода (функции), но что, как он это делает вообще, не понимаю. Пересмотрел кучу статей, видио по этому поводу, всё равно не понимаю.

Читайте также:  Windows one lives forever

Если не сложно приведите пример чтобы понял, заранее спасибо.

2 ответа 2

Каждый метод — это кусок последовательно выполняющегося кода.

Каждый метод в своей сигнатуре (определении) имеет указание на тип возвращаемого значения.

Каждый метод всегда заканчивается вызовом return . В случае если метод возвращаемым значением имеет void (не путать с Void ) то ключевое слово return можно (и нужно) опустить. Пример:

Также return в этих методах можно использовать для логических целей. Например не выполнять код методе, если какие-то условия не выполнились

Если возвращаемое значение метода не void то метод обязан вызвать return и вернуть значение указанного типа. Его можно использовать для назначения к-л переменно или иначе использовать Пример:

В последнем случае результат работы метода будет присвоен переменной i

Не могу говорить совершенно точно про java, но думаю, что там все работает также, как и в C\С++.

Если я правильно понял вопрос — отвечаю:

При вызове функции происходит смена контекста выполняемой программы — все значимые регистры и локальные переменные, а также регистр связи сохраняются в стек, а в регистры, предназначенные под передачу параметров (а если их много — для этого тоже используется стек) записываются передаваемые параметры.

Когда выполняется строка return result — в регистры, предназначенные для возврата результата выполнения функции, помещается её результат.

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

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

А более подробно на эту тему советую почитать «Соглашение о вызовах» целевой платформы.

Carriage Return\Line feed in Java

I have created a text file in Unix environment using Java code.

For writing the text file I am using java.io.FileWriter and BufferedWriter . And for newline after each row I am using bw.newLine() method (where bw is object of BufferedWriter ).

And I’m sending that text file by attaching in mail from Unix environment itself (automated that using Unix commands).

My issue is, after I download the text file from mail in a Windows system, if I opened that text file the data is not properly aligned. newline() character is not working, I think so.

I want same text file alignment as it is in Unix environment, if I opened the text file in Windows environment also.

How do I resolve the problem?

Java code below for your reference (running in Unix environment):

Читайте также:  Windows 10 не открывается свойства ipv4

6 Answers 6

Java only knows about the platform it is currently running on, so it can only give you a platform-dependent output on that platform (using bw.newLine() ) . The fact that you open it on a windows system means that you either have to convert the file before using it (using something you have written, or using a program like unix2dos), or you have to output the file with windows format carriage returns in it originally in your Java program. So if you know the file will always be opened on a windows machine, you will have to output

It’s worth noting that you aren’t going to be able to output a file that will look correct on both platforms if it is just plain text you are using, you may want to consider using html if it is an email, or xml if it is data. Alternatively, you may need some kind of client that reads the data and then formats it for the platform that the viewer is using.

How do I get the return code in Java after executing a windows command line command

I’m doing something like this in Java right now

How can I read the windows exec code? I already know how to read the command line output from the command, but what if I just want the 0 or 1 telling me whether it was successful or failed?

4 Answers 4

Use Process.exitValue() method. You will need to handle the exception thrown if the process has not yet exited and retry.

Or, you could use Process.waitFor() to wait for the process to end and it will return the process exit value also (thanks to increment1).

next line of code:

This blocks until process is complete. You can also use the Process.exitValue() method, if you don’t want to block. See Java6 Process class API doc

You it and then get .

Not the answer you’re looking for? Browse other questions tagged java or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Return -1 in Java [closed]

Want to improve this question? Update the question so it’s on-topic for Stack Overflow.

Читайте также:  Добавление пароля пользователя linux

Closed 6 years ago .

What does return -1 in Java mean? For example if I were trying to convert the following string «98979» into int type without using any library functions:

8 Answers 8

In this case it breaks calculation and give You -1 result which means that string can not be translated.

Because this code is only for possitive numbers.

Your method is incomplete (no return value specified), but the question is still valid. The meaning of a return value is completely up to the developer to decide. So either yourself or the person(s) who has written the library you use. For well-written libraries, the meaning of the return value will be specified in the documentation.

It means nothing per se. Depends on the context program calling your function, which by the way is missing the return type. If you didn’t write that code, assume -1 means an error (because the characters belonging to the String to parse are not numerical, i.e. 34E56j)

What return -1 means depends on the method. In this case, it means that a char encountered is not between (including) zeroAscii and nineAscii.

In case of finding an element of a list, you might also get -1, if the element can not be found. This is (afaik) the most common usage of return -1;

It depends on the semantic of the function. If the functions is meant to return int value which is positive (e.g return size, index) then returning negative value indicates that there is some kind of error with the input.

From the java doc of String.indexOf(int pos) — Returns the index within this string of the first occurrence of the specified character or -1 if the character does not occur.

Your method has no return type, Provide a return type of int in your method.

And return -1 means nothing in java, you are just returning a int value, thats it.

The only meaningful explanation for returning -1 seems to be, that the code calling your function expects a return type of int, converted to int from passed String. Hence when the passed String is of not proper numerical format/value the function returns a random gibberish value, in this case -1. Which by the way could very well be -10, -100 etc

Оцените статью