I have the following code, which is for an assignment to replace numbers in a text file:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Random;
import java.util.Scanner;
public class L20 {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
System.out.println("Enter file name");
String in = input.nextLine();
try {
textWriter(in);
textReader(in);
textChanger(in);
} catch (Exception e) {
}
}
public static void textWriter(String path) throws IOException {
String[] alphabet = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
"k", "m", "l", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w",
"x", "y", "z" };
File file = new File(path);
Writer output = null;
Random number = new Random();
output = new BufferedWriter(new FileWriter(file));
int lines = 10 + number.nextInt(11);
for (int i = 0; i < lines; i++) {
int it2 = 1 + number.nextInt(9);
int n1 = number.nextInt(26);
int n2 = number.nextInt(26);
int n3 = number.nextInt(26);
String t2 = Integer.toString(it2);
String t1 = alphabet[n1] + alphabet[n2] + alphabet[n3];
String text = t1 + t2;
output.write(text);
((BufferedWriter) output).newLine();
}
output.close();
System.out.println("Your file has been written");
}
public static void textReader(String path) throws IOException {
File file = new File(path);
Scanner input;
input = new Scanner(file);
String line;
while ((line = input.nextLine()) != null) {
System.out.println(line);
}
input.close();
}
}
But unfortunately the code isn't working as it should. The problem portion is shown below:
public static void textChanger(String path) throws IOException {
File file = new File(path);
Scanner input;
input = new Scanner(file);
String line;
Pattern p = Pattern.compile("[0-9]");
while ((line = input.nextLine()) != null) {
Matcher m = p.matcher(line);
int n = Integer.parseInt(m.group());
System.out.println(n);
}
input.close();
}
What I want to do is replace only the number part of each line in the Text.txt file. Each of these lines consists of three letters and one number. I only want to change the number portion.
Try this.............
public class Reg {
public static void main(String[] args){
String s = "abc1";
Pattern p = Pattern.compile("\\d");
Matcher m = p.matcher(s);
String no = new String();
while (m.find()){
no = m.group();
}
String newStr = s.replace(no, "hi");
System.out.println(newStr);
}
}