So I'm trying to read in a string from a file. However, I want each string to contain exactly 64 characters or less if the last string doesn't have 64 in it. So essentially I have a counter, when that counter reaches 64, I set the array of characters to a string, go to the next row and reset the count to zero. However I'm not getting output of any kind when I run it. Any help is appreciated. Here is a snippet of my code
public static void main(String[] args) throws IOException{
File input = null;
if (1 < args.length) {
input = new File(args[1]);
}
else {
System.err.println("Invalid arguments count:" + args.length);
System.exit(0);
}
String key = args[0];
BufferedReader reader = null;
int len;
Scanner scan = new Scanner(System.in);
System.out.println("How many lines in the file?");
if(scan.hasNextInt()){
len = scan.nextInt();
}
else{
System.out.println("Please enter an integer: ");
scan.next();
len = scan.nextInt();
}
scan.close();
String[] inputText = new String[2 * len];
String[] encryptText = new String[2 * len];
char[][] inputCharArr = new char[2 * len][64];
reader = new BufferedReader(new FileReader(input));
int r;
int counter = 0;
int row = 0;
while ((r = reader.read()) != -1) {
char ch = (char) r;
if(counter == 64){
String temp = new String(inputCharArr[row]);
inputText[row] = temp;
encryptText[row] = inputText[row];
System.out.println(inputText[row]);
row++;
counter = 0;
}
if(row == len){
break;
}
inputCharArr[row][counter] = ch;
counter++;
}
Edit: Is this close?
CharBuffer cbuf = CharBuffer.allocate(64);
int counter = 0;
while (reader.read(cbuf) != -1) {
inputText[counter] = cbuf.toString();
encryptText[counter] = inputText[counter];
counter++;
cbuf.clear();
}
Related
Hi for my HW I am suppose to read a text file of '.' and 'x' representing cells in Conway's Game of Life. I'm having trouble with reading the given text input and adding it into my double integer arrays. Specifically the rowcounter and columncounter part I'm sure there is a better way to do it but when I tried for loops it only read one row. I included previous parts of the code just in case. Thanks.
// Initiate file
File inputfile = new File(inputfilename);
try {
input = new Scanner(inputfile);
} catch (Exception ie) {
}
// Get array size
int[] arraysize = new int[2];
while (input.hasNextInt()) {
for (int i = 0; i < 2; i++) {
int token = input.nextInt();
arraysize[i] = token;
}
}
//System.out.println(Arrays.toString(arraysize));
// Create Array
int[][] newarray = new int[arraysize[0]][arraysize[1]];
//System.out.println(Arrays.deepToString(newarray));
// Read initial
int rowcounter = 0;
int columncounter = 0;
while (input.hasNextLine()) {
Scanner inputtoken = new Scanner(input.nextLine());
while (inputtoken.hasNext()) {
String token = inputtoken.next();
//System.out.print(token);
char xchar = token.charAt(0);
if (xchar == 'x') {
newarray[rowcounter][columncounter] = 1;
} else {
newarray[rowcounter][columncounter] = 0;
//System.out.print(rowcounter);
}
columncounter = columncounter + 1;
//System.out.print(columncounter);
}
columncounter = 0;
System.out.println();
rowcounter = rowcounter + 1;
//System.out.print(rowcounter);
}
System.out.println(Arrays.deepToString(newarray));
I'm trying to count the number of Words, Lines and characters(excluding whitespace). The only part I can't get to work is ignoring the whitespace for the character count.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Exercise2 {
public static void main(String[] args) throws IOException{
File file = getValidFile();
int count = wordCount(file);
int lines = lineCount(file);
int characters = characterCount(file);
System.out.println("Total Words = " + count);
System.out.println("Total Lines = " + lines);
System.out.println("Total Characters = " + characters);
}
public static int characterCount(File file) throws IOException {
{
Scanner inputFile = new Scanner(file).useDelimiter(",\\s*");;
int characters = 0; // initialise the counter variable
while (inputFile.hasNext())
{
inputFile.next(); //read in a word
characters++; //count the word
}
inputFile.close();
return characters;
}
}
public static int lineCount(File file)throws IOException {
{
Scanner inputFile = new Scanner(file);
int lines = 0; // initialise the counter variable
while (inputFile.hasNext())
{
inputFile.nextLine(); //read in a line
lines++; //count the line
}
inputFile.close();
return lines;
}
}
public static int wordCount(File file) throws IOException {
{
Scanner inputFile = new Scanner(file);
int count = 0; // initialise the counter variable
while (inputFile.hasNext())
{
inputFile.next(); //read in a word
count++; //count the word
}
inputFile.close();
return count;
}
}
public static File getValidFile()
{
String filename; // The name of the file
File file;
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Get a valid file name.
do
{
/*for (int i = 0; i < 2; i ++ )
{*/
System.out.print("Enter the name of a file: ");
filename = keyboard.nextLine();
file = new File(filename);
if (!file.exists())
System.out.println("The specifed file does not exist - please try again!");
}while( !file.exists());
return file;
}
}
If you want to count the characters in the file, excluding any whitespace, you can read your file line by line and accumulate the character count, or read the whole file in a String and do the character count, e.g.
String content = new Scanner(file).useDelimiter("\\Z").next();
int count = 0;
for (int i = 0; i < content.length(); i++) {
if (!Character.isWhitespace(content.charAt(i))) {
count++;
}
}
System.out.println(count);
EDIT
Other solutions if you don't care about the content of the file, then there is no need to load it into a String, you can just read character by character.
Example counting the non-whitespace characters in Arthur Rimbaud poetry.
Using a Scanner
URL rimbaud = new URL("http://www.gutenberg.org/cache/epub/29302/pg29302.txt");
int count = 0;
try (BufferedReader in = new BufferedReader(new InputStreamReader(rimbaud.openStream()))) {
int c;
while ((c = in.read()) != -1) {
if (!Character.isWhitespace(c)) {
count++;
}
}
}
System.out.println(count);
Using a plain StreamReader
count = 0;
try (Scanner sin = new Scanner(new BufferedReader(new InputStreamReader(rimbaud.openStream())))) {
sin.useDelimiter("");
char c;
while (sin.hasNext()) {
c = sin.next().charAt(0);
if (!Character.isWhitespace(c)) {
count++;
}
}
}
System.out.println(count);
example i have this numbers or arrays on my file (notepad)
2 3 4 5 7 2 6 2
2 4 6 8 9 4 8 1
I want to ask if how to read the next row. I can only read the first row using this code.
String path = "/path/notepad.txt";
String stringOfNumbers[];
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
BufferedReader br2 = new BufferedReader (new FileReader(path));
String lineOfNumbers = br2.readLine();
stringOfNumbers = lineOfNumbers.split(" ");
//stringOfNumbers = lineOfNumbers.split("\n");
String str = lineOfNumbers.replace(","," ");
System.out.println(str);
System.out.print("");
int numbers[][] = new int [stringOfNumbers.length][stringOfNumbers.length];
for (int i = 0; i < numbers.length; i++)
{
numbers[i][i] = Integer.parseInt(stringOfNumbers[i]);
}
System.out.print("Enter the number to search: ");
int searchNumber = Integer.parseInt(br.readLine());
int location = 0;
for (int i = 0; i < numbers.length; i++)
{
if (numbers[i][i] == searchNumber)
{
location = i+ 1;
}
}
thank you in advance.
I would do somethin like this
FileReader fr = new FileReader("myFileName");
BufferedReader br = new BufferedReader(fr);
while((line=br.readLine())!=null) // as long as there are lines in the file
{
stringOfNumbers = line.split(" ");
// other code
}
Following code will Help you save all numbers in a file to memory
Scanner scanner = new Scanner(path);
List<Integer[]> integerArList = new ArrayList<Integer[]>();
while(scanner.hasNextLine()){
String lineOfNumbers = scanner.nextLine();
stringOfNumbers = lineOfNumbers.split(" ");
//stringOfNumbers = lineOfNumbers.split("\n");
String str = lineOfNumbers.replace(","," ");
System.out.println(str);
System.out.print("");
Integer[] numbers = new Integer[stringOfNumbers.length];
for (int i = 0; i < numbers.length; i++)
{
numbers[i] = Integer.parseInt(stringOfNumbers[i]);
}
integerArList.add(numbers);
}
After this you can search any Integer by traversing each array in the List like this:
int searchMe = <get this from user>
int location=0;
boolean found=false;
for(Integer[] intAr: integerArList){
for(int i=0;i<intAr.length;i++){
if(intAr[i]==searchMe){
location+=(i+1)
found=true;
break;
}
}
if(found) break;
location+=intAr.length;
}
System.out.println("Location of " + searchMe +" : " +(found?location:"Not Found in Data"));
Hope this helps.
To read all lines of a text file you can do something like this:
String path = "/path/notepad.txt";
String stringOfNumbers[];
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
BufferedReader br2 = new BufferedReader (new FileReader(path));
ArrayList<String> listOfLines = new ArrayList<String>();
//String lineOfNumbers = "";
String line = "";
String allIndexes = "";
while ((line = br2.readLine()) != null) {
if(!line.isEmpty()){
listOfLines.add(line);
}
}
for(String lineOfNumbers : listOfLines){
stringOfNumbers = lineOfNumbers.split(" ");
//stringOfNumbers = lineOfNumbers.split("\n");
String str = lineOfNumbers.replace(","," ");
System.out.println(str);
System.out.print("");
int numbers[][] = new int [stringOfNumbers.length][listOfLines.size()];
for (int i = 0; i < numbers.length; i++)
{
numbers[i][listOfLines.indexOf(lineOfNumbers)] = Integer.parseInt(stringOfNumbers[i]);
}
System.out.print("Enter the number to search: ");
int searchNumber = Integer.parseInt(br.readLine());
int locationI = 0;
int locationJ = 0;
for (int i = 0; i < numbers.length; i++)
{
for(int j = 0; j < listOfLines.size(); j++)
if (numbers[i][j] == searchNumber)
{
locationI = i + 1;
locationJ = j + 1;
allIndexes += locationI + ":" + locationJ + " ";
}
}
}
I'm trying to implement the Caesar cipher.
But while doing so I am getting an unexpected output which I am unable to rectify.
Will someone help me please?
My code is as follows:
import java.io.*;
public class encryptology
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t, move = Integer.parseInt(br.readLine());
String s = "", st = br.readLine();
int l = st.length();
for(int x = 0; x < l; x++){
char c = st.charAt(x);
t = (int)c;
if(move != 0){
t = t + move;
if(t > 90){
t = t - 26;
}
if(t < 65){
t += 26;
}
c = (char)t;
s = st + c;
}
}
System.out.println(s);
}
}
I entered move = 2 and st = charles
The output was: charles[
You are changing wrong string. You are acctualy setting result with starting string st and add encrypted char. Change
s=st+c;
to
s=s+c;
What I need to do is to implement the 0-1 Knapsack problem. There is an input file named "In0302.txt" and an output file named "Out0302.txt". The program gets values from INPUT file and saves the results to OUTPUT file. I got my input values on paper from my "dr".
Putting them to the file seems to be ok in OUTPUT file. But... on classes "dr" tried to put other values in INPUT file, but the program didn't work. What is more there was no even an error, but the program was still compiling and compiling... and I can't get know where the problem is. Does anybody would try to change something in this code or tell me what is wrong ?
INPUT:
4 6
2 1
3 2
3 4
4 5
OUTPUT:
1 4
2 3
JAVA CODE:
public class Knapsack {
public static int max(int a, int b){
if (a > b){
return a;
}
else{
return b;
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args){
int n = 0, W = 0, p[] = null, w[] = null, S[][] = null, S_object[][] = null;
//s[][] = arrays with values
try {
FileReader fr = new FileReader("In0302.txt");
BufferedReader in = new BufferedReader(fr);
String line = in.readLine();
String[] cols = line.split(" ");
n = Integer.parseInt(cols[0]); W = Integer.parseInt(cols[1]);
p = new int[n+1]; w = new int[n+1];
int k = 1;
while ((line = in.readLine()) != null) {
cols = line.split(" ");
p[k] = Integer.parseInt(cols[0]);
w[k] = Integer.parseInt(cols[1]);
k++;
}
S = new int[W+1][n+1];
S_object = new int[W+1][n+1];
for(int weight = 0; weight <= W; weight++){
for(int i = 0; i <= n; i++){
if (i == 0){
S[weight][i] = 0;
S_object[weight][i] = 0;
}
else if (weight < w[i]){
S[weight][i] = S[weight][i-1];
S_object[weight][i] = S_object[weight][i-1];
}
else if (weight >= w[i-1]){
S[weight][i]=max(S[weight][i-1],S[weight-w[i]][i-1]+p[i]);
if ((max(S[weight][i-1], S[weight-w[i]][i-1] + p[i]) == (S[weight-w[i]][i-1] + p[i]))) {
S_object[weight][i]=i;
} //added new element to bag
else {
S_object[weight][i]=S_object[weight][i-1];
} //nothing has been added
}
}
}
in.close();
fr.close();
}
catch (IOException e){
System.out.println("Error: " + e.toString());
}
File outputFile;
FileWriter out;
try{
outputFile = new File("Out0302.txt");
out = new FileWriter(outputFile);
String line = "";
int max_value = S[W][n];
for (int m = n; m > 0; m--){
if (S[W][m] == max_value){
line = " " + S_object[W][m] + "";
int temp = W;
while ((temp-w[S_object[temp][m]]) > 0){
temp = temp - w[S_object[temp][m]];
line += " " + S_object[temp][m];
}
out.write(line + "\n");
out.write("\n\t");
}
}
out.close();
}
catch (IOException e) {
System.out.println("Error: " + e.toString());
}
System.out.println("Arrar of values:");
for(int weight = 0; weight <= W; weight++){
for(int i = 0; i <= n; i++){
System.out.print(S[weight][i] + " ");
}
System.out.println("");
}
System.out.println("Array of objects:");
for(int weight = 0; weight <= W; weight++){
for(int i = 0; i <= n; i++){
System.out.print(S_object[weight][i] + " ");
}
System.out.println("");
}
}
}