Muszę wiedzieć, co robi mój program. Użyłem innych odpowiedzi na inne pytania, aby załatać ten program Frankensteina.
Inną sprawą jest to, że kod powinien gromadzićliczba znaków w pliku tekstowym i jest to jedna litera, więc nie wiem, co robić.
import java.io.*;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class File_Letter_Counter{
public static void main(String[] args) throws IOException{
//Declare variables.
//Hold fileName variable.
String fileName;
//Set accumulator value.
int accumulator=0;
//Set fileName equal to user input.
fileName=JOptionPane.showInputDialog("Enter the name of a file: ");
//Set letter for file search.
String letter=JOptionPane.showInputDialog("Enter a letter: ");
//Set char variable to string input"s letter.
char character=(Character.toLowerCase(letter.charAt(0)));
//Open file.
File file=new File (fileName);
//Set new scanner object to read file.
Scanner inputFile=new Scanner(file);
//Loop for every line in file.
while (inputFile.hasNext()){
//Set line equal to the next line that is in the file.
String line=inputFile.nextLine();
/*For every time count is less than the number
of characters in the string, repeat the loop.*/
for(int count=0; count<line.length(); count++){
/*if line 1 is equal to lower case "character" variable
*/
if (line.charAt(count)==Character.toLowerCase(character)
||line.charAt(count)==Character.toUpperCase(character)){
count++;
accumulator++;
}
}
}
JOptionPane.showMessageDialog(null, accumulator);
inputFile.close();
}
}
Odpowiedzi:
0 dla odpowiedzi № 1Gdybyś mógł mi powiedzieć, co robi moja instrukcja if, to byłoby wielkie docenione.
if (line.charAt(count)==Character.toLowerCase(character) ||line.charAt(count)==Character.toUpperCase(character))
To, jeśli powyższe stwierdzenie w zasadzie przyjmujeznak pod określonym indeksem w ciągu i sprawdza, czy jest on równy znakowi po prawej stronie. Również w tym procesie, porównywany Znak jest zmieniany odpowiednio na małe i wielkie litery dla równości, ponieważ znak może być Wielkimi lub Małe litery. W końcu ta instrukcja if albo potwierdzi poprawność, jeśli jedno z wyrażeń jest prawdziwe, albo fałszywe, jeśli oba sprawdzą poprawność na false.