I'm very new to the Java language, and in one of my school assignments, they want us to take in a simple text file that contains a line of text and index it (so that it can be used as a decoder for a secret message). I already know how to read the file and get that line of text into the program, but how do I index each character in the line of text and assign each character a value starting at 0 and ending at the length of the line of text? Here is what I have so far (*Note: I was trying different stuff with the code in the for loop, so I'm not sure if I'm on the right track or not):
import java.util.*;
import java.io.*;
public class Decoder
{
public static void main(String[] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
String fileName;
System.out.println("Please enter the name of a file to be decoded: ");
fileName = keyboard.nextLine();
File testFile = new File(fileName);
Scanner inputFile = new Scanner(testFile);
String keyPhrase = inputFile.nextLine();
for(int i = 0; i < keyPhrase.length(); i++)
{
char letter = keyPhrase.charAt(i);
int num = (int)letter;
System.out.println(num);
}
}
}
Related
Write a program that asks the user to enter the name of a file, and then asks the user to enter a character. The program should count and display the number of times that the specified character appears in the file.
My problem is that length and charAt on lines 24 and 25 error, and I'm not sure what to do in order to get the program to run.
import java.util.Scanner;
import java.io.*;
public class challenge6 {
public static void main(String[] args) throws Exception {
String string;
char character;
int count = 0;
File file = new File("./file.txt");
Scanner input = new Scanner(file);
input.hasNextLine();
while (input.hasNextLine())
System.out.println(input.nextLine());
System.out.println("enter name of a char");
character = input.next().charAt(0);
for(int i=0; i < input.length(); i++)
{ if(input.charAt(i) == character)
count++;
}
System.out.println(count);}}
An easier way would be to utilize the String::replace method to replace char with blank and check to string length before and after. You also need to loop all through your file
File f = new File("c:/tmp/file.txt");
Scanner input = new Scanner(f);
int count = 0;
String charToFind = "a";
while (input.hasNextLine()) {
String line = input.nextLine();
int len = line.length();
line = line.replace(charToFind, "");
count += len - line.length();
}
System.out.format("There were %d occurrences found%n", count);
input.close();
This is my assignment - Write a program that reads a file and removes all comma’s from it and writes it back out to a second file. It should print to the console window, at the end, the number of comma’s removed.
The program needs to:
Prompt the user for the name of the file to read.
Reads file
Write the non-comma characters to output.txt, including all spaces.
When done reading the input file, write the total number of comma’s removed to the console window.
For example, if the input file contains 3+,2 = 5m, 7%,6 =1 hello
Then the output.txt file should contain:
3+2=5m 7%6=1 hello
And the console window should print “Removed 3 commas”.
Right now I'm having trouble actually removing commas from my input file, I think I would write the line under my last if statment.
Tried figuring out how to remove commas from the input file
package pkg4.pkg4.assignment;
import java.util.Scanner;
import java.io.*;
/**
*
* #author bambo
*/
public class Assignment {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the name of the inputfile?");
String inputfile = keyboard.nextLine();
File f = new File(inputfile);
Scanner inputFile = new Scanner(f);
System.out.println("Please enter the output file");
String outputfile = keyboard.nextLine();
FileWriter fw = new FileWriter(outputfile);
PrintWriter pw = new PrintWriter(fw);
int lineNumber=0;
while(inputFile.hasNext());
lineNumber++;
int commacount = 0;
String line = inputFile.nextLine();
if (line.length () != 0)
commacount++;
for(int i=0; i< line.length(); i++)
{
if(line.charAt(i) == ',');
{
commacount++;
}
pw.println("removed " + commacount + "commas");
}
}
}
According to your requirement for program i am suggesting you to use java 8 classes.for simplicity.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
public class Assignment {
public static void main(String[] args) throws IOException {
String content = "";
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the name of the input file?");
String inputfile = keyboard.nextLine();
content = new String(Files.readAllBytes(Paths.get(inputfile)));
long total_numbers_of_char = content.chars().filter(num -> num == ',').count();
System.out.println("Please enter the output file");
content = content.replaceAll(",", "");
String outputfile = keyboard.nextLine();
Files.write(Paths.get(outputfile), content.getBytes());
System.out.println("removed " + total_numbers_of_char + " commas");
keyboard.close();
}
}
To print on console you should be using :
System.out.println("removed " + commacount + "commas");
To write the line in the output file without the commas :
pw.println(line.replaceAll(",",""));
In this program, I am supposed to check if each word in the file "Paper" is in the file "dictionary". If the word is not in the file dictionary, it prints out ("Line #" "the word"). The problem in this code is the loop. I don't know to make the loop reset.
EX: a dictionary file has two words big and small
a paper file has a sentence his foot is small
The program will print
Line: 1: his
Line: 1: foot
Line: 1: is
import java.util.Scanner;
import java.io.*;
public class SpellCheck{
public static void main(String[] arg) throws FileNotFoundException{
Scanner readfile = new Scanner(new File("paper"));
String word = "";
int count = 0;
while(readfile.hasNextLine()){
String line = readfile.nextLine();
Scanner linescan = new Scanner(line);
String Scannedword = linescan.next();
word = Scannedword;
count++;
}
Scanner openDictionary = new Scanner(new File("Dictionary"));
String wordInDictionary = openDictionary.next();
if(word.equals(wordInDictionary)){
}else{
System.out.println("Line " + count + ": " + word);
openDictionary.close();
}
}
}
I would rather preprocess dictionary file.
while(readfile.hasNextLine()){
String line = readfile.nextLine();
Scanner linescan = new Scanner(line);
String Scannedword = linescan.next();
word = Scannedword;
count++;
}
Just like you have written here, make a hashset or whatever the container you'd like and copy over words in dictionary file. And, using another loop to do your task (check if the container contains the word you just read.) In this way, two loop are not nested so it will run O(n).
I am trying to copy the contents of a .txt file to an array and print it to the console.
The code requires a main method with two scanners (one to read input from the user, and the second to read the file), a method to make the array, and a method to print the array.
I have successfully managed to make an array and print it, but the output is not ideal. It is scattered and difficult to read. Can someone help me to improve my output so it reads more like a list?
Here is my code:
public class CutupSongCreator {
// Creates two Scanner objects; one reads input from console, the other scans a file
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in); // SCANNER ONE (reads input)
System.out.print("What is the input filename? ");
String filename = console.next();
File f = new File(filename);
while (!f.exists()) {
System.out.print("That file does not exist. Try again: ");
filename = console.next();
f = new File(filename);
}
Scanner input = new Scanner(f); // SCANNER TWO (reads file)
SongLine[] arr = makeArray(input);
printArray(arr);
// Sort by genre
// System.out.print("What genre are you looking for: ");
// String genretype = console.next();
// if (genretype == input.next()) {
// System.out.print("You can't just make up a genre. Try again: ");
// genretype = console.next();
// }
// listLinesByGenre(arr, genretype);
}
// Creates an array of SongLines from a set of lines
public static SongLine[] makeArray(Scanner reader) {
int total = reader.nextInt(); // First int = # of lines
SongLine[] arr = new SongLine[total]; // New array to hold the length of the file
for(int i = 0;i < total; i++) {
String genre = reader.next();
int lineNumber = reader.nextInt();
String words = reader.nextLine();
SongLine temp = new SongLine(genre, lineNumber, words);
arr[i] = temp;
}
reader.close();
return arr;
}
// Prints out the elements of an array
public static void printArray(SongLine[] songs) {
System.out.println(Arrays.toString(songs));
}
}
My code makes use of a constructor class, which I could post if needed, but I think I just do not understand how to read or use the constructor file. Below are the current and desired output. The desired shows the genre, lineNumber, and script, and I would like to print it looking as so.
Current Output
Desired Output
Thank you.
I'm trying to write a part of a program that reads a text file and then retrieves an integer from each line in the file and adds them together. I've managed to retrieve the integer, however each line contains more than one integer, leading me to inadvertently pick up other integers that I don't need. Is it possible to skip certain integers?
The format of the text file can be seen in the link underneath.
Text file
The integers that i'm trying to collect are the variables that are 3rd from the left in the text file above, (3, 6 and 4) however i'm also picking up 60, 40 and 40 as they're integers too.
Here's the code that i've got so far.
public static double getAverageItems (String filename, int policyCount) throws IOException {
Scanner input = null;
int itemAmount = 0;
input = new Scanner(new File(filename));
while (input.hasNext()) {
if (input.hasNextInt()) {
itemAmount = itemAmount + input.nextInt();
}
}
return itemAmount;
}
Just add input.nextLine():
if (input.hasNextInt()) {
itemAmount = itemAmount + input.nextInt();
input.nextLine();
}
From the documentation: nextLine advances the scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
Another approach would be parsing each line and taking the third column.
BufferedReader r = new BufferedReader(new FileReader(filename));
while (true) {
String line = r.readLine();
if (line==null) break;
String cols[] line.split("\\s+");
itemAmount += Integer.parseInt(cols[2]);
}
r.close();
public static double getAverageItems (String filename, int policyCount) throws IOException {
Scanner input = null;
int itemAmount = 0;
input = new Scanner(new File(filename));
while (input.hasNext()) {
String []var = input.nextLine().split("\\s+");
itemAmount += var[2];
}
return itemAmount;
}