This question already has an answer here:
What does "error: '.class' expected" mean and how do I fix it
(1 answer)
Closed 3 years ago.
Currently I have an error - '.class' expected - on line 40. Any help is hugely appreciated.
import java.io.*; // For File class and FileNotFoundException
import java.util.Scanner; //For the Scanner class
import javax.swing.JOptionPane; // For the JOptionPane class
/**
* Write a description of class PartB here.
*
* #Hubble, Kieran
* #Version 0.1
*/
public class PartB
{
public static void main(String[] args) throws FileNotFoundException
{
File file; //for file input
Scanner inputFile; //for file input
String fileName; //to hold a file name
String paragraph; //to extract the letter frequencies
//get a file name from the user.
fileName = JOptionPane.showInputDialog("enter " + " the name of the file");
//attempt to open the file.
try
{
file = new File(fileName);
inputFile = new Scanner(file);
JOptionPane.showMessageDialog(null, "the file was found.");
// read the input file, processing data one line at a time
while(inputFile.hasNext())
{
String str = inputFile.nextLine();
System.out.println(str);
}
//create an Output file
PrintWriter outputFile = new PrintWriter("crackedcode.txt");
while(paragraph.length() > 0)
// error is occurring on the next line (line 40)
int[]; letterCount = new int[26];
for (int count = 0; count < paragraph.length; count++) {
String current = paragraph[count];
char[] letters = current.toCharArray();
}
for (int count2 = 0; count2 < letters.length; count2++) { char lett = letters[count2]; if ( (lett >= 'A') & (lett <= 'Z') ) {
letterCount[lett - 'A']++;
}
}
for (char count = 'A'; count <= 'Z'; count++) {
System.out.print(count + ": " +
letterCount[count - 'A'] +
" ");
}
System.out.println();
// close the input file
inputFile.close();
}
catch (FileNotFoundException e)
{
JOptionPane.showMessageDialog(null, "file not found.");
}
JOptionPane.showMessageDialog(null, "done.");
System.exit(0); //terminate program
}
}
Remove the semicolon
int[]; letterCount = new int[26];
should be
int[] letterCount = new int[26];
Also, You need to wrap the block of the while (from the line above it) with {}
Related
output file is created but numbers are not written.
public static void main(String[] args)
{
String file_name;
String done_string = "done";
boolean done = false;
while (!done)
{
file_name = JOptionPane.showInputDialog("Enter a file name" + " or done to exit: ");
if (file_name.equals(done_string))
{
done = true;
JOptionPane.showMessageDialog(null, "EXITING");
}
else
{
try
{
File file_in = new File(file_name);
Scanner input = new Scanner(file_in);
JOptionPane.showMessageDialog(null, "File " + file_name + " found ");
int[] hold_ints = new int[100];
for (int i = 0; i< 100; i++)
{
hold_ints[i] = input.nextInt();
}
PrintWriter output = new PrintWriter("reverse_ints");
for (int i = 99; i <= 0; i--)
{
output.print(hold_ints[i]);
output.print(" ");
}
output.close();
input.close();
}
catch (FileNotFoundException e)
{
JOptionPane.showMessageDialog(null, "File " + file_name + " not found ");
}
}
}
}
}
Program should read a file then create an output file that prints the numbers in the input file in reverse.
Actual results just shows the file but nothing is written in the file.
For-loop condition is wrong, so code in the loop is not run.
I suppose it should be
for (int i = 99; i >= 0; i--)
{
output.print(hold_ints[i]);
output.print(" ");
}
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.
So I fixed my program but the problem is that after replacing all the blank spaces with tildes i have to output the text to a file that has been closed. How would I re-open the file for output and input something in?
//Name: Allen Li
//Program file: Vowels.Java
//Purpose: Using File IO, read a file's input and output this text to a new text file
//When outputting, all blank spaces will be changed to tildes and there will be a count of each vowel(AEIOU)
import java.util.Scanner; //input
import java.io.File; //IO
import java.io.IOException; //IO exception class
import java.io.FileWriter; //file output
import java.io.FileReader; //file input
import java.io.FileNotFoundException; //if file isnt found, file not found class
public class Vowels { //class
public static void main(String[] args) { //main method
try { //try block
FileReader poetry = new FileReader("poetry.txt");
FileWriter dentist = new FileWriter(
"LI_ALLEN_dentist.txt");
int a;
while ((a = poetry.read()) != -1) {
dentist.write(a);
System.out.print((char) a); //print the file to the monitor
}
poetry.close();
dentist.close();
Scanner inFile = new Scanner(new File(
"LI_ALLEN_dentist.txt"));
int numOfVowelsA = 0; //count #s of A/E/I/O/U vowels
int numOfVowelsE = 0;
int numOfVowelsI = 0;
int numOfVowelsO = 0;
int numOfVowelsU = 0;
while (inFile.hasNext()) {
String sentence = inFile.next() /* ("\\S+") */;
for (int i = 0; i <= sentence.length() - 1; i++) {
if (sentence.toLowerCase().charAt(i) == 'a') {
numOfVowelsA++;
}
if (sentence.toLowerCase().charAt(i) == 'e') {
numOfVowelsE++;
}
if (sentence.toLowerCase().charAt(i) == 'i') {
numOfVowelsI++;
}
if (sentence.toLowerCase().charAt(i) == 'o') {
numOfVowelsO++;
}
if (sentence.toLowerCase().charAt(i) == 'u') {
numOfVowelsU++;
}
}
}
System.out.println();
System.out.println("There are " + numOfVowelsA
+ " A vowels in this file of text");
System.out.println("There are " + numOfVowelsE
+ " E vowels in this file of text.");
System.out.println("There are " + numOfVowelsI
+ " I vowels in this file of text.");
System.out.println("There are " + numOfVowelsO
+ " O vowels in this file of text.");
System.out.println("There are " + numOfVowelsU
+ " U vowels in this file of text. ");
Scanner tildes = new Scanner(new File(
"LI_ALLEN_dentist.txt"));
while (tildes.hasNext()) {
String replace = tildes.nextLine();
replace = replace.replaceAll(" ", "~");
System.out.println();
System.out.print(replace);
}
} catch (FileNotFoundException i) {
System.out.println("The file you are trying to use as input is not found. " + i);
} catch (IOException i) {
System.out.println("There is an issue with the input or output file. " + i);
}
}
}
You didn't close inFile. Close inFile first and then you are able to open it again in tildes.
Close it before Scanner tildes = new Scanner(...); line.
The goal of this code is to read a file and add numbers to the end of every {(curly bracket) but the file does not output each line like it does in the file but it out puts it into one entire line. where do I put a System.out.println statement. I tried every where and it keeps repeating it
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
readFile();
}
public static void readFile() { // Method to read file
Scanner inFile = null;
String out = " ";
try {
Scanner input = new Scanner(System.in);
System.out.println("enter file name");
String filename = input.next();
File in = new File(filename); // ask for the file name
inFile = new Scanner(in);
int count = 0;
while (inFile.hasNextLine()) { // reads each line
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
char ch = line.charAt(i);
out = out + ch;
if (ch == '{') {
count = count + 1;
out = out + " " + count + " ";
} else if (ch == '}') {
out = out + " " + count + " ";
if (count > 0) {
count = count - 1;
}
}
}
}
System.out.println(out);
} catch (FileNotFoundException exception) {
System.out.println("File not found.");
}
inFile.close();
}
}
where do I put a System.out.println statement
The entire output is built in a single string that is not printed until the end, so adding System.out.println statements in the line loop won't help. You can add line breaks to the string by doing:
out += "\n";
Or, at the end of the body of your line loop, print the current line, and reset the buffer for the next line:
System.out.println(out);
out = "";
Using a String for the output buffer is not efficient by the way. String is immutable, so every + statement is copying and duplicating all of the previous characters to create a new object, every time. Consider declaring out as a StringBuilder rather than a String. Then you can add to it with the .append() method and it will not copy all the text every time because a StringBuilder is mutable.
Further down it keeps saying the tow local variable cant be initialized when they are. Cant seem to find the problem
import java.io.*;
import java.util.Scanner; //Scanner method
public class Popcorn1 {
public static void main(String args[]) throws FileNotFoundException{
printHeader();
File file;
do {
Scanner in = new Scanner (System.in);
System.out.println("Enter the the file name");
String filename = in.next();
file = new File(filename);
} while(!file.exists());
FileReader inputFile = new FileReader (file);
Scanner inFile = new Scanner(inputFile);
System.out.println(" PopCorn Co-op");
System.out.println(" Production in Hundreds");
System.out.println(" of Pint Jars Per Acre");
System.out.println(" 1 2 3 4 5 6");
System.out.println("Farm Name ---|---|---|---|---|---|");
System.out.println();
// Printing out title and table header for reader to easily read data
String errorMSG = " ";
while (inFile.hasNextLine()) {
String inputLine = inFile.nextLine();
//System.out.print(inputLine);
int position;
String name;
int jars;
double acres;
position = inputLine.indexOf(','); //Get the Location of the comma to use as a delimiter
name = inputLine.substring(0,position); //Everything to the left of the comma is the farm name
System.out.printf("%-31s", name);
inputLine = inputLine.substring(position + 2,inputLine.length()); //rest of the string
Scanner line = new Scanner(inputLine);
if(line.hasNextDouble())
acres = line.nextDouble();
else
errorMSG += "There is missing data";
if(line.hasNextInt())
jars = line.nextInt();
else
errorMSG += "There is missing data";
int starsConversion =(int)(jars/acres/25); **<-------- problem is here**
for (int i = 1; i < starsConversion; i++) {
if( i == 20)
System.out.print("#");
else
System.out.print("*");
}
if (starsConversion < 20) {
for (int i = 1; i < (21 - starsConversion); i++) {
System.out.print(" ");
}
System.out.print("|");}
System.out.println(); //go to the next line
}
System.out.println(errorMSG);
}
}
There is an execution path where jars was never initialized, specifically, if line.hasNextInt() is false.
To use it, you must make sure jars is always initialized to something. You can initialize it to say 0 before the if.
What happens if if(line.hasNextInt()) is false on the first run?