After entering file to be processed the command line jumps to next line but remains blank, as opposed to printing the desired array. I want to call the getInputScanner() method to produce the scanner that accesses the file, after the file is entered by the user the command line jumps to the next line, as opposed to processing any of the text. Any ideas why?
import java.util.*;
import java.awt.*;
import java.io.*;
public class Test {
public static void main(String [] args) {
Scanner console = new Scanner(System.in);
Scanner input = getInputScanner(console);
System.out.println("{" + nameArr(input) + "}");
}
public static Scanner getInputScanner(Scanner console) {
System.out.print("Please enter a file to process: ");
File file = new File(console.next());
while (!file.exists()) {
System.out.print("\nFile does not exists.\nPlease enter a new file name: ");
file = new File(console.next());
}
try {
Scanner fileScanner = new Scanner(file);
return fileScanner;
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
return null;
}
public static String [] nameArr(Scanner input) {
int count = 0;
while (input.hasNextLine()) {
count++;
}
String [] nameArray = new String[count];
while (input.hasNextLine()) {
String line = input.nextLine();
for (int i = 0; i < nameArray.length; i++) {
nameArray[i] = lineProcess(input.nextLine());
}
}
return nameArray;
}
public static String lineProcess(String line) {
Scanner lineScan = new Scanner(line);
String line2 = lineScan.nextLine();
String lineString[] = line2.split(" ");
String name = lineString[0];
return name;
}
}
You've and infinite loop since you're not advancing the scanner calling input.nextLine():
while (input.hasNextLine()) {
count++;
}
I see other parts of the code which I'm thing that are wrong, try using java.util.List instead of array to collect the names in the lines of your processed file:
import java.util.*;
import java.io.*;
public class Test {
public static void main(String [] args) {
Scanner console = new Scanner(System.in);
Scanner input = getInputScanner(console);
List<String> nameList = nameArr(input);
for(String name : nameList){
System.out.println("{ "+ name + " } ");
}
}
public static Scanner getInputScanner(Scanner console) {
System.out.print("Please enter a file to process: ");
File file = new File(console.next());
while (!file.exists()) {
System.out.print("\nFile does not exists.\nPlease enter a new file name: ");
file = new File(console.next());
}
try {
Scanner fileScanner = new Scanner(file);
return fileScanner;
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
return null;
}
public static List<String> nameArr(Scanner input) {
List<String> nameList = new ArrayList<String>();
while (input.hasNextLine()) {
nameList.add(lineProcess(input.nextLine()));
}
return nameList;
}
public static String lineProcess(String line) {
return line.split(" ")[0];
}
}
Related
I read the information in a .txt file and now I would like to store the lines of information from the text into a String Array or a variable.
The information in the .txt file is as given:
Onesimus, Andrea
BAYV
Twendi, Meghan
RHHS
Threesten, Heidi
MDHS
I want to store BAYV, RHHS, MDHS into a different array from the names.
import java.io.File;
import java.util.Scanner;
class testing2 {
public static void main(String [] args) throws Exception {
File Bayviewcamp = new File ("H:\\Profile\\Desktop\\ICS3U\\Bayviewland Camp\\Studentinfo.txt");
Scanner scanner = new Scanner (Bayviewcamp);
while (scanner.hasNextLine())
System.out.println(scanner.nextLine());
Check whether names matches with the regex "[A-Z]+"
List<String> upperCaseList = new ArrayList<>();
List<String> lowerCaseList = new ArrayList<>();
while (scanner.hasNextLine()) {
String[] names = scanner.nextLine().split(",");
for(String name:names) {
if(name.matches("[A-Z]+")) {
upperCaseList.add(name);
}
else {
lowerCaseList.add(name);
}
}
}
As per your example, some of the names has leading spaces. you may have to trim those spaces before you compare with the regex
for(String name:names) {
if(name.trim().matches("[A-Z]+")) {
upperCaseList.add(name.trim());
}
else {
lowerCaseList.add(name.trim());
}
}
Below code has few restrictions like:
There must be format that you said (name and next line value)
Array size is 100 by default but you can change as you want
By name I mean one line: (Onesimus, Andrea) it's under first index in names array.
private static final int ARRAY_LENGTH = 100;
public static void main(String[] args) throws FileNotFoundException {
boolean isValue = false;
File txt = new File("file.txt");
Scanner scanner = new Scanner(txt);
String[] names = new String[ARRAY_LENGTH];
String[] values = new String[ARRAY_LENGTH];
int lineNumber = 0;
while (scanner.hasNextLine()) {
if (isValue) {
values[lineNumber / 2] = scanner.nextLine();
} else {
names[lineNumber / 2] = scanner.nextLine();
}
isValue = !isValue;
lineNumber++;
}
for (int i = 0; i < ARRAY_LENGTH; i++) {
System.out.println(names[i]);
System.out.println(values[i]);
}
}
Below code return separated names:
private static final int ARRAY_LENGTH = 100;
public static void main(String[] args) throws FileNotFoundException {
boolean isValue = false;
File txt = new File("file.txt");
Scanner scanner = new Scanner(txt);
String[] names = new String[ARRAY_LENGTH];
String[] values = new String[ARRAY_LENGTH];
int namesNumber = 0;
int valuesNumber = 0;
while (scanner.hasNextLine()) {
if (!isValue) {
String tempArrayNames[] = scanner.nextLine().split(",");
values[valuesNumber++] = tempArrayNames[0].trim();
values[valuesNumber++] = tempArrayNames[1].trim();
} else {
names[namesNumber++] = scanner.nextLine();
}
isValue = !isValue;
}
}
A folder contains number of text files like a.txt, b.txt, c.txt like that more than 30 files I need to search a particular string in the all files the output should come as follows:
a.txt contains your entered string
20
b.txt contains you entered string
30
And so on...
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter String");
String input = sc.nextLine();
double count = 0, countBuffer = 0, countLine = 0;
String lineNumber = ".txt";
File folder = new File("C://Users//Desktop//Santhosh.txt");
BufferedReader br;
String line = " ";
try {
br = new BufferedReader(new FileReader(folder));
try {
while ((line = br.readLine()) != null) {
countLine++;
//System.out.println(line);
String[] words = line.split(" ");
for (String word : words) {
if (word.equals(input)) {
count++;
countBuffer++;
}
}
#santhosh I think you want to search a text in files and count the occurrence of word according to file here is the program that do this:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
public class TextSearch {
File file;
FileReader reader;
BufferedReader buffReader;
String word;
Scanner scanner;
Map<String, Integer> counter = new TreeMap<String, Integer>();
public TextSearch() {
file = new File("D:\\Backup\\NP\\GN");// This Contain the 30 files
scanner = new Scanner(System.in);
System.out.println("Enter a word");
word = scanner.nextLine();
File[] listOfFiles = file.listFiles();
startSearch(listOfFiles);
Iterator<String> iterator = counter.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
System.out.println(key + " contain this word " + word + " " + counter.get(key) + "times");
}
}
public void startSearch(File[] list) {
for (int i = 0; i < list.length; i++) {
if (list[i].isFile()) {
try {
reader = new FileReader(list[i]);
buffReader = new BufferedReader(reader);
String line = "";
while ((line = buffReader.readLine()) != null) {
if (line.contains(word)) {
if (counter.containsKey(list[i].getName())) {
Integer count = counter.get(list[i].getName());
count++;
counter.put(list[i].getName(), count);
} else {
counter.put(list[i].getName(), 1);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public static void main(String args[]) {
new TextSearch();
}
}
import java.util.*;
import java.io.*;
public class Events{
File output = new File ("chinese.txt");
static ArrayList <Event> events = new ArrayList <Event>();
public static void main(String[]args){
try{
Scanner sc = new Scanner(new File("events.txt"));
File output = new File("chinese.txt");
PrintWriter printer = new PrintWriter(output);
while(sc.hasNext()){
//String temp = sc.nextLine();
//System.out.println(temp);
int num = sc.nextInt();
String desc = sc.nextLine();
events.add(new Event(num,desc));
}
//break;
}
catch(Exception e){
System.out.println("Invalid file");
}
Collections.sort(events);
for(int i = 0; i<events.size();i++){
System.out.println(events.get(i));
printer.println(events.get(i).toString());
}
`}
}'
I create a printer object and a new file object to print the contents of an arraylist but inside my for loop it can't find the symbol and I have tried everything to fix it with no luck.
printer is declared inside the try block but you are trying to use it outside it. Include the for loop within the try block and it should solve your problem
import java.util.*;
import java.io.*;
public class Events{
File output = new File ("chinese.txt");
static ArrayList <Event> events = new ArrayList <Event>();
public static void main(String[]args){
try{
Scanner sc = new Scanner(new File("events.txt"));
File output = new File("chinese.txt");
PrintWriter printer = new PrintWriter(output);
while(sc.hasNext()){
//String temp = sc.nextLine();
//System.out.println(temp);
int num = sc.nextInt();
String desc = sc.nextLine();
events.add(new Event(num,desc));
}
//break;
Collections.sort(events);
for(int i = 0; i<events.size();i++){
System.out.println(events.get(i));
printer.println(events.get(i).toString());
}
}
catch(Exception e){
System.out.println("Invalid file");
}
}
}
You need to declare printer before the try block, otherwise the scope of printer is limited to the try block. This will fix it:
public static void main(String[]args){
PrintWriter printer = null;
try{
Scanner sc = new Scanner(new File("events.txt"));
File output = new File("chinese.txt");
printer = new PrintWriter(output);
while(sc.hasNext()){
//String temp = sc.nextLine();
//System.out.println(temp);
int num = sc.nextInt();
String desc = sc.nextLine();
events.add(new Event(num,desc));
}
//break;
}
catch(Exception e){
System.out.println("Invalid file");
}
Collections.sort(events);
for(int i = 0; i<events.size();i++){
System.out.println(events.get(i));
printer.println(events.get(i).toString());
}
}
I am really stuck here, I can't seem to read in the arrays properly.
I can't seem to read in these arrays into columns. Looking for a solution to help me finally make an array out of these numbers.
public class TextFileInputAndOutput
{
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("USStateCapitalsSelected.txt"));
int lineCounter = 1;
String line;
while ((line = reader.readLine()) != null) {
// parse line using any method.
// example 1:
Scanner intScanner = new Scanner(line);
while (intScanner.hasNextLine()) {
String nextInt = intScanner.nextLine();
System.out.println(nextInt + "Herro");
if (intScanner.hasNextDouble() == true) {
Scanner scanner = new Scanner(line);
while (scanner.hasNextDouble()) {
String nextString = scanner.next();
System.out.println(nextString);
}
}
}
}
}
}
You can use com.google.common.io.Files:
Sample.txt:
nameA labA quizeA
nameB labB quizeB
Code:
public static void main(String[] args) throws Exception {
File myFile = new File("Sample.txt");
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> labs = new ArrayList<String>();
ArrayList<String> quizes = new ArrayList<String>();
for (String line : Files.readLines(myFile, Charset.defaultCharset())) {
String[] cols = line.split(" ");
names.add(cols[0]);
labs.add(cols[1]);
quizes.add(cols[2]);
}
System.out.println(names);
System.out.println(labs);
System.out.println(quizes);
}
Tryb this
try{
File file = new File("filename");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] temp = line.split(" ");
//add values to arraylist
names.add(temp[0]);
labs.add(temp[1]);
quizes.add(temp[2]);
}
}catch (Exception ex) {
ex.printStackTrace();
}
So, what am I trying to do is I get the info from a text file,
For example, 134567H;Gabriel;24/12/1994;67;78;89
Then I display only Admin number which is the first one but not the whole line in drop down list. So here are my codes :
public static String[] readFile(){
String file = "output.txt";
ArrayList <String> studentList = new ArrayList <String> ();
try{
FileReader fr = new FileReader(file);
Scanner sc = new Scanner(fr);
sc.useDelimiter(";");
while(sc.hasNextLine()){
studentList.add(sc.nextLine());
}
fr.close();
}catch(FileNotFoundException exception){
System.out.println("File " + file + " was not found");
}catch(IOException exception){
System.out.println(exception);
}
return studentList.toArray(new String[studentList.size()]);
}
And this is how I populate the drop down list :
public void populate() {
String [] studentList ;
studentList = Question3ReadFile.readFile();
jComboBox_adminNo.removeAllItems();
for (String str : studentList) {
jComboBox_adminNo.addItem(str);
}
}
However, my problem now is the options in drop down list is showing the whole line from the text file. It is not showing the admin number only. I tried with useDelimiter already. Am I supposed to use that?
Any help would be appreciated. Thanks in advance.
Rince help check.
public class Question3ReadFile extends Question3 {
private String adminNo;
public Question3ReadFile(String data) {
String[] tokens = data.split(";");
this.adminNo = tokens[0];
}
public static String[] readFile(){
String file = "output.txt";
ArrayList <String> studentList = new ArrayList <String> ();
try{
FileReader fr = new FileReader(file);
Scanner sc = new Scanner(fr);
while(sc.hasNextLine()){
studentList.add(new Question3ReadFile(sc.nextLine()));
}
fr.close();
}catch(FileNotFoundException exception){
System.out.println("File " + file + " was not found");
}catch(IOException exception){
System.out.println(exception);
}
return studentList.toArray(new String[studentList.size()]);
}
hasNext and next instead of hasNextLine and nextLine
public static void main(String[] args) {
String input = " For example, 134567H;Gabriel;24/12/1994;67;78;89";
Scanner scanner = new Scanner(input);
scanner.useDelimiter(";");
String firstPart = null;
while(scanner.hasNext()){
firstPart = scanner.next();
break;
}
String secondPart = input.split(firstPart)[1].substring(1);
System.out.println(firstPart);
System.out.println(secondPart);
scanner.close();
}
Don't use delimiter in this case. I suggest to make a Student object out of the line.
studentList.add(new Student(sc.nextLine));
and have the Student class:
public class Student {
private final String adminNo;
public Student(String data) {
String[] tokens = data.split(";");
this.adminNo = tokens[0];
}
public String getAdminNo() {
return adminNo;
}
}
and then you just read the fields you need later (student.getAdminNo()) for example.
This approach is much prettier and easier to extend later.
upd: simplistic approach
Or don't bother with stupid OO and just do this:
studentList.add(sc.nextLine.split(";")[0]);