Я хочу прочитать файл, а также проверить слово, есть ли слово в файле или нет. Если слово присутствует, один из моих методов вернет +1 - PullRequest
0 голосов
/ 10 марта 2019

Это мой код.Я хочу прочитать файл с именем «write.txt», а затем, когда он читает.Сравните это со словом, здесь я использую переменную * target (типа string), как только сравнение будет выполнено внутри метода, называемого findTarget , оно вернет 1 послеусловие истинно. Я пытаюсь вызвать метод, но получаю сообщение об ошибке. test.java: 88: ошибка: не удается найти символ String testing = findTarget (target1, source1); ^ символ: переменная target1 местоположение: ошибка теста класса 1 может кто-то исправить мою ошибку. Я совершенно новичок в программировании.

import java.util.*;
import java.io.*;


public class test {

public static int findTarget( String target, String source ) 
{

int target_len = target.length();
int source_len = source.length();

int add = 0;

for(int i = 0;i < source_len; ++i) // i is an varialbe used to count upto 
source_len.
{
int j = 0; // take another variable to count loops        
    while(add == 0)
    {
        if( j >= target_len ) // count upto target length
        {
            break;
        }
        else if( target.charAt( j ) != source.charAt( i + j ) ) 
        {
            break;
        } 
        else 
        {
            ++j;
            if( j == target_len ) 
            {     
            add++; // this will return 1: true

            }
        }
    }
}
return add;
//System.out.println(""+add);
}
public static void main ( String ... args ) 
{
//String target = "for";
// function 1    
try
{
// read the file
File file = new File("write.txt"); //establising a file object
BufferedReader br = new BufferedReader(new FileReader(file));   
//reading the files from the file object "file"

String target1; 
while ((target1 = br.readLine()) != null) //as long the condition is not null it will keep printing.
System.out.println(target1);

//target.close();
}
catch (IOException e)
  {
     System.out.println("file error!"); 
  }

String source1 = "Searching for a string within a string the hard way.";


// function 2

test ob = new test();

String testing = findTarget(target1, source1);


// end    
//System.out.println(findTarget(target, source));
System.out.println("the answer is: "+testing);


}

}

Ответы [ 2 ]

1 голос
/ 11 марта 2019

Ошибка в том, что findTarget является функцией класса.

Итак, где у вас это:

test ob = new test();

String testing = findTarget(target1, source1);

... должно быть изменено для вызова функции из статического контекста:

//test ob = new test();  not needed, the function is static

int testing = test.findTarget(target1, source1);
// also changed the testing type from String to int, as int IS findTarget's return type.

У меня нет содержимого файла для пробного запуска, но это, по крайней мере, должно помочь устранить ошибку.

===== UPDATE:

Вы близко!

Внутри main измените код в вашем цикле так, чтобы он выглядел так:

String target1;
int testing = 0;  // move and initialize testing here

while ((target1 = br.readLine()) != null) //as long the condition is not null it will keep printing.
{
    //System.out.println(target1);

    testing += test.findTarget(target1, source1);
    //target1 = br.readLine();
}

System.out.println("answer is: "+testing);
0 голосов
/ 11 марта 2019

Я наконец-то смог решить мою проблему.но расширяя функциональные возможности.Я хочу увеличить прибавление на 1., но в моем программировании он выдает мне вывод

ответ: 1 ответ: 1

вместоЯ хочу, чтобы моя программа печатала не две 1, а 1 + 1 = 2

Может кто-нибудь решить эту проблему увеличения?

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;


public class test {
    public static int findTarget(String target, String source) {

        int target_len = target.length();
        int source_len = source.length();

        int add = 0;

        // this function checks the character whether it is present.


        for (int i = 0; i < source_len; ++i) // i is a varialbe used to count upto source_len.
        {

            int j = 0; // take another variable to count loops

            while (add == 0) 
            {
                if (j >= target_len) // count upto target length
                {
                    break;
                } 
                else if (target.charAt(j) != source.charAt(i + j)) 
                {
                    break;
                } 
                else 
                {
                    ++j;
                    if (j == target_len) 
                    {

                        add++; // this will return 1: true

                    }
                }
            }

        }

        return add;
        //System.out.println(""+add);

    }

    public static void main(String... args) {

    //String target = "for";
    // function 1
        try {
            // read the file
            Scanner sc = new Scanner(System.in);

            System.out.println("Enter your review: ");
            String source1 = sc.nextLine();

            //String source1 = "Searching for a string within a string the hard way.";
            File file = new File("write.txt"); //establising a file object
            BufferedReader br = new BufferedReader(new FileReader(file)); //reading the files from the file object "file"

            String target1;
            while ((target1 = br.readLine()) != null) //as long the condition is not null it will keep printing.
            {
                //System.out.println(target1);


                int testing = test.findTarget(target1, source1);
                System.out.println("answer is: "+testing);
                //target1 = br.readLine();
            }

            br.close();
        } 
        catch (IOException e) 
        {
            System.out.println("file error!");
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...