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.
Related
I want to take a string input in
%d+%d
format in java.How do i do it?
I know that I can do this with string.split() method. But I feel that it is going to be way more complex if I had to deal with more strings in input. Like
%d+%d-%d
I am looking for solutions that are close to a scanf solution for c.
I tried this for %d+%d
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
String first,second;
String[] arr = str.split("\\+");
first = arr[0];
second = arr[1];
scanner.close();
And this for %d+%d-%d+%d..........=%d-%d+%d.....+%d...
private final String[] splitLoL(String txt) {
LinkedList<String> strList1 = new LinkedList<String>();
LinkedList<String> strList2 = new LinkedList<String>();
LinkedList<String> strList3 = new LinkedList<String>();;
strList1.addAll(Arrays.asList(txt.split("\\+")));
for(String str : strList1) {
String[] proxy = str.split("-");
strList2.addAll(Arrays.asList(proxy));
}
for(String str : strList2) {
String[] proxy = str.split("=");
strList3.addAll(Arrays.asList(proxy));
}
String[] strArr = new String[strList3.size()];
for(int i = 0; i < strArr.length; i++) {
strArr[i] = new String(strList3.get(i));
}
return strArr;
}
Try this:
String str = scanner.nextLine();
List<String> str2 = new ArrayList();
Matcher m = Pattern.compile("\\d+").matcher(str);
while(m.find()) {
str2.add(m.group());
}
Or you can do the following using JDK 9+:
import java.util.Scanner;
public class ScannerTrial {
public static void main(String[] args) {
Scanner scanner = new Scanner(" 4 z zz ggg 22 e");
scanner.findAll("\\d+").forEach((e) -> System.out.println(e.group()));
}
}
This would print
4 22
I'm trying to import a txt file with car info and separate the strings into arrays and then display them. The number of doors is combined with the next number plate. Have tried a few ways to get rid of the whitespace characters which I think is causing the issue but have had no luck.
whitespace chars
My code displays this result:
Number Plate : AG53DBO
Car Type : Mercedes
Engine Size : 1000
Colour : (255:0:0)
No. of Doors : 4
MD17WBW
Number Plate : 4
MD17WBW
Car Type : Volkswagen
Engine Size : 2300
Colour : (0:0:255)
No. of Doors : 5
ED03HSH
Code:
public class Application {
public static void main(String[] args) throws IOException {
///// ---- Import File ---- /////
String fileName =
"C:\\Users\\beng\\eclipse-workspace\\Assignment Trailblazer\\Car Data";
BufferedReader reader = new BufferedReader(new FileReader(fileName));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
String ls = System.getProperty("line.separator");
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
reader.close();
String content = stringBuilder.toString();
///// ---- Split file into array ---- /////
String[] dataList = content.split(",");
// Display array
for (String temp : dataList) {
// System.out.println(temp);
}
ArrayList<Car> carArray = new ArrayList();
// Loop variables
int listLength = 1;
int arrayPosition = 0;
// (dataList.length/5)
while (listLength < 5) {
Car y = new Car(dataList, arrayPosition);
carArray.add(y);
listLength++;
arrayPosition += 4;
}
for (Car temp : carArray) {
System.out.println(temp.displayCar());
}
}
}
And
public class Car {
String[] data;
private String modelUnpro;
private String engineSizeUnpro;
private String registrationUnpro;
private String colourUnpro;
private String doorNoUnpro;
// Constructor
public Car(String[] data, int arrayPosition) {
registrationUnpro = data[arrayPosition];
modelUnpro = data[arrayPosition + 1];
engineSizeUnpro = data[arrayPosition + 2];
colourUnpro = data[arrayPosition + 3];
doorNoUnpro = data[arrayPosition + 4];
}
// Getters
private String getModelUnpro() {
return modelUnpro;
}
private String getEngineSizeUnpro() {
return engineSizeUnpro;
}
private String getRegistrationUnpro() {
return registrationUnpro;
}
private String getColourUnpro() {
return colourUnpro;
}
private String getDoorNoUnpro() {
return doorNoUnpro;
}
public String displayCar() {
return "Number Plate : " + getRegistrationUnpro() + "\n Car Type : " + getModelUnpro() + "\n Engine Size : "
+ getEngineSizeUnpro() + "\n Colour : " + getColourUnpro() + "\n No. of Doors : " + getDoorNoUnpro() + "\n";
}
}
Text file:
AG53DBO,Mercedes,1000,(255:0:0),4
MD17WBW,Volkswagen,2300,(0:0:255),5
ED03HSH,Toyota,2000,(0:0:255),4
OH01AYO,Honda,1300,(0:255:0),3
WE07CND,Nissan,2000,(0:255:0),3
NF02FMC,Mercedes,1200,(0:0:255),5
PM16DNO,Volkswagen,1300,(255:0:0),5
MA53OKB,Honda,1400,(0:0:0),4
VV64BHH,Honda,1600,(0:0:255),5
ER53EVW,Ford,2000,(0:0:255),3
Remove Line separator from while loop.
String fileName = "D:\\Files\\a.txt";
BufferedReader reader = new BufferedReader(new FileReader(fileName));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line.trim());
}
reader.close();
String content = stringBuilder.toString();
String[] dataList = content.split(",");
ArrayList<Car> carArray = new ArrayList();
int listLength = 1;
int arrayPosition = 0;
// (dataList.length/5)
while (listLength < 3) {
Car y = new Car(dataList, arrayPosition);
carArray.add(y);
listLength++;
arrayPosition += 4;
}
for (Car temp : carArray) {
System.out.println(temp.displayCar());
}
In StringBuilder you collect all lines:
AG53DBO,Mercedes,1000,(255:0:0),4\r\nMD17WBW,Volkswagen,2300,(0:0:255),5\r\n...
This string should first be spit on ls - and then you have lines with fields separated by comma.
Now just splitting by comma will cause a doubled array element 4\r\nMD17WBW.
Something like:
String fileName =
"C:\\Users\\beng\\eclipse-workspace\\Assignment Trailblazer\\Car Data";
Path path = Paths.get(fileName);
List<String> lines = Files.readAllLines(path); // Without line ending.
List<Car> cars = new ArrayList<>();
for (String line : lines) {
String[] data = line.split(",");
Car car = new Car(data);
cars.add(car);
}
Path, Paths and especially Files are very handy classes. With java Streams one also can abbreviate things like:
String fileName =
"C:\\Users\\beng\\eclipse-workspace\\Assignment Trailblazer\\Car Data";
Path path = Paths.get(fileName);
List<Car> cars = Files.lines(path) // Stream<String>
.map(line -> line.split(",")) // Stream<String[]>
.map(Car::new) // Stream<Car>
.collect(Collectors.toList()); // List<Car>
Here .lines returns a Stream<String> (walking cursor) of lines in the file, without line separator.
Then .map(l -> l.split(",")) splits every line.
Then the Car(String[]) constructor is called on the string array.
Then the result is collected in a List.
I have this code, it gets the average grade, but I need to export the arraylist Hell to a CSV file. How do I do this?
import java.util.*;
import java.io.*;
import java.io.PrintWriter;
import java.text.*;
public class hello3 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.printf("Please enter the name of the input file: ");
String input_name = in.next();
System.out.printf("Please enter the name of the output CSV file: ");
String csv_name = in.next();
System.out.printf("Please enter the name of the output pretty-print file: ");
String pretty_name = in.next();
processGrades(input_name, csv_name, pretty_name);
System.out.printf("\nExiting...\n");
}
public static void processGrades (String input_name, String csv_name, String pretty_name)
{
PrintWriter csv = null;
PrintWriter pretty = null;
String[][] data = readSpreadsheet(input_name);
boolean resultb = sanityCheck(data);
int length = data.length;
ArrayList<String> test_avg = new ArrayList<String>();
ArrayList<String> HW_avg = new ArrayList<String>();
ArrayList<String> NAME = new ArrayList<String>();
ArrayList<String> ColN = new ArrayList<String>();
ArrayList<String> Hell = new ArrayList<String>();
for(int row = 1; row<length; row++)
{
String name = data[row][0];
String name2 = data[row][1];
String Name = name+" "+name2;
int test1 = Integer.parseInt(data[row][2]);
int test2 = Integer.parseInt(data[row][3]);
int test3 = Integer.parseInt(data[row][4]);
int Test = (test1+test2+test3)/3;
String Testav = Integer.toString(Test);
int hw1 = Integer.parseInt(data[row][5]);
int hw2 = Integer.parseInt(data[row][6]);
int hw3 = Integer.parseInt(data[row][7]);
int hw4 = Integer.parseInt(data[row][8]);
int hw5 = Integer.parseInt(data[row][9]);
int hw6 = Integer.parseInt(data[row][10]);
int hw7 = Integer.parseInt(data[row][11]);
int HW = (hw1+hw2+hw3+hw4+hw5+hw6+hw7)/7;
int[] trying = {Test, HW};
int low = find_min(trying);
String grade = null;
if(low>=90)
{
grade ="A";
}
if(low < 90&& low>= 80)
{
grade = "B";
}
if(low <80&&low>=70)
{
grade ="C";
}
if(low<70&&low>=60)
{
grade="D";
}
if(low<60)
{
grade = "F";
}
String Lows = Integer.toString(low);
String HWav = Integer.toString(HW);
test_avg.add(Testav);
HW_avg.add(HWav);
NAME.add(Name);
Hell.add(Name);
Hell.add(Testav);
Hell.add(HWav);
Hell.add(Lows);
Hell.add(grade);
System.out.println(Hell);
System.out.printf("\n");
}
}
public static int find_min(int[] values)
{
int result = values[0];
for(int i = 0; i<values.length; i++)
{
if(values[i]<result)
{
result = values[i];
}
}
return result;
}
public static boolean sanityCheck(String[][] data)
{
if (data == null)
{
System.out.printf("Sanity check: nul data\n");
return false;
}
if(data.length<3)
{
System.out.printf("Sanity check: %d rows\n",data.length);
return false;
}
int cols= data[0].length;
for(int row = 0; row<data.length; row++)
{
int current_cols = data[row].length;
if(current_cols!=cols)
{
System.out.printf("Sanity Check: %d columns at rows%d\n", current_cols, row);
return false;
}
}
return true;
}
public static String[][] readSpreadsheet(String filename)
{
ArrayList<String> lines = readFile(filename);
if (lines == null)
{
return null;
}
int rows = lines.size();
String[][] result = new String[rows][];
for (int i = 0; i < rows; i++)
{
String line = lines.get(i);
String[] values = line.split(",");
result[i] = values;
}
return result;
}
public static ArrayList<String> readFile(String filename)
{
File temp = new File(filename);
Scanner input_file;
try
{
input_file = new Scanner(temp);
} catch (Exception e)
{
System.out.printf("Failed to open file %s\n",
filename);
return null;
}
ArrayList<String> result = new ArrayList<String>();
while (input_file.hasNextLine())
{
String line = input_file.nextLine();
result.add(line);
}
input_file.close();
return result;
}
}
Any help would be appreciated. thank you.
Broadly, you need to open a file with the name you require, and a writer in a loop - like this:
File csvFile = new File(csvName);
try (PrintWriter csvWriter = new PrintWriter(new FileWriter(csvFile));){
for(String item : list){
csvWriter.println(item);
}
} catch (IOException e) {
//Handle exception
e.printStackTrace();
}
Obviously you will have to print some commas as required
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.
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?