I have to enter string x in reverse order, but it outputs null. Why and how to fix it?
Sorry in advance for the name of the variables, but also for the double loop (I know it's bad, but this is the only thing that came to my mind)
The main question is why null is entered in the file
public static void OutputOfFile(char[] x)throws IOException {
File file = new File("test");
PrintWriter out = new PrintWriter(file.getAbsoluteFile());
out.print(x);
out.close();
}
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String x = reader.readLine();
char[] x1 = x.toCharArray();
char[] x2 = new char[x1.length];
for(int i = x1.length - 1; i < -1; i--) {
for (int k = 0; k > x1.length; k++) {
x2[i] = x1[k];
}
}
OutputOfFile(x2);
}
the problem is with your loop, you need to iterate in one loop instead of an inner loop:
public static void OutputOfFile(char[] x) throws IOException {
File file = new File(""test"");
PrintWriter out = new PrintWriter(file.getAbsoluteFile());
out.print(x);
out.close();
}
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String x = reader.readLine();
char[] x1 = x.toCharArray();
char[] x2 = new char[x1.length];
for (int i = x1.length - 1, k = 0; i >= 0; i--, k++) {
x2[k] = x1[i];
}
OutputOfFile(x2);
}
Related
So I'm trying to use the BufferedWriter Class to create and write to a text file. However, a file is never created, nor is any error generater. However, if I create a text file and specify its path, it will write to that file; it seems that it just doesn't create files. Any suggestions? Thanks in advance.
public class test3 {
public static void main(String[] args) throws IOException {
int ctr = 1;
int count = 10;
Random r = new Random();
String[] textData = new String[count*3];
String storeFile = "testComplete";
String fn = "C:\\Users\\13023\\eclipse-workspace\\test\\src\\testprac\\" + storeFile;
for (int i = 0; i < count*3; i++) {
textData[i] = "Test";
textData[i+1] = "Tes";
textData[i+2] = "T";
ctr++;
i = i + 2;
}
BufferedWriter BW = new BufferedWriter(new FileWriter(fn));
int j = 0;
for (String s: textData) {
BW.write(textData[j] + "\n");
System.out.println("done");
}
BW.close();
}
}
Made a few changes to the code you provided.
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class test3 {
public static void main(String[] args) throws IOException {
int ctr = 1;
int count = 10;
// Random r = new Random(); // not used by program, maybe it will later
String[] textData = new String[count*3];
String storeFile = "testCompletetest";
String fn = "C:\\Users\\13023\\eclipse-workspace\\test\\src\\testprac\\" + storeFile;
for (int i = 0; i < count*3; i += 3) {
textData[i] = "Test";
textData[i+1] = "Tes";
textData[i+2] = "T";
ctr++;
// i = i + 2; //<<
}
BufferedWriter BW = new BufferedWriter(new FileWriter(fn));
//int j = 0; not used.
for (String s: textData) {
// ******* modified *******
BW.write(s); // textData[j] + "\n"); write the strings in the array
}
BW.close();
System.out.println("done");
}
Here is the CSV file I am using:
B00123,55
B00783,35
B00898,67
I need to read and store the first value entered in the file e.g. B00123 and store it into an array. A user can add to the file so it is not a fixed number of records.
So far, I have tried this code:
public class ArrayReader
{
static String xStrPath;
static double[][] myArray;
static void setUpMyCSVArray()
{
myArray = new double [4][5];
Scanner scanIn = null;
int Rowc = 0;
int Row = 0;
int Colc = 0;
int Col = 0;
String InputLine = "";
double xnum = 0;
String xfileLocation;
xfileLocation = "src\\marks.txt";
System.out.println("\n****** Setup Array ******");
try
{
//setup a scanner
/*file reader uses xfileLocation data, BufferedRader uses
file reader data and Scanner uses BufferedReader data*/
scanIn = new Scanner(new BufferedReader(new FileReader(xfileLocation)));
while (scanIn.hasNext())
{
//read line form file
InputLine = scanIn.nextLine();
//split the Inputline into an array at the comas
String[] InArray = InputLine.split(",");
//copy the content of the inArray to the myArray
for (int x = 0; x < myArray.length; x++)
{
myArray[Rowc][x] = Double.parseDouble(InArray[x]);
}
//Increment the row in the Array
Rowc++;
}
}
catch(Exception e)
{
}
printMyArray();
}
static void printMyArray()
{
//print the array
for (int Rowc = 0; Rowc < 1; Rowc++)
{
for (int Colc = 0; Colc < 5; Colc++)
{
System.out.println(myArray[Rowc][Colc] + " ");
}
System.out.println();
}
return;
}
public static void main(String[] args)
{
setUpMyCSVArray();
}
}
This loops round the file but doesn't not populate the array with any data. The outcome is:
****** Setup Array ******
[[D#42a57993
0.0
0.0
0.0
0.0
0.0
There is actually a NumberFormatException happening when in the first row when trying to convert the ID to Double. So I revised the program and it works for me.
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class ArrayReader
{
static String xStrPath;
static Map<String,Double> myArray = new HashMap<>();
static void setUpMyCSVArray()
{
Scanner scanIn = null;
int Rowc = 0;
int Row = 0;
int Colc = 0;
int Col = 0;
String InputLine = "";
double xnum = 0;
String xfileLocation;
xfileLocation = "/Users/admin/Downloads/mark.txt";
System.out.println("\n****** Setup Array ******");
try
{
//setup a scanner
/*file reader uses xfileLocation data, BufferedRader uses
file reader data and Scanner uses BufferedReader data*/
scanIn = new Scanner(new BufferedReader(new FileReader(xfileLocation)));
while (scanIn.hasNext())
{
//read line form file
InputLine = scanIn.nextLine();
//split the Inputline into an array at the comas
String[] inArray = InputLine.split(",");
//copy the content of the inArray to the myArray
myArray.put(inArray[0], Double.valueOf(inArray[1]));
//Increment the row in the Array
Rowc++;
}
}
catch(Exception e)
{
System.out.println(e);
}
printMyArray();
}
static void printMyArray()
{
//print the array
for (String key : myArray.keySet()) {
System.out.println(key + " = " + myArray.get(key));
}
return;
}
public static void main(String[] args)
{
setUpMyCSVArray();
}
}
Output:
the code can't reader anything ,you file path incorrect.give it absoulte file path.
scanIn = new Scanner(new BufferedReader(new FileReader(xfileLocation)));
I use opencsv library to read from csv.
import com.opencsv.CSVReader;
public class CSV {
private static String file = <filepath>;
private static List<String> list = new ArrayList<>();
public static void main(String[] args) throws Exception {
try {
CSVReader reader = new CSVReader(new FileReader(file));
String[] line;
while ((line = reader.readNext()) != null) {
list.add(line[0]);
}
Object[] myArray = list.toArray();
System.out.println(myArray.length);
System.out.println(myArray[0]);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output printed as below
3
B00123
I am trying to design a program that takes data from an external file, stores the variable to arrays and then allows for manipulation.sample input:
String1 intA1 intA2
String2 intB1 intB2
String3 intC1 intC2
String4 intD1 intD2
String5 intE1 intE2
I want to be able to take these values from the array and manipulate them as follows;
For each string I want to be able to take StringX and computing((intX1+
intX2)/)
And for each int column I want to be able to do for example (intA1 + intB1 + intC1 + intD1 + intE1)
This is what I have so far, any tips?
**please note java naming conventions have not been taught in my course yet.
public class 2D_Array {
public static void inputstream(){
File file = new File("data.txt");
try (FileInputStream fis = new FileInputStream(file)) {
int content;
while ((content = fis.read()) != -1) {
readLines("data.txt");
FivebyThree();
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static int FivebyThree() throws IOException {
Scanner sc = new Scanner(new File("data.txt"));
int[] arr = new int[10];
while(sc.hasNextLine()) {
String line[] = sc.nextLine().split("\\s");
int ele = Integer.parseInt(line[1]);
int index = Integer.parseInt(line[0]);
arr[index] = ele;
}
int sum = 0;
for(int i = 0; i<arr.length; i++) {
sum += arr[i];
System.out.print(arr[i] + "\t");
}
System.out.println("\nSum : " + sum);
return sum;
}
public static String[] readLines(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null)
{
lines.add(line);
}
return lines.toArray(new String[lines.size()]);
}
/* int[][] FivebyThree = new int[5][3];
int row, col;
for (row =0; row < 5; row++) {
for(col = 0; col < 3; col++) {
System.out.printf( "%7d", FivebyThree[row][col]);
}
System.out.println();*/
public static void main(String[] args)throws IOException {
inputstream();
}
}
I see that you read data.txt twice and do not use first read result at all. I do not understand, what you want to do with String, but having two-dimension array and calculate sum of columns of int is very easy:
public class Array_2D {
static final class Item {
final String str;
final int val1;
final int val2;
Item(String str, int val1, int val2) {
this.str = str;
this.val1 = val1;
this.val2 = val2;
}
}
private static List<Item> readFile(Reader reader) throws IOException {
try (BufferedReader in = new BufferedReader(reader)) {
List<Item> content = new ArrayList<>();
String str;
while ((str = in.readLine()) != null) {
String[] parts = str.split(" ");
content.add(new Item(parts[0], Integer.parseInt(parts[1]), Integer.parseInt(parts[2])));
}
return content;
}
}
private static void FivebyThree(List<Item> content) {
StringBuilder buf = new StringBuilder();
int sum1 = 0;
int sum2 = 0;
for (Item item : content) {
// TODO do what you want with item.str
sum1 += item.val1;
sum2 += item.val2;
}
System.out.println("str: " + buf);
System.out.println("sum1: " + sum1);
System.out.println("sum2: " + sum2);
}
public static void main(String[] args) throws IOException {
List<Item> content = readFile(new InputStreamReader(Array_2D.class.getResourceAsStream("data.txt")));
FivebyThree(content);
}
}
Sorry for click bait title, but it is my problem, and I can't really change to wording without losing the question.
I have the following code which is meant to select a file, read it, and find it's mode, and I think I got it done, but I have one issue
public class ModeFinder
{
public static int countDoubles(File file) throws FileNotFoundException
{
Scanner reader = new Scanner(file);
int count = 0;
while (reader.hasNextDouble())
{
count++;
reader.nextDouble();
}
reader.close();
return count;
}
public static void main(String args[]) throws FileNotFoundException
{
String filename;
FileDialog filePicker = new FileDialog(new JFrame());
filePicker.setVisible(true);
filename = filePicker.getFile();
String folderName = filePicker.getDirectory();
filename = folderName + filename;
System.out.println("filename = " +filename);
File inputFile = new File(filename);
Scanner fileReader = new Scanner (inputFile);
int maxValue = 0,
maxCount = 0;
int[] a = new int[countDoubles(inputFile)];
while (fileReader.hasNextInt())
{
for (int i = 0; i < a.length; i++)
{
int count = 0;
for (int j = 0; j < a.length; j++)
{
if (a[j] == a[i])
count++;
}
if (count > maxCount)
{
maxCount = count;
maxValue = a[i];
}
}
}
System.out.println("The most common grade is: " +maxValue);
}
}
The last bit with the most common grade doesn't even print and I don't know why.
You aren't calling nextInt to get the value from the file so your while loop is going to loop forever. You need something like:
while (fileReader.hasNextInt())
{
int value = fileReader.nextInt();
...
I'm going to show all of my code here so you guys get a gist of what I'm doing.
import java.io.*;
import java.util.*;
public class Plagiarism {
public static void main(String[] args) {
Plagiarism myPlag = new Plagiarism();
if (args.length == 0) {
System.out.println("Error: No files input");
}
else if (args.length > 0) {
try {
List<String> foo = new ArrayList<String>();
for (int i = 0; i < 2; i++) {
BufferedReader reader = new BufferedReader (new FileReader (args[i]));
foo = simplify(reader);
for (int j = 0; j < foo.size(); j++) {
System.out.print(foo.get(j));
}
}
int blockSize = Integer.valueOf(args[2]);
System.out.println(args[2]);
// String line = foo.toString();
List<String> list = new ArrayList<String>();
for (int k = 0; k < foo.size() - blockSize; k++) {
list.add(foo.toString().substring(k, k+blockSize));
}
System.out.println(list);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
public static List<String> simplify(BufferedReader input) throws IOException {
String line = null;
List<String> myList = new ArrayList<String>();
while ((line = input.readLine()) != null) {
myList.add(line.replaceAll("[^a-zA-Z]","").toLowerCase());
}
return myList;
}
}
This is the code that is using substring.
int blockSize = Integer.valueOf(args[2]);
//"foo" is an ArrayList<String> which I have to convert toString() to use substring().
String line = foo.toString();
List<String> list = new ArrayList<String>();
for (int k = 0; k < line.length() - blockSize; k++) {
list.add(line.substring(k, k+blockSize));
}
System.out.println(list);
When I specify blockSize as 4 in cmd this is the result:
[[, a, , ab, abc ]
the text file (standardised using my other code) is this:
abcdzaabcdd
so the result should be this:
[abcd, bcdz, cdza, ] etc.
Any help?
Thanks in advance.
Here is code showing how to improve a little your code. Main change is returning simplified string from simplify method instead of List<String> of simplified lines, which after converting it to string returned String in form
[value0, value1, value2, ...]
Now code returns String in form value0value1value2.
Another change is lowering indentation lever by removing unnecessary else if statement and braking control flow with System.exit(0); (you can also use return; here).
class Plagiarism {
public static void main(String[] args) throws Exception {
//you are not using 'myPlag' anywhere, you can safely remove it
// Plagiarism myPlag = new Plagiarism();
if (args.length == 0) {
System.out.println("Error: No files input");
System.exit(0);
}
String foo = null;
for (int i = 0; i < 2; i++) {
BufferedReader reader = new BufferedReader(new FileReader(args[i]));
foo = simplify(reader);
System.out.println(foo);
}
int blockSize = Integer.valueOf(args[2]);
System.out.println(args[2]);
List<String> list = new ArrayList<String>();
for (int k = 0; k < foo.length() - blockSize; k++) {
list.add(foo.toString().substring(k, k + blockSize));
}
System.out.println(list);
}
public static String simplify(BufferedReader input)
throws IOException {
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = input.readLine()) != null) {
sb.append(line.replaceAll("[^a-zA-Z]", "").toLowerCase());
}
return sb.toString();
}
}