简体   繁体   English

变量的原始类型在编译期间没有字段x

[英]The primitive type of a variable does not have a field x during compilation

I wrote a java program to compare two strings and at the time of compilation I am getting the error: The primitive type int of length1 does not have a field j Syntax error on token ",", . 我编写了一个Java程序来比较两个字符串,并且在编译时遇到了错误:length1的原始类型int没有字段j语法错误,标记为“,”,。 expected 预期

Here is my program: 这是我的程序:

import java.util.*;

public class StringCompare {
    public static void main(String args[]){
        String str1, str2;
        int i,j, flag=0;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the first string \n");
        str1=sc.nextLine();
        System.out.println("Enter the next string \n");
        str2=sc.nextLine();
        int length1=str1.length();
        int length2=str2.length();
        if(length1!=length2){
            System.out.println("The strings are not equal");
        }
        else
        {
            for(i=1,j=1;i<=length1, j<=length2;i++,j++){
                if(str1.charAt(i)!=str2.charAt(j)){
                    flag=1;
                    break;
                }
            }
            if(flag==0)
                System.out.println("The strings are equal \n");
            else
                System.out.println("The strings are not equal \n");
        }
    }
}

You cannot have a comma-seperated list of conditions in the middle of your for loop. for循环的中间不能有逗号分隔的条件列表。 You must have an expression that evaluates to true or false only. 您必须具有一个仅计算为truefalse的表达式。

You are free to have a comma-seperated list of initialization statements in the first part of your for loop, which is probably what you were thinking. 您可以自由地在for循环的第一部分中以逗号分隔的初始化语句列表,这可能正是您所想的。

Read here for more: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html 在此处阅读更多信息: https : //docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html

Because length1 and length2 has the same value in the for loop you only need the i variable. 因为length1和length2在for循环中具有相同的值,所以您只需要i变量。 Simplify it to be like: 简化为:

for (i = 0; i < length1; i++){
    if(str1.charAt(i) != str2.charAt(i)){
        flag = 1;
        break;
    }
}

EDIT: you also have a bug in your code. 编辑:您的代码中也有一个错误。 Lets say your strings length is 3 and your loop goes from 1 to 3, when str1.charAt(3) is called (i==3) it will crash. 假设您的字符串长度为3,循环从1变为3,当调用str1.charAt(3)(i == 3)时它将崩溃。 You need to start from 0 and stop to 2 (i < length1). 您需要从0开始并停止到2(i <length1)。

The reason for string index of of range error at for for (i = 0; i < length1; i++) is that the compiler is trying to access a point in the string which does not exist. for for (i = 0; i < length1; i++)的范围错误的字符串索引的原因是,编译器试图访问字符串中不存在的点。 It should be for(i=1;i<=length1-1;i++) 应该是for(i=1;i<=length1-1;i++)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM