This question already has answers here:
What is character encoding and why should I bother with it
(4 answers)
Closed 4 years ago.
I wrote the below code in order to read some integers from a text file and then print in a new txt every integer after I added the value ten to each of them. The "-1" int is as a pointer to show the end.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Scanner;
public class SmallChallengeCh {
public static void main(String[] args){
Scanner in = null;
PrintWriter pw = null;
try{
File f = new File("C:\\Users\\paioa\\primlnl.txt");
in = new Scanner(f);
pw = new PrintWriter(new FileOutputStream("C:\\Users\\paioa\\primOut.txt"),true);
int num = in.nextInt();
while(num != -1 ){
num = num + 10;
System.out.print(num + " ");
pw.print(num + " ");
num = in.nextInt();
}
}catch(FileNotFoundException e1){
System.out.println("The file does not exist");
}finally {
try{
if(in != null) in.close(); else throw new Exception("NULL");
if(pw != null) pw.close();else throw new Exception("NULL");
}catch (Exception e){
System.out.println(e.getMessage());
}
}
}
}
However I am getting the below error
**Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at gr.aueb.elearn.ch6.SmallChallengeCh.main(SmallChallengeCh.java:18)
Process finished with exit code 1**
But I cannot understand why. The inputmismatchexception is due to the fact that probably my file doesn't contain ints but that's not true here is the txt.
Input of txt file, also saved with coding UTF-8
Solved
ANSWER: The issue was with coding UTF-8. I should left the file ANSI. I don't know why the example I was reading/exercising on advocated this ..
try this
int num;
while(in.hasNextInt()){
num = in.nextInt();
num = num + 10;
System.out.print(num + " ");
pw.print(num + " ");
}
If you want to read only integers before "-1" you have to do something like
int num;
while(in.hasNextInt()){
num = in.nextInt();
if(num == -1)
break;
num = num + 10;
System.out.print(num + " ");
pw.print(num + " ");
}
Related
I am writing a program that lets the user enter up to 9999 accounts into a text file, however the issue i'm having is that they can be put in any order, but I have to print them in a sequential order. Here's my code
import java.nio.file.*;
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import static java.nio.file.StandardOpenOption.*;
import java.util.Scanner;
import java.text.*;
public class CreateBankFile {
public static int lines = 0;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Path file = Paths.get("/root/sandbox/BankAccounts.txt");
String line = "";
int acctNum = 0;
String lastName;
double bal;
final int QUIT = 9999;
try
{
OutputStream output = new BufferedOutputStream(Files.newOutputStream(file));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
while(acctNum != QUIT)
{
System.out.print("Enter the acct num less than 9999: ");
acctNum = input.nextInt();
if(acctNum == QUIT)
{
continue;
}
System.out.print("Enter a last name: ");
lastName = input.next();
if(lastName.length() != 8)
{
if(lastName.length() > 8)
{
lastName = lastName.substring(0, 8);
}
else if(lastName.length() < 8)
{
int diff = 8 - lastName.length();
for(int i = 0; i < diff; i++)
{
lastName += " ";
}
}
}
System.out.print("Enter balance: ");
bal = input.nextDouble();
line = "ID#" + acctNum + " " + lastName + "$" + bal;
writer.write(line);
writer.newLine();
lines++;
}
writer.close();
}
catch(IOException e)
{
System.out.println("Error");
}
}
}
My question being, how can I get it so that when the user inputs "55" for example, it is printed to the 55th line of the text file?
You can do something like this :
1) create a class that will store your line ( acctNum , lastName .. etc )
2) in your method , create an arraylist of the class you created , for a given number "n" , your method will parse all the lines , if acctNum is less than "n" , you will create a new instance using this line and add it to your arraylist
3) you will sort the arraylist using the acctNum and then print its content
Perhaps FileChannels would work for you:
RandomAccessFile writer = new RandomAccessFile(file, "rw");
FileChannel channel = writer.getChannel();
ByteBuffer buff = ByteBuffer.wrap("Test write".getBytes(StandardCharsets.UTF_8));
channel.write(buff,5);//5 is the distance in the file
Lots of good examples on the web.
In your question I think you are taking acctNum as line number and you want to add a line at this line number in the file so you can do something like this.
List<String> readLines = Files.readAllLines(path, StandardCharsets.UTF_8);
readLines.set(acctNum- 1, data);
Files.write(path, lines, StandardCharsets.UTF_8);
I assumed that you are using Java 7 or higher so I did acctNum-1 because in Java 7 or higher version line number starts with 1 in rest it starts with 0 so you can change to acctNum.
Reference: List set() and NIO
This question already has answers here:
compilation error: identifier expected
(4 answers)
Closed 7 years ago.
Hi i am trying to run a simple Odd even program but its giving me the error "identifier expected" program is as follows:
import.java.io.*;
public class OddevenbufferedReader {
System.output.println("Enter a number to be checked as odd or even: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String args[]) {
int num, output;
num = Integer.parseInt(br.readLine());
output = num % 2;
if (output == 0) {
System.out.println("Entered number is even");
} else {
System.out.println("Entered number is odd");
}
}
}
Remove the . between import and java.io.*;
import java.io.*;
and put the System.output.println and BufferedReader br lines inside your main method.
There are multiple issues with your program
Incorrect syntax for import.
import.java.io.*;
should be
import java.io.*;
System.output should be corrected
System.output.println("Enter a number to be checked as odd or even: ");
should be
System.out.println("Enter a number to be checked as odd or even: ");
Output statement should be present within the method block. And the exception thrown by the buffered reader should be handled i.e. update main method as
main method
public static void main(String args[]) {
System.out.println("Enter a number to be checked as odd or even: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int num, output;
try {
num = Integer.parseInt(br.readLine());
output = num % 2;
if (output == 0) {
System.out.println("Entered number is even");
} else {
System.out.println("Entered number is odd");
}
} catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
}
i tried reading a string from a file and it worked just fine but it won't work with an integer. i can't seem to find the problem
public static void main(String[] args) throws FileNotFoundException {
File in = new File ("FCITsamba.in.rtf");
Scanner scanner = new Scanner(in);// Scanner variable to read from the input file
File outFile = new File("FCITsamba.txt");// the out file
PrintWriter out = new PrintWriter(outFile); // Printwriter to write to the file
int maxAccounts = 0;//maximum number of accounts that can be in the bank
int maxTransactions = 0;//maximum number of transactions in a given day
int accNum = 0;
int transNum = 0;
int d = 0;
int k = 0;
int dayNo = 1;
if (!in.exists()) {
System.out.println("Input file, " + in + ", does not exist.");
System.exit(0);
}
maxAccounts = scanner.nextInt();
maxTransactions = scanner.nextInt();
d = scanner.nextInt(); //representing the number of days for the simulation
k = scanner.nextInt();
it gives me this error:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at fcitsamba.FCITsamba.main(FCITsamba.java:43)
Java Result: 1
i tried putting an inputMismatchException but it didn't work i also tried putting it in an if statement as shown below:
if(scanner.hasNextInt()){
maxAccounts = scanner.nextInt();
maxTransactions = scanner.nextInt();
d = scanner.nextInt(); //representing the number of days for the simulation
k = scanner.nextInt();
}
but it didn't work as well
this is the input File :
200
10000
2
11
OPENACCOUNT 1485 Aslam Saeed 2000.0
DEPOSIT 1485 1000.0
...
When you read from a file, it won't recognize whether it is reading numbers or strings, hence everything will be treated as strings including what is shown in your data file (200, 10000, 2, 11).
Instead of writing:
d = scanner.nextInt();
Try this:
d = Integer.parseInt(scanner.nextLine());
Scanner reads 1 value at a time, so if the next value you are trying to read is not an int it will throw an error.
I used your data and the following worked for me:
public static void main(String[] args) {
//Replace FILE_PATH with your file path.
try {
Scanner reader = new Scanner(new File("FILE_PATH/fromFile.txt"));
PrintWriter writer = new PrintWriter(new File("FILE_PATH/toFile.txt"));
int maxAccounts = reader.nextInt();
int maxTransactions = reader.nextInt();
int d = reader.nextInt();
int k = reader.nextInt();
writer.println("maxAccounts: " + maxAccounts);
writer.println("maxTransactions: " + maxTransactions);
writer.println("d: " + d);
writer.println("k: " + k);
writer.close();
reader.close();
} catch (FileNotFoundException ex) {
System.out.println("Error: " + ex.getMessage());
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I have a problem with where I am getting a NullPointerException on line 59 of my code.
The program's purpose is to prompt the user for the file location (which has the digits of PI). The program should then accept any number of digits (say k digits) via the Scanner class. Then, the program must read k digits of PI from the file. Using the Scanner class, the program should then obtain a number for 0-9 from a user and print the first and last position in which it appears and also the number of times it appears. Only digits after the decimal point are to be considered. The program should be able to accept 100,000 digits of PI.
The sample output of the code is below:
Give the location of the file:
C:\Users\Joe\Desktop\pi.txt
Number of digits of PI to parse:
10
Give any number between 0-9:
1
1 appears 2 times
First position in which appears: 1
Last position in which appears: 3
Any help would be much appreciated.
Below is my code:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
import java.util.ArrayList;
public class Problem2 {
#SuppressWarnings("null")
public static void main(String[] args) throws Exception {
FileInputStream inputstream = null;
BufferedReader reader = null;
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
try {
System.out.println("Give the location of the file (example: C:\\Users\\Joe\\Desktop\\pi.txt):");
String fileloc = input.nextLine();
inputstream = new FileInputStream(fileloc);
reader = new BufferedReader(new InputStreamReader(inputstream));
String stringinput;
System.out.println("Number of digits of PI to parse: ");
int parsenum = input.nextInt() + 2;
String[] stringarray = new String[parsenum];
while((stringinput = reader.readLine()) != null) {
stringinput = stringinput.substring(2, parsenum);
for(int i = 0; i < stringinput.length(); i++) {
stringarray = stringinput.split("");
}
}
System.out.println("Give any number between 0-9: ");
String searchnum = input.next();
int count = 0;
for(int i = 1; i < parsenum - 1; i++) {
if(searchnum == stringarray[i]) {
count++;
}
else count++;
}
System.out.println(searchnum + " appears " + count + " time(s)");
for(int i = 1; i < parsenum - 1; i++) {
System.out.print(stringarray[i]);
}
System.out.println();
System.out.println("First position in which " + searchnum + " appears: " + stringinput.indexOf(searchnum));
System.out.println("Second position in which " + searchnum + " appears: " + stringinput.lastIndexOf(searchnum));
}
catch (FileNotFoundException exception) {
System.err.println("File not found, please try again");
main(null);
}
catch (Exception e) {
System.err.println("Invalid input entered");
e.printStackTrace();
System.exit(0);
}
finally {
reader.close();
}
}
}
while((stringinput = reader.readLine()) != null)
The above while loop will run untill reader.readLine is null and so will be stringinput.
Now after the while loop your using stringinput:
stringinput.indexOf(searchnum)
stringinput.lastIndexOf(searchnum)
and thus getting the NullPointerException.
I am currently trying to create a Java program that allows a scanner to read 100 integers from a .txt file and then for the program to output the average of the 100 numbers. It must also check for errors whilst reading from the code. E.G (there is a letter in .txt file, instead of an integer).
Here is the code I have so far:
package NumFile;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Scanner;
public class NumFile {
public static void main (String [] args) throws FileNotFoundException {
try {
int counter = 0; // Counter for number of numbers in the txt file
double sum = 0; // Sum of all digits in the txt file
String line = null; // The line that is read in the txt file
Scanner userIn = new Scanner(System.in);
System.out.println("Type the name of the file located");
String fileName = userIn.nextLine();
BufferedReader in = new BufferedReader(new FileReader(Workbook1.txt));
Object input;
while(in.hasNextLine() && !((input = in.nextLine()).equals(""))) {
counter++;
sum += Double.parseDouble(line);
}
double average = sum/counter;
System.out.println("The average of the numbers is: " + format(average));
System.out.println("The sum of the numbers is: " + sum);
System.out.println("The number of digits is " + counter);
}
catch (IOException e) {
System.out.println("Input/Output exception");
}
}
public static String format(double number) {
DecimalFormat d = new DecimalFormat("0.00");
return d.format(number);
}
}
With this code, I am having a few errors.
Here are the errors that display:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Workbook1 cannot be resolved to a variable
The method hasNextLine() is undefined for the type BufferedReader
The method nextLine() is undefined for the type BufferedReader
at NumFile.NumFile.main(NumFile.java:27)
If I remove:
Object input;
// Loop until the end of the file
while(in.hasNextLine() && !((input = in.nextLine()).equals(""))){
then the program starts to run, however it cannot find the .txt file containing the integers!
You can do something like this:
Scanner in = new Scanner(new File(fileName));
String input = "";
while(in.hasNextLine() && !((input = in.nextLine()).equals(""))) {
//code here
}