我不明白这种方法的错误

时间:2014-04-05 19:38:16

标签: java

我正在制作一个加密程序,用户输入一个单词,然后是一个模式,然后拼写这个单词。

这是我的错误:

 1 error found:
  [line: 42]
Error: The method charArray(int) is undefined for the type Cipher

这是我的代码:

import java.util.Scanner;

public class Cipher
{
  public static char cipher (int j){
    char[] cipher1 = {'a','b','c','d','e','f','g'};
  j = (int) (Math.random() * cipher1.length);//choose a random element from the array
    return cipher1[j];
  }

  public static void main (String[] args){

    System.out.print("Please type a sentence to be encrypted\n");
    Scanner inputScanner = new Scanner(System.in);
    String input = inputScanner.next();
      System.out.print("please enter");
   input = input.toLowerCase();
    int yu = input.length();
    char[] charArray = input.toCharArray();

        int w=1;
    do{
    try{
    w=2;
      System.out.println("please entrer pattern");
      String hello = inputScanner.next();
      int hello2= Integer.parseInt(hello);
      if(hello2<0){
        System.out.println("please enter proper number");
        w=1;
      }
    }catch (NumberFormatException f){
      System.out.println("please enter proper number");
    }

    }while (w==1);

    System.out.print("your encrypted code is ");

    for(int i = 0; i < yu; i++){
    System.out.print(charArray(i)); //THIS IS WHERE ERROR IS HIGHLIGHITNG
    for(int q = 0; q <= w; q++){
    System.out.print( cipher(1));
    }
    }
  }
}

3 个答案:

答案 0 :(得分:0)

错误似乎正在发生,因为charArray类中没有名为Cipher的方法。我怀疑你真正想要的是从你之前在代码中定义的名为charArray的数组中获取元素。所以语法应该是charArray[i]来获取索引i的元素。

答案 1 :(得分:0)

是的,这里没有定义charArray(int)方法。

当您使用正在尝试打印charArray[i]时,您不小心写了charArray(i)

不是访问位置i的值,而是尝试执行不存在的方法。只需将()括号更改为[],您就会看到错误消失。

答案 2 :(得分:0)

当你像charArray(i)那样编写它时,它会尝试调用一个名为charArray的方法,将i作为参数传递给它(实际上并未在你的情况下定义)

当您说charArray[i]时,您会理解您想要访问i

charArray元素

所以你需要改变

System.out.print(charArray(i));

System.out.print(charArray[i]);