Попросите функцию взять некоторые данные и отправить их обратноJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Попросите функцию взять некоторые данные и отправить их обратно

Сообщение Anonymous »

Я пытаюсь заставить Java-функцию принимать входные данные, изменять их и отправлять обратно. Обычно вы должны вернуть varName; или что-то в этом роде, однако здесь это не работает. Мой вопрос заключается в следующем: как я могу создать собственный метод, который будет принимать переменную "nameRaw" и изменять ее внутри функции "nameChanger()", а затем помещать измененное имя в переменную: "nameChanged".

Я использовал IDEONE.com, чтобы показать код и обработать его, поэтому вот ссылка: http://ideone.com/cdj6Cd

Если вы не доверяете случайным ссылкам, это находка и совершенно понятно. Итак, я тоже помещу это здесь, но предположим, что единственное, что пользователь ввел в качестве входных данных, — это «Тест».

Код:

Код: Выделить всё

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception {
System.out.println("*INTENDED* Function of this-To create a custom method to take in a variable 'nameRaw' and change it within the function 'nameChanger()' then out put the changed name to variable: 'nameChanged'.\nProblem: the name changes within the function 'nameChanger()' only, therefore I cannot call the variable 'nameChanged' elsewhere, such as in main().........\n\n\n");
// Initalize the Java Scanner
Scanner in = new Scanner(System.in);

// Initalizes a completely empty string with name "nameChanged"
String nameChanged = null;

System.out.println("Please enter a username for yourself below:");
System.out.println("Test"); // Fake input to make me feel good I guess, it just looks better

// Sets "nameRaw" to "Test"
String nameRaw = in.nextLine();

// Spits out the untouched value that the user has entered
System.out.println("\nRaw name before passing to custom method: " + nameRaw);

// Puts "nameRaw" into the custom method "nameChanger()" to change the, "s" in, "Test" to a "z" by default
nameChanger(nameRaw, nameChanged);

// Spits out the touched and changed nameChanged variable from "nameChanger()"
if(nameChanged == null) {
System.out.println("\nHere is the failed changed name: " + nameChanged);
System.out.println("\nARE YOU KIDDING ME! WHY DOES THIS NOT WORK?!?! PLEASE HELP!!!!");
} else {
System.out.println("Here is the successfuly changed name: " + nameChanged);
System.out.println("\nWhoever solved this problem is a god..");
}

} // Closes method main()

// Custom method named "nameChanger" that will need a variable named "nameRaw" *which is set* within its () to function
private static String nameChanger(String nameRaw, String nameChanged) {

//// Initalizes a completely empty string with name "nameChanged"
//String nameChanged = null;

// States the set name *unchanged* from the main method on line 17
System.out.println("\t#\tName unchanged read and displayed by the nameChanger custom method: " + nameRaw);

// The name by default "Test" does contain an "s" so the if statement is satisfied
if(nameRaw.contains("s")) {

// The variable "nameRaw should be running through here and having it's "s" replaced with a "z"
nameChanged = nameRaw.replace("s", "z");

// Output the changed name *if all goes right*
System.out.println("\t#\tName changed *still in custom function* is: " + nameChanged);

// The else statement is just for testing purposes, such as changing "Test" as the input to "Demo" to dis-satisfy the if statemtent
} else {
System.out.println("\t#\tFor reference, here is the unchanged name raw: " + nameRaw);
System.out.println("\t#\tAlso for reference, here is the null value 'nameChanged': " + nameChanged);
}

// One more time to show my hate toward Java, output the changed variable "nameChanged". Take note that the "s" is a "z".....
System.out.println("\t#\tPlease don't be null or have an 's' in it: " + nameChanged);

// To output to main() that nameChanged is now not null *if all goes right*, but "Tezt" should be the output
return nameChanged;
} // Close custom method, nameChanger()
}
Спасибо, ребята, надеюсь, это не слишком вас расстроило :p,
Аарон

Подробнее здесь: https://stackoverflow.com/questions/392 ... nd-it-back
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «JAVA»