【问题标题】:I am not able to pass the values of one function to another function in java. How can I do it correctly ?我无法将一个函数的值传递给 java 中的另一个函数。我怎样才能正确地做到这一点?
【发布时间】:2018-06-05 08:39:05
【问题描述】:

这是我正在处理的代码。

import java.io.*;
import java.util.*;    
public class Program {      
  public static void main(String[] args) {
      char[] a = new char[] {'0','1'};
      possibleStrings(3, a,"");
      char[] b = new char[] {'|','&'};
      possibleStrings(2, b,"");          
      result(a,b);   }

  public static void possibleStrings(int maxLength, char[] alphabet, String curr) {    
      if(curr.length() == maxLength) {
          System.out.print(curr);
          System.out.println();         
      } else {
          for(int i = 0; i < alphabet.length; i++) {
              String oldCurr = curr;
              curr += alphabet[i];
              possibleStrings(maxLength,alphabet,curr);
              curr = oldCurr;
          }}}

  public static void result(char[] arrayA,char[] arrayB) {     
        StringBuilder sb = new StringBuilder();
        int i = 0;
        while( i < arrayA.length && i < arrayB.length){
        sb.append(arrayA[i]).append(arrayB[i]);
        ++i;
        }
        for(int j = i; j < arrayA.length; ++j){
            sb.append(arrayA[j]);
        }
        for(int j = i; j < arrayB.length; ++j){
            sb.append(arrayB[j]);
        }            
        System.out.println("o/p="+sb.toString()); 
  }}

从主函数中,我将值传递给 possibleStrings,我试图将此处生成的字符串收集回主函数,用于同一组输入,即 possibleStrings(3, a,"");possibleStrings(2, b,"");,然后将字符串传递给和 b 到 result 函数。

在结果函数中,我试图逐个字符地附加字符串,并获得上述字符串中获得的输出的组合。

但是我得到的输出是错误的。我不知道我哪里出错了。请帮帮我。

【问题讨论】:

  • 那么:到底是什么问题?输出或传递参数?错误是什么?
  • 这里的输出是 0|1& 我需要像 0|0|0 到 0&0&0, 0|0|1 到 0&0&1........最多 1|1| 这样的输出1 到 1&1&1。
  • @Logan 我的问题在这里是不同的这里我想传递 2 个不同的值来函数 possibleStrings,然后想以不同的方式取回答案,以便我可以在函数结果中传递它们。

标签: java arrays string


【解决方案1】:

如果我是正确的,这是将数据传递给函数时的错误:possibleStrings(2, b,""); 将其替换为:possibleStrings(2,'b',"");,因为它是一个我认为应该用单引号括起来的字符。

【讨论】:

  • 不,该方法需要一个 array 字符,而不仅仅是单个字符。变量 b 已经是一个 char 数组,这是预期的实际参数。不是单个字符'b'
猜你喜欢
  • 1970-01-01
  • 2021-10-06
  • 1970-01-01
  • 2022-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多