如何在Java中从方法中打印出某些内容并返回另一内容?

huangapple go评论93阅读模式
英文:

How to print something out and return another thing from a method in Java?

问题

// 你的方法定义
public static String StringFormating(String[] array, String input) {
    // 在这里处理字符串数组的工作

    int i = array.length; // 假设你已经定义了 i 的值
    System.out.println(array[i - 2]);
    return array[i - 3];
}

// 主方法
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    String[] array = new String[10]; // 假设你已经创建了一个字符串数组
    String result = "";

    do {
        result = input.nextLine();
    } while (!result.isBlank());

    String output = StringFormating(array, result);
    System.out.println(output);
}

注意:上述代码只是一个基本的示范,假设了一些变量和数组的初始化。你需要根据实际情况进行调整,确保你的 StringFormating 方法接收正确的参数并返回正确的结果。同时,确保数组的长度和索引的范围是合适的,以免引发数组越界异常。

英文:

So I've got a method in Java that does some things with strings. At the end of the method, I do :

System.out.println(array[i-2]);
return(array[i-3]);

Basically, in this method I work with an array of strings. At the end of it, I have to print out one value, and return another value. Now I need to create a main method in which I will let the user input things as long as he doesn't input an empty row, then call this method, pass it that string , make the method do its work with the string and write out (print out) both of these values in the console (array[i-2] and array[i-3]). Lets say my method is named "StringFormating". How can I do this in main method? I've tried doing this:

Scanner input = new Scanner();
String result="";
do{
 result=input.nextLine();
 }while(!result.isBlank());

and then doing something like System.out.println(StringFormating(result));

but it just gives me null references and I still don't understand how to actually print out both of those values in the console. Any help, please?

答案1

得分: 0

我认为您正在询问有关连接操作的问题。在Java中,有不同的方法来执行连接操作,这取决于数据的来源和用途。StringBuilde将适用于此情况。您可以将数据的新部分添加到StringBuilder中,然后在最后打印出其内容。

只是一个注意事项... 无限制地从用户那里接收数据可能是危险的,并可能导致溢出。当然,在进行学校项目时,没有人会这样做,但在部署产品时,您需要确保用户无法破坏您的代码,因为这可能会造成潜在的漏洞。

英文:

I think you are trying to ask about Concatenation. There are different ways to do this in Java it just depends on the source and use of the data. The stringbuilder would work with this. You can add new segments of data to the string builder and then print out its contents at the end.

Just a Note... Taking data in from a user endlessly can be dangerous and throw overflow.
Of course no one will do this if your just doing a school project but in deploying products you need to make sure the user cannot break your code and this could cause a possible vulnerability.

答案2

得分: 0

我不确定是否正确理解您的意思,但这可能是解决方案。

Scanner input = new Scanner();
StringBuilder sb = new StringBuilder("");
while(!input.nextLine().isBlank()){
  sb.append(StringFormatting(input.nextLine()));
}
String result = sb.toString();
System.out.println(result);
英文:

I'm not sure if I understand you correctly but this might be solution.

Scanner input = new Scanner();
StringBuilder sb = new StringBuilder("");
while(!input.nextLine().isBlank()){
  sb.append(StringFormatting(input.nextLine()));
}
String result = sb.toString();
System.out.println(result);

答案3

得分: 0

我不确定我是否正确理解了你的问题,但可能是由于do while语句导致的。在do while中,总是会在检查while条件之前执行do的主体部分,所以如果输入为空,你将把它保存在result中。你可以尝试这样做:

while(!input.nextLine().isBlank()){
    result = input.nextLine();
}

另外,我建议你使用Java的命名约定,将方法名的第一个字母小写,比如stringFormatting

英文:

I'm not sure I'm understanding your problem correctly, but it might be due to the do while. With a do while you always execute the body of the do before checking the condition in the while, so if you have an empty input you are going to save it in result. You might try doing this:

while(!input.nextLine().isBlank()){
    result = input.nextLine();
}

In addition to this, I would recommend you writing the name of the method with the first letter lowercase, this way stringFormatting, as it is a Java naming convention.

答案4

得分: 0

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String result = "";
        do {
            System.out.print("Enter your string: ");
            result = input.nextLine();
            if (!result.isBlank()) {
                System.out.println(stringFormating(result));
            } else {
                System.out.println("Goodbye!");
            }
        } while (!result.isBlank());
    }

    static int stringFormating(String str) {
        String[] data = null;
        int n = 0;
        if (str != null) {
            data = str.split(",");
        }
        if (data.length == 2) {
            System.out.println(data[0]);
            try {
                n = Integer.parseInt(data[1]);
            } catch (NumberFormatException e) {
                System.out.println("Error occured while processing data.");
            }
        }
        return n;
    }
}

A sample run:

Enter your string: abc,200
abc
200
Enter your string: xyz,40
xyz
40
Enter your string:
Goodbye!


<details>
<summary>英文:</summary>

You need something like:

    import java.util.Scanner;
    
    public class Main {
    	public static void main(String[] args) {
    		Scanner input = new Scanner(System.in);
    		String result = &quot;&quot;;
    		do {
    			System.out.print(&quot;Enter your string: &quot;);
    			result = input.nextLine();
    			if (!result.isBlank()) {
    				System.out.println(stringFormating(result));
    			} else {
    				System.out.println(&quot;Goodbye!&quot;);
    			}
    		} while (!result.isBlank());
    	}
    
    	static int stringFormating(String str) {
    		String[] data = null;
    		int n = 0;
    		if (str != null) {
    			data = str.split(&quot;,&quot;);
    		}
    		if (data.length == 2) {
    			System.out.println(data[0]);
    			try {
    				n = Integer.parseInt(data[1]);
    			} catch (NumberFormatException e) {
    				System.out.println(&quot;Error occured while processing data.&quot;);
    			}
    		}
    		return n;
    	}
    }

**A sample run:**

    Enter your string: abc,200
    abc
    200
    Enter your string: xyz,40
    xyz
    40
    Enter your string: 
    Goodbye!


</details>



huangapple
  • 本文由 发表于 2020年4月6日 04:55:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/61049386.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定