I have a simple problem.
I wrote a method in java to get the contents of text file.
public static String[] viewSuppliers()
{
Scanner x = null;
try{
x = new Scanner(new File("C:\\Users\\فاطمة\\Downloads\\suppliers.txt"));
while(x.hasNext())
{
String a = x.next();
String b = x.next();
String c = x.next();
String d = x.next();
String array[] = {a,b,c,d};
return array;
}
x.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
I have called this method in main program but it only returns one line of the file. The contents of my text file are like this:
PEPSI John London 214222
COLA Sarah France 478800
Here is my main program:
String array3[] = {"Supplier Company: ", "Supplier Name: ", "Supplier Address: ",
"Supplier Phone Number: "};
String array4[] = i.viewSuppliers(); // object of class
if(i.viewSuppliers() == null)
System.out.println("No current suppliers.");
else
{
System.out.println("Current Suppliers: ");
for(int u = 0; u < array3.length; u++)
{
System.out.printf(array3[u]);
System.out.println(array4[u]);
}
}
When i run the main program and call the method it is only return the first line and i want to return all the file.
Instead of returning an array of 4 strings,
it seems what you really want is to return a list of array of 4 strings:
public static List<String[]> viewSuppliers()
{
List<String[]> lines = new ArrayList<>();
Scanner x = null;
try{
x = new Scanner(new File("C:\\Users\\فاطمة\\Downloads\\suppliers.txt"));
while(x.hasNext())
{
String a = x.next();
String b = x.next();
String c = x.next();
String d = x.next();
String array[] = {a,b,c,d};
lines.add(array);
}
x.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return lines;
}
Then, iterate over the results:
List<String[]> list = i.viewSuppliers(); // object of class
if (list.isEmpty())
System.out.println("No current suppliers.");
else
{
System.out.println("Current Suppliers: ");
for (String[] supplier : list) {
for(int u = 0; u < array3.length; u++)
{
System.out.printf(array3[u]);
System.out.println(supplier[u]);
}
}
}
Try take the return out of the while loop, otherwise after the first iteration it returns.
You have the output on a loop based on the length of array3, but not array4, so it will always only print the first supplier because of the length of array3.
System.out.println("Current Suppliers: ");
for(int u = 0; u < array3.length; u++)
{
System.out.printf(array3[u]);
System.out.println(array4[u]);
}
Perhaps adding the System.out.println(array4) to a loop based on its length below the first loop.
Related
I am trying to write 2 different arrays to a csv. The first one I want in the first column, and second array in the second column, like so:
array1val1 array2val1
array1val2 array2val2
I am using the following code:
String userHomeFolder2 = System.getProperty("user.home") + "/Desktop";
String csvFile = (userHomeFolder2 + "/" + fileName.getText() + ".csv");
FileWriter writer = new FileWriter(csvFile);
final String NEW_LINE_SEPARATOR = "\n";
FileWriter fileWriter;
CSVPrinter csvFilePrinter;
CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
fileWriter = new FileWriter(fileName.getText());
csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
try (PrintWriter pw = new PrintWriter(csvFile)) {
pw.printf("%s\n", FILE_HEADER);
for(int z = 0; z < compSource.size(); z+=1) {
//below forces the result to get stored in below variable as a String type
String newStr=compSource.get(z);
String newStr2 = compSource2.get(z);
newStr.replaceAll(" ", "");
newStr2.replaceAll(" ", "");
String[] explode = newStr.split(",");
String[] explode2 = newStr2.split(",");
pw.printf("%s\n", explode, explode2);
}
}
catch (Exception e) {
System.out.println("Error in csvFileWriter");
e.printStackTrace();
} finally {
try {
fileWriter.flush();
fileWriter.close();
csvFilePrinter.close();
} catch (IOException e ) {
System.out.println("Error while flushing/closing");
}
}
However I am getting a strange output into the csv file:
[Ljava.lang.String;#17183ab4
I can run
pw.printf("%s\n", explode);
pw.printf("%s\n", explode2);
Instead of : pw.printf("%s\n", explode, explode2);
and it prints the actual strings but all in one same column.
Does anyone know how to solve this?
1.Your explode and explode2 are actually String Arrays. You are printing the arrays and not the values of it. So you get at the end the ADRESS of the array printed.
You should go through the arrays with a loop and print them out.
for(int i = 0; i<explode.length;++i) {
pw.printf("%s%s\n", explode[i], explode2[i]);
}
2.Also the method printf should be look something like
pw.printf("%s%s\n", explode, explode2);
because youre are printing two arguments, but in ("%s\n", explode, explode2) is only one printed.
Try it out and say if it worked
After these lines:
newStr.replaceAll(" ", "");
newStr2.replaceAll(" ", "");
String[] explode = newStr.split(",");
String[] explode2 = newStr2.split(",");
Use this code:
int maxLength = Math.max(explode.length, explode2.length);
for (int i = 0; i < maxLength; i++) {
String token1 = (i < explode.length) ? explode[i] : "";
String token2 = (i < explode2.length) ? explode2[i] : "";
pw.printf("%s %s\n", token1, token2);
}
This also cover the case that the arrays are of different length.
I have removed all unused variables and made some assumptions about content of compSource.
Moreover, don't forget String is immutable. If you just do "newStr.replaceAll(" ", "");", the replacement will be lost.
public class Tester {
#Test
public void test() throws IOException {
// I assumed compSource and compSource2 are like bellow
List<String> compSource = Arrays.asList("array1val1,array1val2");
List<String> compSource2 = Arrays.asList("array2val1,array2val2");
String userHomeFolder2 = System.getProperty("user.home") + "/Desktop";
String csvFile = (userHomeFolder2 + "/test.csv");
try (PrintWriter pw = new PrintWriter(csvFile)) {
pw.printf("%s\n", "val1,val2");
for (int z = 0; z < compSource.size(); z++) {
String newStr = compSource.get(z);
String newStr2 = compSource2.get(z);
// String is immutable --> store the result otherwise it will be lost
newStr = newStr.replaceAll(" ", "");
newStr2 = newStr2.replaceAll(" ", "");
String[] explode = newStr.split(",");
String[] explode2 = newStr2.split(",");
for (int k = 0; k < explode.length; k++) {
pw.println(explode[k] + "\t" + explode2[k]);
}
}
}
}
}
I have a list of strings. First element is:
2 helloworld 10173.991234
I've written the code below:
ArrayList<Integer> idList = new ArrayList<Integer>();
for (String s:list){
String subs = s.substring(0,8);
subs = subs.trim();
idList.add(Integer.valueOf(subs));
}
This code shoud parse first id field and add it to arraylist.
But it fails on line idList.add(Integer.valueOf(subs));
Whats the problem? Any help?
Upd:
public class Solution {
public static void main(String[] args) throws Exception {
if (args[0].equals("-c")) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String fileString = reader.readLine();
reader.close();
Scanner scanner = new Scanner(new File(fileString));
ArrayList<String> list = new ArrayList<String>();
while (scanner.hasNextLine()) {
list.add(scanner.nextLine());
}
String ne = list.get(list.size()-1);
scanner.close();
int maxId;
if (ne.length()>1) {
ArrayList<Integer> idList = new ArrayList<Integer>();
for (String s:list){
String subs = s.substring(0,8);
subs = subs.trim();
idList.add(Integer.parseInt(subs));
}
maxId = idList.get(0);
for (int i:idList){
if (maxId<i){
maxId=i;
}
}
maxId++;
}
else {
maxId = 0;
}
String maxIdString = ""+maxId;
while (maxIdString.length()<8){
maxIdString+=" ";
}
if (maxIdString.length()>8){
maxIdString = maxIdString.substring(0,8);
}
String productName = "";
for (int i = 1; i < args.length-2; i++) {
productName+=args[i]+" ";
}
productName = productName.trim();
while (productName.length()<30){
productName+=" ";
}
if (productName.length()>30)
productName=productName.substring(0,30);
String price = args[args.length-2];
while (price.length()<8){
price+=" ";
}
if (price.length()>8)
price=price.substring(0,8);
String quantity = args[args.length-1];
while (quantity.length()<4){
quantity+=" ";
}
if (quantity.length()>4)
quantity=quantity.substring(0,4);
String outString = maxIdString+productName+price+quantity;
FileOutputStream outputStream = new FileOutputStream(fileString,true);
if (ne.length()>1)
outputStream.write("\r\n".getBytes());
outputStream.write(outString.getBytes());
outputStream.close();
}
}
}
It's the content of the file
2 helloworld 10173.991234
124 helloworld 10173.991234
125 helloworld 10173.991234
Program arguments, for example:
-c helloworld 10173.99 1234
I found what the problem was :) It was in UTF-8 coding. I understood it after starting to use Notepad++ application.
I have tried so hard to find a solution to this problem! Here is my code:
import java.io.*;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class Weather {
public static void main(String[] args) throws IOException {
//Getting the file.
String fileName = "weather2013.txt";
//Lines!
String line;
//Creating arrayList object
ArrayList aList = new ArrayList();
try {
BufferedReader input = new BufferedReader(new FileReader(fileName));
while ((line = input.readLine()) != null) {
aList.add(line);
}
//Close the file
input.close();
} catch (FileNotFoundException ex) {
System.out.println("File not found!");
}
//Station ID Number:
String firstLine = aList.get(1).toString();
String stationIDStr = firstLine.substring(0, 6);
int StationID = Integer.parseInt(stationIDStr);
//System.out.println(StationID);
//WBAN ID Number:
String wbanIDstr = firstLine.substring(7, 12);
int wbanID = Integer.parseInt(wbanIDstr);
//System.out.println(wbanID);
//Year!
String yearStr = firstLine.substring(12, 18).trim();
int year = Integer.parseInt(yearStr);
//System.out.println(year);
//Remove line of text (not needed)
aList.remove(0);
//Fog days:
int fogDays = 0;
for (int i = 0; i < aList.size(); i++) {
String listString = aList.get(i).toString(); //iterate each readLINE -> String
String lastDigits = listString.substring(132, 137); //Each entry from 132-137 only
char fogIndicator = lastDigits.charAt(0);
if (fogIndicator == '1') {
fogDays++;
}
}
//System.out.println(fogDays);
//Maximum and minimum average temps
for (int i = 0; i < aList.size(); i++) {
String listString = aList.get(i).toString();
String averageTempDigits = listString.substring(24, 30).trim();
}
}
}
The specific part of the code where I am having trouble is the VERY last for loop.
Here's what's being outputted:
47.9
41.8
.
.
.
.
41.8
67.0
66.5
I would like to know how to get this column above into an Array or ArrayList?
I want to search in an arraylist from a user input but my if condition doesn't seem to work. Using boolean and .contains() doesn't work for my programme either. This is the coding:
String phone;
phone=this.text1.getText();
System.out.println("this is the phone: " + phone);
BufferedReader line = new BufferedReader(new FileReader(new File("C:\\Users\\Laura Sutardja\\Documents\\IB DP\\Computer Science HL\\cs\\data.txt")));
String indata;
ArrayList<String[]> dataArr = new ArrayList<String[]>();
while ((indata = line.readLine()) != null) {
String[] club = new String[2];
String[] value = indata.split(",", 2);
//for (int i = 0; i < 2; i++) {
int n = Math.min(value.length, club.length);
for (int i = 0; i < n; i++) {
club[i] = value[i];
}
boolean aa = dataArr.contains(this.text1.getText());
if(aa==true)
text2.setText("The data is found.");
else
text2.setText("The data is not found.");
dataArr.add(club);
}
for (int i = 0; i < dataArr.size(); i++) {
for (int x = 0; x < dataArr.get(i).length; x++) {
System.out.printf("dataArr[%d][%d]: ", i, x);
System.out.println(dataArr.get(i)[x]);
}
}
}
catch ( IOException iox )
{
System.out.println("Error");
}
Your dataArr is a list of String[], and you are searching for a String. The two are different kind of objects.
I don't really know how the content of the club array looks like, but you should either change dataArr in order to hold plain String, or to write a method which looks iteratively in dataArr for a String[] containing the output of this.text1.getText().
There is a lot wrong with the program. I assume you want to read a textfile and store each line in the arraylist. To do this you have to split each line of the textfile and store that array in the arrayList.
String[] value;
while ((indata = line.readLine()) != null) {
value = indata.split(",");
dataArr.add(value);
}
Now you have the contents of the file in the arrayList.
Next you want to compare the userinput with each element of the arraylist.
int j = 0;
for (int i = 0; i < dataArr.size(); i++) {
String[] phoneData = dataArr.get(i);
if (phoneData[1].equals(phone)) { // i am assuming here that the phone number is the 2nd element of the String[] array, since i dont know how the textfile looks.
System.out.println("Found number.");
club[j++] = phoneData[1];
} else if (i == dataArr.size()-1) {
System.out.println("Didn't find number.");
}
}
Edit:
As requested:
String phone;
phone = "38495";
System.out.println("this is the phone: " + phone);
BufferedReader line = new BufferedReader(new FileReader(new File("list.txt")));
String indata;
ArrayList<String[]> dataArr = new ArrayList<>();
String[] club = new String[2];
String[] value;// = indata.split(",", 2);
while ((indata = line.readLine()) != null) {
value = indata.split(",");
dataArr.add(value);
}
int j = 0;
for (int i = 0; i < dataArr.size(); i++) {
String[] phoneData = dataArr.get(i);
if (phoneData[1].equals(phone)) {
System.out.println("Found number.");
club[j++] = phoneData[1];
break;
} else if (i == dataArr.size()-1) {
System.out.println("Didn't find number.");
}
}
I hope this makes sense now.
So I have a file that has names along with 11 popularity ranks which looks like this. <--- (this is a link) I am a bit confused on what I am suppose to do with this next part that I have for my assignment. Generally I have a name app that looks like this:
public class Name{
private String givenName;
private int[] ranks = new int[11];
public Name(String name, int[] popularityRanks){
givenName = name;
for (int i = 0; i < 11; i++){
ranks[i] = popularityRanks[i];
}
}
public String getName(){
return givenName;
}
public int getPop(int decade){
if (decade >= 1 && decade <= 11){
return ranks[decade];
}
else{
return -1;
}
}
public String getHistoLine(int decade){
String histoLine = ranks[decade] + ": ";
return histoLine;
}
public String getHistogram(){
String histogram = "";
for (int i = 0; i < 11; i++){
histogram += ranks[i] + ": " + this.getHistoLine(i)
+ "\n";
}
return histogram;
}
}
It is not finished for the getHistoLine but that doesn't have anything to do with what I am trying to do. Generally I want to take these names in from the file and create an array of list.
How he describes it:
Create the array in main, pass it to the readNamesFile method and let that method fill it with Name objects
Test this, by printing out various names and their popularity rankings
For example, if main named the array, list, then upon return from the readNamesFile method do something like:
System.out.println( list[0].getName() + list[0].getPop(1) );
This is what my main looks like:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class NameApp{
public static void main(String[] args){
Name list[] = new Name()
}
private static void loadFile(){
Scanner inputStream = null;
String fileName = "names.txt";
try {
inputStream = new Scanner (new File(fileName));
}
catch (FileNotFoundException e){
System.out.println("Error opening file named: " + fileName);
System.out.println("Exiting...");
}
while (inputStream.hasNext()){
}
}
}
I am just a bit confused how I can take the name have it send to the Name object list[] and then take the popularity ranks and send it to the Name object list[]. So when I call
list[0].getName()
it will just call the name for one of the lines... Sorry I am a bit new to the java language. Thanks in advance
You need to create a Name list correctly. I would use a List since you don't know how many names there will be;
public static void main(String[] args){
List<Name> list = new ArrayList<Name>();
loadFile();
System.out.println(list.get(0).getPop());
}
private static void loadFile(){
Scanner inputStream = null;
String fileName = "names.txt";
try {
inputStream = new Scanner (new File(fileName));
}
catch (FileNotFoundException e){
System.out.println("Error opening file named: " + fileName);
System.out.println("Exiting...");
}
while (inputStream.hasNext()){
// givenName = something
// ranks = something;
list.add(new Name(givenName, ranks);
}
}
Assuming each line is something like this (from your deleted comment)
A 1 234 22 43 543 32 344 32 43
Your while loop can be something like this
while (inputStream.hasNextLIne()){
String line = inputStream.nextLine();
String tokens = line.split("\\s+");
String givenName = tokens[0];
int[] numList = new int[tokens.lenth - 1];
for (int i = 1; i < tokens.length; i++){
numList[i - 1] = Integer.parseInt(tokens[i].trim());
}
list.add(new Name(givenName, numList);
}