Я пытаюсь сделать функцию 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()
}
Спасибо, ребята надеюсь, что это не захлестнуть вас toooo много: р, Аарон
Вам не нужно 'если (nameRaw.contains ("S"))' чек. Это пустая трата времени. Просто сделайте 'nameRaw.replace (" s "," z ");' – 4castle
Вы не можете объединить «null» в строку. – 4castle