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());
}
}
Related
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 1 year ago.
import java.io.IOException;
import java.io.File;
import java.nio.file.Path;
import java.util.Scanner;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.NoSuchElementException;
public class filehandling{
public static void main(String[] args){
Scanner x = new Scanner(System.in);
while(true){
System.out.println("1. write 2. read 3. delete 4. create 5.exit");
System.out.print("Enter choice: ");
int ch = x.nextInt();
if(ch==1){
writer1 var0 = new writer1();
var0.function1();
}
if(ch==2){
reader1 var0 = new reader1();
var0.function2();
}
if(ch==3){
delete1 var0 = new delete1();
var0.function4();
}
if(ch==4){
create1 var0 = new create1();
var0.function3();
}
if(ch==5){
System.out.println("exited, thank you for using program");
x.close();
break;
}
}
}
}
class writer1{
void function1(){
Scanner y = new Scanner(System.in);
System.out.print("Input file name: ");
String path = y.nextLine();
File file = new File("D:\\"+path);
System.out.print("input number of lines: ");
Scanner a = new Scanner(System.in);
int n = a.nextInt();
Scanner z = new Scanner(System.in);
System.out.print("input data: ");
String data = z.nextLine();
FileWriter fr = null;
BufferedWriter br = null;
String datawithnewline = data+System.getProperty("line.separator");
System.out.println(datawithnewline);
try {
for(int i = n; i>0;i--){
try {
fr = new FileWriter(file);
br = new BufferedWriter(fr);
br.write(datawithnewline);
} catch (NoSuchElementException e) {
System.out.println("DONE ");
}
}
} catch (IOException e) {
System.out.print("error");
}
finally{
try{
br.close();
fr.close();
y.close();
z.close();
a.close();
}
catch(IOException e){
System.out.print("Error 2");
}
}
}
}
class reader1{
void function2(){
Scanner y = new Scanner(System.in);
System.out.print("Input file name: ");
String path = y.nextLine();
File file = new File("C:\\Users\\subra\\AppData\\Local\\Temp\\vscodesws_32946\\jdt_ws\\jdt.ls-java-project\\src"+path);
if(file.canRead()){
FileReader fr = null;
BufferedReader br = null;
try{
fr = new FileReader(path);
br = new BufferedReader(fr);
int var = 0;
while(( var=br.read())!= -1){
char text = (char) var;
System.out.print(text);
}
}
catch(IOException e){
System.out.println("Error");
}
finally{
y.close();
if (fr !=null){
try{
fr.close();
}
catch(IOException e){
System.out.println("Error");
}
}
if(br!=null){
try{
br.close();
}
catch(IOException e){
System.out.println("Error");
}
}
}
}
}
}
class create1{
public void function3(){
Scanner var1 = new Scanner(System.in);
System.out.print("Input file name: ");
String var2 = var1.nextLine();
File file = new File("D:\\"+var2);
try {
boolean createNewfile = file.createNewFile();
System.out.println("File created: "+createNewfile);
} catch (IOException e) {
System.out.println("Error");
var1.close();
}
}
}
class delete1{
public void function4(){
Scanner y = new Scanner(System.in);
System.out.print("Input file name");
String path = y.nextLine();
Path path1 = Path.of(path);
String path2 = path1.toString();
File file = new File(path2);
if(file.canRead()){
boolean delete = file.delete();
System.out.println("DELETED FILE: "+delete);
}
y.close();
}
}
every time I run this program, it always returns this error, I am actually studying file handling in java so I used this website, I am using visual studio code, I have tried putting br.write(...) part in a try and catch block inside the for loop in writer1 class,
the total interaction in the terminal is
PS C:\Users\subra\AppData\Local\Temp\vscodesws_32946\jdt_ws\jdt.ls-java-project\src> c:; cd 'c:\Users\subra\AppData\Local\Temp\vscodesws_32946\jdt_ws\jdt.ls-java-project\src'; & 'c:\Users\subra\.vscode\extensions\vscjava.vscode-java-debug-0.36.0\scripts\launcher.bat' 'C:\Program Files\Java\jdk-16.0.2\bin\java.exe' '-agentlib:jdwp=transport=dt_socket,server=n,suspend=y,address=localhost:50835' '--enable-preview' '-XX:+ShowCodeDetailsInExceptionMessages' '-Dfile.encoding=UTF-8' '-cp' 'C:\Users\subra\AppData\Roaming\Code\User\workspaceStorage\3543e469db802eccea9e87de0109e000\redhat.java\jdt_ws\src_c37eea88\bin' 'filehandling'
1. write 2. read 3. delete 4. create 5.exit
Enter choice: 1
Input file name: hi
input number of lines: 5
input data: i love coding
i love coding
1. write 2. read 3. delete 4. create 5.exit
Enter choice: Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at filehandling.main(filehandling.java:16)
what should I do??
You only should be using one Scanner across all your classes, and only closing it once
Using an example from only one of your classes (classes should be capitalized, and generally don't use numbers)
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Reader reader = new Reader(sc); // your class. Don't close the Scanner in it
int ch = -1;
while (ch !=5) {
ch = sc.nextInt();
if (ch == 2) {
reader.read();
}
}
sc.close(); // only done once
}
Then update the classes to add a constructor
class Reader {
private Scanner sc;
public Reader(Scanner scanner) {
this.sc = scanner;
}
public void read() {
String filepath = sc.readLine();
...
}
it's showing null exception. what to do now?
import java.io.File;
import java.util.Scanner;
public class Quiz1 {
public static void main(String[] args) {
File f = new File("QuizMark.txt");
try{
Scanner s = new Scanner (f);
QuizMark[] p = new QuizMark[10];
while(s.hasNext()==true)
{
int c = s.nextInt();
double d = s.nextInt();
for(int i=0;i<10;i++){
p[i]= new QuizMark(c,d);
System.out.println(p[i].getId());
System.out.println(p[i].getScore());
i++;
}
}
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
}
First of all your file must define a pattern of data saved in it like marks and id Separated by commas or hyphens underscores etc whatever you like to save pattern.Each next data should be on next line.Then read the text in proper manner as you saved in file.
Example QuizMarks.txt
01,96.5
02,78.9
03,65
04,89.7
Java Code
int count = 0;
String s[];
String line="";
QuizMark[] p = new QuizMark[10];
BufferedReader br= new BufferedReader(new FileReader("QuizMark.txt"));
while(line=br.readLine()!=null){
s=line.split(",");//your data separated by symbol in file
//First Record with id and marks
int id =Interger.parseInt(s[0]); //conversion from string to int
double marks = Double.parseDouble(s[1]); //conversion from string to double
p[count]= new QuizMark(id,marks);
count++;
}
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();
}
I have a text file and i am trying to convert every line into an ArrayList. Then i have to take a random line from this text.file and display it on new JOptionPane.
I am trying to implement it in the for-loop but it always appears only the first line from my text.file. Thank you very much and here is my code.
public void actionPerformed(ActionEvent e) {
ArrayList<String> allQuestions = new ArrayList<String>();
ArrayList<String> allRandomSelectedQuestions = new ArrayList<String>();
File file = new File("C:/Users/User/Documents/NetBeansProjects/SummerExamProject/src/Questions2.txt");
int numberOfRandomQuestions = 16;
try {
//Read line by line from the file
Scanner scan = new Scanner(file);
while (scan.hasNextLine()) {
String line = scan.nextLine();
// System.out.println(line);
JOptionPane.showMessageDialog(null, line.replace("/", "\n"));
scan.close();
allQuestions.add(line);
}
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
for(int i = 0; i < numberOfRandomQuestions; i++){
Random randNum = new Random();
int randQuestionIndex = randNum.nextInt(numberOfRandomQuestions);
String randomQuestion = allQuestions.get(randQuestionIndex);
allRandomSelectedQuestions.add(randomQuestion);
}
}
This line...
scan.close();
Is inside your while loop, so it closes the file after reading a line the first time it goes through the loop.
Moving it to after the loop (i.e. after the close culry-brace) ought to fix it.
The problem is this: scan.close();. You are closing your scanner in the same loop you are using for reading. Moving it outside the loop body should solve the problem.
Call close method after the while loop. What is happening that, you close after the first line. so the while loop stops after only one time.
while (scan.hasNextLine()) {
String line = scan.nextLine();
//System.out.println(line);
JOptionPane.showMessageDialog(null, line.replace("/", "\n"));
allQuestions.add(line);
}
scan.close();
Try this. Hope it helps.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class StackTest {
public static void main(String[] args) {
actionPerformed();
}
public static void actionPerformed() {
ArrayList<String> allQuestions = new ArrayList<String>();
File file = new File("D:/me/test.txt");
int numberOfRandomQuestions = 10;
try {
// Read line by line from the file
Scanner scan = new Scanner(file);
while (scan.hasNextLine()) {
String line = scan.nextLine();
allQuestions.add(line);
}
scan.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
for (int i = 0; i < numberOfRandomQuestions; i++) {
Random randNum = new Random();
int randQuestionIndex = randNum.nextInt(numberOfRandomQuestions);
System.out.println();
String randomQuestion = allQuestions.get(randQuestionIndex);
JOptionPane.showMessageDialog(null, randomQuestion.replace("/", "\n"));
}
}
}
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];
}
}