Печатайте верхний / нижний регистр и переходите от ввода к выводу, используя поток
Я пытаюсь прочитать каждую строку из input.txt
и напечатайте каждую строку, чтобы каждая буква во входной строке стала заглавной, если она строчной, и строчной, если она заглавной. Кроме того, я хотел бы использовать Thread
чтобы сделать это, так как я также хотел бы напечатать обратную сторону каждой строки.
Я получаю ошибку за printUppLow uppLow = new printUppLow();
а также printRev rev = new printRev();
non-static variable this cannot be referenced from a static context.
Код
public static void main(String args[])
{
String inputfileName="input.txt"; // A file with some text in it
String outputfileName="output.txt"; // File created by this program
String oneLine;
try {
// Open the input file
FileReader fr = new FileReader(inputfileName);
BufferedReader br = new BufferedReader(fr);
// Create the output file
FileWriter fw = new FileWriter(outputfileName);
BufferedWriter bw = new BufferedWriter(fw);
printRev rev = new printRev();
printUppLow uppLow = new printUppLow();
rev.start();
uppLow.start();
// Read the first line
oneLine = br.readLine();
while (oneLine != null) { // Until the line is not empty (will be when you reach End of file)
// Print characters from input file
System.out.println(oneLine);
bw.newLine();
// Read next line
oneLine = br.readLine();
}
// Close the streams
br.close();
bw.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
public class printUppLow extends Thread
{
public void run(String str)
{
String result = "";
for (char c : str.toCharArray())
{
if (Character.isUpperCase(c)){
result += Character.toLowerCase(c); // Convert uppercase to lowercase
}
else{
result += Character.toUpperCase(c); // Convert lowercase to uppercase
}
}
return result; // Return the result
}
}
public class printRev extends Thread
{
public void run()
{
StringBuffer a = new StringBuffer("input.txt");
System.out.println(a.reverse());
}
}
2 ответа
Это потому, что вложенные классы printUppLow
а также printRev
не объявлены static
и, следовательно, относительны к экземпляру.
Чтобы решить эту проблему, объявите их вне своего основного класса или добавьте static
Ключевое слово в их декларации.
(Кстати, вы, вероятно, получите жалобы, что вы не называете свои классы заглавными буквами.)
Это пример использования вложенных классов для интерфейса Runnable.
package co.edu.unbosque.jn.in2outtext;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
* @author Alejandro
*/
public class FileManager {
private File toRead;
BufferedReader br;
public FileManager(String fileIN) throws FileNotFoundException {
this.toRead = new File(fileIN);
if (!this.toRead.exists()) {
throw new IllegalArgumentException("File doesn't exist");
}
br = new BufferedReader(new FileReader(toRead));
}
public String reverseUpLowReadLine() throws IOException {
String line = br.readLine();
StringBuilder newSt = new StringBuilder();
if (line != null) {
for (Character c : line.toCharArray()) {
if (Character.isLowerCase(c)) {
newSt.append(Character.toUpperCase(c));
} else {
newSt.append(Character.toLowerCase(c));
}
}
} else {
br.close();
return null;
}
return newSt.toString();
}
public String reverseLine() throws IOException {
String line = br.readLine();
if (line != null) {
StringBuilder sb = new StringBuilder(line);
return sb.reverse().toString();
} else {
br.close();
return null;
}
}
}
================================================== ===========
package co.edu.unbosque.jn.in2outtext;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author Alejandro Leon
*/
public class In2Out {
public static void main(String[] args) {
String inFile = "In.txt";
try {
final FileManager fm = new FileManager(inFile);
Thread t = new Thread(new Runnable() {
@Override
public void run() {
String s = null;
do {
try {
s = fm.reverseLine();
if (s != null) {
System.out.println(s);
}
} catch (IOException ex) {
Logger.getLogger(In2Out.class.getName()).log(Level.SEVERE, null, ex);
}
} while (s != null);
}
});
final FileManager fm2 = new FileManager(inFile);
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
String s = null;
do {
try {
s = fm2.reverseUpLowReadLine();
if (s != null) {
System.out.println(s);
}
} catch (IOException ex) {
Logger.getLogger(In2Out.class.getName()).log(Level.SEVERE, null, ex);
}
} while (s != null);
}
});
t.start();
t2.start();
} catch (FileNotFoundException ex) {
Logger.getLogger(In2Out.class.getName()).log(Level.SEVERE, null, ex);
}
}
}