Here's my code:
public static void main(String[] args) throws IOException {
writeToFile ("c:\\scores.txt");
processFile("c:\\scores.txt");
}
public static void writeToFile (String filename) throws IOException {
BufferedWriter outputWriter = new BufferedWriter(new FileWriter(filename));
Scanner reader = new Scanner (System.in);
int Num;
System.out.println ("Please enter 7 scores");
for (int i = 0; i < 7; i++) {
Num= reader.nextInt ();
outputWriter.write(Num);
if(i!=6) {
outputWriter.newLine();
}
}
outputWriter.flush();
outputWriter.close();
}
public static void processFile (String filename) throws IOException, FileNotFoundException
{
double sum=0.00;
double number;
double average;
int count = 0;
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream(filename)));
String line;
while((line = inputReader.readLine()) != null)
{
number= Double.parseDouble(line);
System.out.println(number);
count ++;
sum += (number);
System.out.print ("Total Sum: ");
System.out.println(sum);
System.out.print("Average of Scores: ");
average=sum/count;
System.out.println(average);
}
inputReader.close();
}
This is what my output is.
Please enter 7 scores
2
3
5
6
8
9
1
Exception in thread "main" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1011)
at java.lang.Double.parseDouble(Double.java:540)
at writefile.Writefile.processFile(Writefile.java:52)
at writefile.Writefile.main(Writefile.java:19)
Java Result: 1
I do not know how to fix this. I'm not sure how to fiz the floating decimal or empty string error.The file has weird symbols in it, no integers. How do I fix this? Please be specific please as I'm only a beginner at Java.
outputWriter.write(1); does not mean outputWriter.write("1");
you need change outputWriter.write(Num); to outputWriter.write(""+Num);
please refer outputstream.write(int)
The error happens because line is an empty string at some point, test for this before parsing the string:
while ((line = inputReader.readLine()) != null) {
if (line.trim().length() > 0) {
number = Double.parseDouble(line);
// rest of loop
}
}
That is, assuming that the line contains only numbers. If there are other characters, you'll have to perform a more careful validation before parsing the line.
The file has weird symbols in it, no integers.
From BufferedWriter#write(int):
Writes a single character.
So it's not writing the int value you're sending to it, instead its character representation.
It would be better if you just write the numeric value as String and then retrieve it as String and parse it. In your writeToFile method, modify this part
for (int i = 0; i < 7; i++) {
Num = reader.nextInt ();
outputWriter.write(Integer.toString(Num));
if(i!=6) {
outputWriter.newLine();
}
}
Related
I'm having trouble with one of my homework problems, I think i've done everything right up until the last part which is to call the method and write the method to the output file. Here is the assignment:
Write a method isPrime which takes a number and determines whether the
number is prime or not. It returns a Boolean.
Write a main method that asks the user for an input file that contains
numbers and an output file name where it will write the prime numbers
to.
Main opens the input file and calls isPrime on each number. Main
writes the prime numbers to the output file.
Modify main to throw the appropriate exceptions for working with
files.
I've tried several different ways to write the method with the output file but I'm not sure exactly how to do it.
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the name of the input file?");
String inputfile = keyboard.nextLine();
File f = new File(inputfile);
System.out.println("What is the name of the output file?");
String outputfile = keyboard.nextLine();
Scanner inputFile = new Scanner(f);
FileWriter fw = new FileWriter(outputfile);
PrintWriter pw = new PrintWriter(new File(outputfile));
while (inputFile.hasNextLine()) {
pw.write(inputFile.nextLine().isPrime());
pw.write(System.lineSeparator());
}
pw.close();
inputFile.close();
}
public static void isPrime (int num) throws IOException {
boolean flag = false;
for (int i =2; i <= num/2; i++) {
if (num % i ==0) {
flag = true;
break;
}
}
if (!flag)
System.out.println(num + "is a prime number");
else
System.out.println(num + "is not a prime number");
}
I need the program to be able to read a inputfile of a different numbers and then write out to the output file which of those numbers is prime.
You wrote "inputFile.nextLine().isPrime()". But inputFile.nextLine() gives you back a String. There is no method isPrime() that you can call on a String, therefore you will get a compilation error.
You must first convert it to an integer, pass it to your method, and then deal with the result:
isPrime(Integer.parseInt(inputFile.nextLine()));
I suggest you just return a message string from your method isPrime() instead of void, then you can deal with it properly:
pw.write(isPrime(Integer.parseInt(inputFile.nextLine())));
ADDENDUM:
I modified your code so you can see where to add the suggested lines. I also left out unnecessary lines.
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the name of the input file?");
String inputfile = keyboard.nextLine();
File f = new File(inputfile);
System.out.println("What is the name of the output file?");
String outputfile = keyboard.nextLine();
Scanner inputFile = new Scanner(f);
PrintWriter pw = new PrintWriter(new File(outputfile));
while (inputFile.hasNextLine()) {
String nextLine = inputFile.nextLine();
boolean isPrime = isPrime(Integer.parseInt(nextLine));
if (isPrime) {
pw.write(nextLine + System.lineSeparator());
}
}
pw.close();
inputFile.close();
}
public boolean isPrime (int num) {
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
TODO: put your file-opening code inside a try-catch-finally block and put your close() commands into its finally block. (If you don't know why it should be inside finally, just ask)
Could someone help me understand what I am doing wrong please?
I have to read through a file with 11 integers and doubles on each line, each line needs to become its own object and stored in an arrayList. However, the delimiter is a single space. And I have used this code, but it doesnt seem to work and I am not sure what I am doing wrong.
package p2_0000000;
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
public class P2_000000 {
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Which file year would you like to analyze:\n"
+ "1) 2007\n"
+ "2) 2011\n"
+ "3) 2013\n"
+ "(Enter number for choice)");
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
ArrayList<dwellingClass> alist = new ArrayList<dwellingClass>();
if (choice == 1) {
try {
File file = new File("2007.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] info = line.split(" ");
int age = Integer.parseInt(info[0]);
int region = Integer.parseInt(info[1]);
double lmed = Double.parseDouble(info[2]);
double fmr = Double.parseDouble(info[3]);
double extremelyLowIncome = Double.parseDouble(info[4]);
double veryLowIncome = Double.parseDouble(info[5]);
double lowIncome = Double.parseDouble(info[6]);
int bedrooms = Integer.parseInt(info[7]);
double value = Double.parseDouble(info[8]);
int rooms = Integer.parseInt(info[9]);
double utility = Double.parseDouble(info[10]);
dwellingClass dwelling = new dwellingClass(age, region, lmed, fmr, extremelyLowIncome, veryLowIncome, lowIncome, bedrooms, value, rooms, utility);
alist.add(dwelling);
}
scanner.close();
} catch (Exception a) {
a.printStackTrace();
System.exit(0);
};
for (dwellingClass each : alist) {
System.out.println(each);
}
}
System.out.println(alist.get(0).getAge());
}
}
I get these errors:
java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
Thank you everyone for the help!
I also figured out that this could also work for anyone who reads this post later:
public class P2_0000000 {
public static void main(String[] args) {
// TODO code application logic here
ArrayList<dwellingClass> alist = new ArrayList<dwellingClass>();
try {
File file = new File("2007.txt");
Scanner input = new Scanner(file);
while (input.hasNext()) {
int age = input.nextInt();
int region = input.nextInt();
double lmed = input.nextDouble();
double fmr = input.nextDouble();
double extremelyLowIncome = input.nextDouble();
double veryLowIncome = input.nextDouble();
double lowIncome = input.nextDouble();
int bedrooms = input.nextInt();
double value = input.nextDouble();
int rooms = input.nextInt();
double utility = input.nextDouble();
dwellingClass dwelling = new dwellingClass(age, region, lmed, fmr, extremelyLowIncome, veryLowIncome, lowIncome, bedrooms, value, rooms, utility);
alist.add(dwelling);
}
input.close();
} catch (Exception a) {
a.printStackTrace();
System.exit(0);
};
for (dwellingClass each : alist) {
System.out.println(each.getAge() + each.getRegion());
}
System.out.println(alist.get(0).getAge());
}
}
First you can read the file this way:
Scanner in = new Scanner(new FileReader("2007.txt"));
Secondly to parse white spaces you will need to use something like this:
yourString.split("\\s+");
So your this line should become:
String[] info = line.split("\\s+");
Then you can access your String the way you did it.
But make sure that you are passing the right values i.e. the right types to each of the methods otherwise yo will get the error you are getting.
You should do a number validation of the string you read from the file and make sure that it matches the requirements for building your dwellingClass object.
String line = scanner.nextLine();
String[] info = line.split("\\s+");
boolean validInput = true;
//loop through your info array and check each number is valid beforehand
for(int i = 0; i < info.length; i++)
{
if(!info[i].matches("\\d"))
{
validInput = false;
break;
}
}
//now we want to make sure our input was valid or else we don't create the object
if(info.length == 11 && validInput == true)
{
dwellingClass dwelling = new dwellingClass(
Integer.parseInt(info[0]),
Integer.parseInt(info[1]),
Double.parseDouble(info[2]),
Double.parseDouble(info[3]),
Double.parseDouble(info[4]),
Double.parseDouble(info[5]),
Double.parseDouble(info[6]),
Integer.parseInt(info[7]),
Double.parseDouble(info[8]),
Integer.parseInt(info[9]),
Double.parseDouble(info[4]));
alist.add(dwelling);
}
If you put this inside your while loop it will only create objects with lines read from the file that contain only numbers and contains 11 digits, other lines will simply be ignored. This would allow execution of the file even if a line is not formatted correctly.
You are creating a NEW file, not loading your file. To load a file, you need to use a file input stream. your Scanner wont find anything in a new file and thus its all Null
I stand corrected, the syntax is correct and this would load an existing file. As others have mentioned above its a data issue
This is my first time using more than one method in a progam and I have also never tried to count lines, words and letters in a file. So I've read three Java books file sections and then looked at questions on the forum here and had a go. I think I am doing something wrong with variable names, as I don't know the rules with where you put them in in multi method etc. If you could say something like that is glaringly wrong because you have to do this, that would be helpful. I can't use the debugger because I can't compile it. Anyway, thanks for looking at this.
import java.util.Scanner;
import java.io.*;
/**
* A program to count the number of lines, words and characters in a text file.
*
* #author
* #version 2014
*/
public class WordCount
{
public static void main(String[] args) throws FileNotFoundException
{
// get the filename
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the name of the file: ");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
lines(filename);
words(filename);
characters(filename);
}
/**
* Count the number of lines in a file, and print out the result.
*
*/
public static void lines(String filename) throws FileNotFoundException
{
Scanner inputFile = new Scanner(file);
int lines = 0;
while (inputFile.hasNextLine())
{
lines++;
file.nextLine();
}
return lines;
inputFile.close();
}
/**
* Count the number of words in a file, and print out the result.
*
*/
public static void words(String filename) throws FileNotFoundException
{
Scanner inputFile = new Scanner(file);
int words = 0;
while (input.hasNextLine())
{
String word = input.next();
words++;
}
return words;
inputFile.close();
}
/**
* Count the number of characters in a file, and print out the result.
*
*/
public static void characters(String filename) throws FileNotFoundException
{
Scanner inputFile = new Scanner(file);
int characters = 0;
while (inputFile.hasNextLine())
{
String line = inputFile.nextLine();
for(int i = 0; i < line.length(); i++)
{ characters = line.charAt(i);
if (character != 32)
{
characters++;
}
}
}
return characters;
inputFile.close();
System.out.println("The number of lines is: " + lines);
System.out.println("The number of words is: " + words);
System.out.println("The number of characters is: " + characters);
System.out.println();
}
}
Change the following
public static int lines(String filename) throws FileNotFoundException
//change the return type to int instead of void
{
Scanner inputFile = new Scanner(filename); //filename instead of file
int lines = 0;
while (inputFile.hasNextLine())
{
lines++;
inputFile.nextLine(); // ---do----
}
inputFile.close(); // after return it will become unreachable
return lines;
}
Same applies to other methods
Your code contains several problems. So let us fix that one by one in each method:
public static void main(String[] args) throws FileNotFoundException
{
// get the filename
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the name of the file: ");
String filename = keyboard.nextLine();
keyboard.close(); // <- don't forget to close this resource
File file = new File(filename);
//Scanner inputFile = new Scanner(file); // <- this line is unnecessary, because you never use that variable
lines(file); // <- you already obtained a File object, so use it ;)
words(file);
characters(file);
}
Next method:
public static void lines(File file) throws FileNotFoundException // mind the new argument type
{
Scanner inputFile = new Scanner(file);
int lines = 0;
while (inputFile.hasNextLine())
{
lines++;
inputFile.nextLine(); //<- use "inputFile" instead of "file"
}
inputFile.close();
//return lines; // <- you can't return something if your method uses "void" as the return type
//your comment on that method says that you like to print the result, so let's do that
System.out.println("The number of lines is: " + lines);
}
And the next one:
public static void words(File file) throws FileNotFoundException // <- new argument type
{
Scanner inputFile = new Scanner(file);
int words = 0;
while (inputFile.hasNextLine())
{
//String word = inputFile.next(); // that won't work like you think, but we can do a little "trick" here
String line = inputFile.nextLine(); // read the current line of text
words += line.split(" ").length; // split the line using whitespace and add the number of words to the current value of variable "words"
//words++; // <- not needed anymore
}
//return words; // <- like before: not possible if return type is void
inputFile.close();
//your comment on that method says that you like to print the result, so let's do that
System.out.println("The number of words is: " + words);
}
And the last method:
public static void characters(File file) throws FileNotFoundException
{
Scanner inputFile = new Scanner(file);
int characters = 0;
int count = 0; // new variable to count the characters
while (inputFile.hasNextLine())
{
String line = inputFile.nextLine();
for(int i = 0; i < line.length(); i++)
{
characters = line.charAt(i); // <- no harm in using a new line :)
if (characters != 32) // <- you wrote "character"
{
count++; // <- "characters" is the current character itself, we won't increase that. For example "a" would become "b" and we don't want/need that :)
}
}
}
//return characters; // <- you know that already ...
inputFile.close();
//System.out.println("The number of lines is: " + lines); // <- "lines" and "words" are unknown here, but we printed these results already
//System.out.println("The number of words is: " + words);
System.out.println("The number of characters is: " + count); // <- print the count of characters
System.out.println();
}
After this changes you code should work now :).
It seems the methods only need the File object.
int n = countLines(file);
System.out.println("Lines: " + n);
...
public static int countLines(File textFile) throws IOException
{
Scanner inputFile = new Scanner(textFile);
int lines = 0
while (inputFile.hasNextLine())
{
lines++;
inputFile.nextLine();
}
inputFile.close();
return lines;
}
For nextLine you asked the wrong object, Scanner needed.
return returns from the method, so close has come before.
As you return the line count, you must return int.
Method names contain a verb by convention.
The method knows no file or filename.
It also cannot alter a variable if you pass a variable, like file,
You can give the new paramaeter the same name, but for clarity not done here.
Problem number 1:
public static void lines(String filename) throws FileNotFoundException
{
Scanner inputFile = new Scanner(file);
int lines = 0;
while (inputFile.hasNextLine())
{
lines++;
file.nextLine();
}
return lines; // <----------------
inputFile.close();
}
This is a void method but you have a return lines statement. Either remove it or change the method header to public static int lines(String filename) throws FileNotFoundException
Problem number 2
public static void words(String filename) throws FileNotFoundException
{
Scanner inputFile = new Scanner(file);
int words = 0;
while (input.hasNextLine())
{
String word = input.next();
words++;
}
return words; <-------------
inputFile.close();
}
Again here you ask from a void method to return a value. Change method header to public static int words(String filename) throws FileNotFoundException
Problem number 3:
public static void characters(String filename) throws FileNotFoundException
{
Scanner inputFile = new Scanner(file);
int characters = 0;
while (inputFile.hasNextLine())
{
String line = inputFile.nextLine();
for(int i = 0; i < line.length(); i++)
{ characters = line.charAt(i);
if (character != 32)
{
characters++;
}
}
}
return characters; //<---------------
inputFile.close();
System.out.println("The number of lines is: " + lines);
System.out.println("The number of words is: " + words);
System.out.println("The number of characters is: " + characters);
System.out.println();
}
Again here you have a return int statement on a void method. Just change the method header to this: public static int characters(String filename) throws FileNotFoundException
I would just like to ask on how can I make my code to just get the input instead of declaring it? Here's my program. I want to input different atomic numbers and not just "37" like what's in my code. Don't mind my comments, it's in my native language. Thanks!
public class ElectConfi {
public static void main(String s[]) {
int atomicNumber = 37;
String electronConfiguration = getElectronConfiguration(atomicNumber);
System.out.println(electronConfiguration);
}
public static String getElectronConfiguration(int atomicNumber) {
int[] config = new int[20]; //dito nag store ng number of elec. in each of the 20
orbitals.
String[] orbitals = {"1s^", "2s^", "2p^", "3s^", "3p^", "4s^", "3d^", "4p^", "5s^",
"4d^", "5p^", "6s^", "4f^", "5d^", "6p^", "7s^", "5f^", "6d^", "7p^", "8s^"};
//Names of the orbitals
String result="";
for(int i=0;i<20;i++) //dito ung i represents the orbital and tapos ung j
represents ng electrons
{
for(int j=0;(getMax(i)>j)&&(atomicNumber>0);j++,atomicNumber--) //if atomic
number > 0 and ung orbital ay kaya pa magsupport ng more electrons, add
electron to orbital ie increment configuration by 1
{
config[i]+=1;
}
if(config[i]!=0) //d2 nagche-check to prevent it printing empty
orbitals
result+=orbitals[i]+config[i]+" "; //orbital name and configuration
correspond to each other
}
return result;
}
public static int getMax(int x) //returns the number of max. supported electrons by each
orbital. for eg. x=0 ie 1s supports 2 electrons
{
if(x==0||x==1||x==3||x==5||x==8||x==11||x==15||x==19)
return 2;
else if(x==2||x==4||x==7||x==10||x==14||x==18)
return 6;
else if(x==6||x==9||x==13||x==17)
return 10;
else
return 14;
}
}
You can use either a Scanner or BufferedReader and get the user input
Using Scanner
Scanner scanner = new Scanner(System.in);
System.out.println("Please input atomic number");
int atomicNumber = scanner.nextInt();
Using BufferedReader
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int atomicNumber = Integer.parseInt(reader.readLine());
public static String getElectronConfiguration(int atomicNumber) {}
This method accepting any int value and will return String result. so you only need to provide different number as input. There is no change required in this method.
How to provide different inputs?
You can use Scanner to do that.
Scanner scanner = new Scanner(System.in);
System.out.println("Please input atomic number");
int atomicNumber = scanner.nextInt();
Now call your method
String electronConfiguration = getElectronConfiguration(atomicNumber);
What are the other ways?
You can define set of values for atomicNumber in your code and you can run those in a loop
You can get input from command line arguments by doing below :
Scanner scanner = new Scanner(System.in);
String inputLine = scanner.nextLine(); //get entire line
//or
int inputInt= scanner.nextInt();//get an integer
Check java.util.Scaner api for more info - http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Hope this helps!
You can get the user input from a command line argument:
public static void main(String s[]) {
if (s.length == 0) {
// Print usage instructions
} else {
int atomicNumber = Integer.parseInt(s[0]);
// rest of program
}
}
I am creating a simple program that counts the number of words, lines and total characters (not including whitespace) in a paper. It is a very simple program. My file compiles but when I run it I get this error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1347)
at WordCount.wordCounter(WordCount.java:30)
at WordCount.main(WordCount.java:16)
Does anyone know why this is happening?
import java.util.*;
import java.io.*;
public class WordCount {
//throws the exception
public static void main(String[] args) throws FileNotFoundException {
//calls on each counter method and prints each one
System.out.println("Number of Words: " + wordCounter());
System.out.println("Number of Lines: " + lineCounter());
System.out.println("Number of Characters: " + charCounter());
}
//static method that counts words in the text file
public static int wordCounter() throws FileNotFoundException {
//inputs the text file
Scanner input = new Scanner(new File("words.txt"));
int countWords = 0;
//while there are more lines
while (input.hasNextLine()) {
//goes to each next word
String word = input.next();
//counts each word
countWords++;
}
return countWords;
}
//static method that counts lines in the text file
public static int lineCounter() throws FileNotFoundException {
//inputs the text file
Scanner input2 = new Scanner(new File("words.txt"));
int countLines = 0;
//while there are more lines
while (input2.hasNextLine()) {
//casts each line as a string
String line = input2.nextLine();
//counts each line
countLines++;
}
return countLines;
}
//static method that counts characters in the text file
public static int charCounter() throws FileNotFoundException {
//inputs the text file
Scanner input3 = new Scanner(new File("words.txt"));
int countChar = 0;
int character = 0;
//while there are more lines
while(input3.hasNextLine()) {
//casts each line as a string
String line = input3.nextLine();
//goes through each character of the line
for(int i=0; i < line.length(); i++){
character = line.charAt(i);
//if character is not a space (gets rid of whitespace)
if (character != 32){
//counts each character
countChar++;
}
}
}
return countChar;
}
}
I can't really say the exact reason for the problem without looking at the file (Maybe even not then).
while (input.hasNextLine()) {
//goes to each next word
String word = input.next();
//counts each word
countWords++;
}
Is your problem. If you are using the input.hasNextLine() in the while conditional statement use input.nextLine(). Since you are using input.next() you should use input.hasNext() in the while loops conditional statement.
public static int wordCounter() throws FileNotFoundException
{
Scanner input = new Scanner(new File("words.txt"));
int countWords = 0;
while (input.hasNextLine()) {
if(input.hasNext()) {
String word = input.next();
countWords++;
}
}
return countWords;
}
I have just added an if condition within the while loop. Just make sure to check there are token to be parsed. I have changed only in this place. Just make sure to change wherever needed.
This link will give good info. in regard to that.
Hope it was helpful. :)