Elements in Array List to appear on a new line - java

My ArrayList is adding a String each time it loops, however it shows up on one big line. How do I make it to where each String shows up on a new line in JOptionPane as it loops?
Here is my report method:
public String report()
{
return(name + "\t" + height + " inches\t" + weight + " pounds\tBMI: "
+ df.format(bmiValue()) + "\t" + bmiStatus() );
}
And here is the code with the ArrayList:
ArrayList a = new ArrayList();
if(JFileChooser.APPROVE_OPTION)
{
File f = choose.getSelectedFile();
Scanner s = new Scanner(new FileInputStream(f));
int l = scanner.nextInt();
for(int i = 0; i < l; i++)
{
int height = s.nextInt();
int weight = s.nextInt();
String name = s.nextLine();
BmiRecord r = new BmiRecord(name, height, weight);
a.add(r.report());
}
confirm = JOptionPane.showConfirmDialog(null, a, "BMI Calc",
JOptionPane.YES_NO_OPTION);

Your report() function should be:
public String report()
{
return(name + "\t" + height + " inches\t" + weight + " pounds\tBMI: "
+ df.format(bmiValue()) + "\t" + bmiStatus() + "\n");
}
Notice I added the \n which adds a new line to the end of the String returned from the report() function.
Also ArrayList a = new ArrayList(); should be changed to ArrayList<String> a = new ArrayList<String>(); Using the String parameter for the ArrayList ensures type safety as the ArrayList can only hold String objects where as your ArrayList is a raw type that can hold any object and is not type safe.

Related

Error when want to change data in csv file in java

Here is my customer.csv file:
1, Ali,1203456789, Normal
2, Siti,134567890, Normal
3, Bob,1568980765, Normal
I want to change the Normal status of the name I enter to Cased but my code seems got something wrong.And here is my code:
public static void main(String[] args) throws IOException{
Scanner input = new Scanner(System.in);
System.out.println("Please enter the customer you want to flag as Cased:");
String flagCus = input.nextLine();
ArrayList<String> customersFlagged = new ArrayList<String>();
List<String> lines = Files.readAllLines(Paths.get("customer.csv"));
for (int i = 0; i < lines.size(); i++) {
String[] items = lines.get(i).split(",");
if (items[1] == flagCus){
String enterList = items[0] + "," + items[1] + "," + items[2] + "," + "Cased";
customersFlagged.add(enterList);
} else{
String enterList = items[0] + "," + items[1] + "," + items[2] + "," + items[3];
customersFlagged.add(enterList);
}
}
I think the problem is the line if (items[1] == flagCus) ones but I am not sure where got wrong , I have been try to add a " " before my flagCus when doing the if statement but it still goes wrong. Can somebody help me check this code? Thank you for your attention.
Edit:I should have change the code (items[1] == flagCus) to (items[1].equals(" " + flagCus).Thank you guys for help.
When comparing two objects as opposed to primitive types, use .equals() not ==. So:
items[1].equals(flagCus);
To check equal String, use "string".equals("other") instead.
The Strings in the file have a space at the beginning (you are splitting on the commas).
1, Ali,1203456789, Normal
Either remove those from the input data or call:
if (items[1].trim().equals(flagCus)){
(as others have indicated in their answers, use .equals to compare String objects.
complete code:
public static void main(String[] args) throws IOException{
Scanner input = new Scanner(System.in);
System.out.println("Please enter the customer you want to flag as Cased:");
String flagCus = input.nextLine();
ArrayList<String> customersFlagged = new ArrayList<String>();
List<String> lines = Files.readAllLines(Paths.get("customer.csv"));
for (int i = 0; i < lines.size(); i++) {
String[] items = lines.get(i).split(",");
if (items[1].trim().equals(flagCus)){
String enterList = items[0] + "," + items[1] + "," + items[2] + "," + "Cased";
customersFlagged.add(enterList);
} else{
String enterList = items[0] + "," + items[1] + "," + items[2] + "," + items[3];
customersFlagged.add(enterList);
}
}

How to sort ArrayList alphabetically then by number

this is how it looks like before sorting. The book title, year publish
I want to sort the title alphabetically then the year published.
This is my current coding for before sorting:
ArrayList BookList = new ArrayList();
BufferedReader br = new BufferedReader (new FileReader ("bookInput.txt"));
String str = br.readLine();
while (str!=null){
StringTokenizer st = new StringTokenizer(str,";");
String title = st.nextToken();
String yr = st.nextToken();
int year = Integer.parseInt(yr);
Book b1 = new Book (title,year);
BookList.add(b1);
str = br.readLine();
}
br.close();
//3(d)
System.out.println("List of Books" + "( " + BookList.size() + " record(s) ) ");
for (int i = 0; i < BookList.size(); i++){
Book b2 = (Book)BookList.get(i);
System.out.println("#" + (i+1) + " " + b2.getTitle() + " , " + b2.getYear());
}
I've tried everything i know but failed 😅
You can use the Comparator chain assuming Book class has getters:
BookList.sort(Comparator.comparing(Book::getTitle)
.thenComparingInt(Book::getYear));

A program I created in Eclipse has no output when running as a runnable JAR

My code pulls from three text files in order to identify the date/time of the highest value in a list (and display the prior and following five values). Unfortunately, after exporting it as a runnable JAR from Eclipse (I'm including all three text files in the export), it produces absolutely no output. I tried Google and Stack Overflow, but can't seem to find the source of the error. Do you think it's more likely to be an issue with my code, or something I'm doing in Eclipse (e.g. when exporting the file)?
Here is how I'm exporting this as a Runnable Jar File
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
public class FindTheMaxGeiger {
public static void main (String[] args) {
String [] dateStamp = getDate("4_22_18_dates.txt");
String [] timeStamp = getTime("4_22_18_times.txt");
try {
Scanner scanner1 = new Scanner(new File("4_22_18_radiation.txt"));
int radCtr = 0;
while (scanner1.hasNextLine()) {
radCtr++;
scanner1.nextLine();
}
Scanner scanner2 = new Scanner(new File("4_22_18_radiation.txt"));
int [] radiation = new int [radCtr]; //create the radiation array
int i = 0;
while(scanner2.hasNextLine()){
radiation[i++] = scanner2.nextInt();
}
int max = getMax(radiation);
System.out.println("Date Counts per Minute");
System.out.println("-------------------------------");
System.out.println(dateStamp[max-5]+ " " + timeStamp[max-5] + " " + radiation[max-5]);
System.out.println(dateStamp[max-4]+ " " + timeStamp[max-4] + " " + radiation[max-4]);
System.out.println(dateStamp[max-3]+ " " + timeStamp[max-3] + " " + radiation[max-3]);
System.out.println(dateStamp[max-2]+ " " + timeStamp[max-2] + " " + radiation[max-2]);
System.out.println(dateStamp[max-1]+ " " + timeStamp[max-1] + " " + radiation[max-1]);
System.out.println(dateStamp[max]+ " " + timeStamp[max] + " " + radiation[max] + "(This is the max)");
System.out.println(dateStamp[max+1]+ " " + timeStamp[max+1] + " " + radiation[max+1]);
System.out.println(dateStamp[max+2]+ " " + timeStamp[max+2] + " " + radiation[max+2]);
System.out.println(dateStamp[max+3]+ " " + timeStamp[max+3] + " " + radiation[max+3]);
System.out.println(dateStamp[max+4]+ " " + timeStamp[max+4] + " " + radiation[max+4]);
System.out.println(dateStamp[max+5]+ " " + timeStamp[max+5] + " " + radiation[max+5]);
}
catch (FileNotFoundException e){
}
}
//here we call the method to find the max
public static String[] getDate(String file) {
//step 1:
// count the number of lines in the file
//step 2 - create the array and copy the elements in
int ctr = 0;
try {
Scanner s3 = new Scanner(new File(file));
while (s3.hasNextLine()) {
ctr++;
s3.nextLine();
}
String[] dateStamp = new String[ctr]; //creation
Scanner s4 = new Scanner(new File(file));
for (int i = 0; i < ctr; i++) {
dateStamp[i] = s4.next();
}
return dateStamp;
}
catch (FileNotFoundException e){
}
return null;
}
//get time
public static String[] getTime(String file) {
//step 1:
// count the number of lines in the file
//step 2 - create the array and copy the elements in
int ctr = 0;
try {
Scanner s5 = new Scanner(new File(file));
while (s5.hasNextLine()) {
ctr++;
s5.nextLine();
}
String[] timeStamp = new String[ctr]; //creation
Scanner s6 = new Scanner(new File(file));
for (int i = 0; i < ctr; i++) {
timeStamp[i] = s6.next();
}
return timeStamp;
}
catch (FileNotFoundException e){
}
return null;
}
public static int getMax(int[] inputArray){
int maxValue = inputArray[0];
int maxLoc = 0;
for(int i=1;i < inputArray.length;i++){
if(inputArray[i] > maxValue){
maxValue = inputArray[i];
maxLoc = i;
}
}
return maxLoc;}}
as mentioned the files are now compressed and inside the jar and don't live on the file system
use something like InputStream in = this.getClass().getClassLoader().getResourceAsStream("SomeTextFile.txt");
look here for how to convert the inputStream to a String. or it seems that you can use a Scanner directly on the stream. you will need to know the char encoding

JavaFX Loop through array and find a match, otherwise try again

I have a GUI based e-store project. I read in a file and parse through it and saved it into an array.
The file format is like so: 11111, "title", 9.90
11111 is the book id, "title" is title, and 9.90 is the price.
I currently have 3 classes in my project. 1 class for Input/Output, 1 class for the Book store GUI code, and another for pop-up boxes when specific buttons are clicked.
In the GUI code, I check read the file into String[] fileArray and then loop through it until there is a match (with TextField input String bookIds = bookIdinput.getText())
I'm able to successfully get a match and go on with the rest of the code, but when there isn't a match, I get an error: Exception in thread "JavaFX Application Thread" java.lang.NullPointerException at windowDisplay.lambda$start$3(windowDisplay.java:###)
which is this line of code for(int i=0; i<fileArray.length; i++)
If there isn't a match, then it should show a pop-up box saying that bookID isn't found.
Below is some of the GUI code
public class windowDisplay extends Application
{
// Variable declarations
private String[] fileArray = null;
private String holdStr = "";
private Stage mainWindow;
private boolean matchFound = false;
private int count = 1;
private int lineItems = 1;
private double totalAmount = 0.0;
private double subTotal = 0.0;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception
{
// OMITTED CODE
// These TextFields show the output depending on the input TextField's.
itemInfoOutput.setDisable(true);
orderSubtotalOutput.setDisable(true);
// Process item button.
processItem.setText("Process Item #" + count);
processItem.setMinWidth(106);
processItem.setOnAction(e ->
{
int numItems = Integer.parseInt(numItemInput.getText());
lineItems = numItems;
String bookIDs = bookIdInput.getText();
int qtyItems = Integer.parseInt(qtyItemInput.getText());
// Read file and check for Book ID
fileArray = bookStoreIO.readFile(bookIDs);
// Loop through array to find match or no matches
for(int i=0; i<fileArray.length; i++)
{
// If there is a match in book ID
if (fileArray[i].equals(bookIDs))
{
double price = Double.parseDouble(fileArray[i + 2]); // Price is in the i+2 position
double discount = calculateDiscount(qtyItems);
totalAmount = calculatePrice(qtyItems, price);
itemInfoOutput.setText(fileArray[i] + " " + fileArray[i + 1] + " " + "$" + price + " " +
qtyItems + " " + discount + "%" + " " + "$" + df.format(totalAmount));
// Disable processItem Button if there is a match and enable confirmItem Button
processItem.setDisable(true);
confirmItem.setDisable(false);
matchFound = true;
}
}
if(matchFound == false)
System.out.println("No match found!");
});
}
// OMITTED CODE
// This method calculates the discount depending on the quantity of items
public static double calculateDiscount(int inputQty){return null;}
// This methdod calculates the price with the discount
public static double calculatePrice(int inputQty, double price){return null;}
}
This class reads the file and returns an array with the contents of that file (once split by the ", " delimitter).
public class bookStoreIO
{
// This method reads the input file "inventory.txt" and saves it into an array.
public static String[] readFile(String stringIn)
{
try
{
String nextLine;
String[] fIn;
// Read file
BufferedReader br = new BufferedReader(new FileReader("inventory.txt"));
while((nextLine = br.readLine()) != null)
{
fIn = nextLine.split(", "); // Split when ", " is seen
if(stringIn.equalsIgnoreCase(fIn[0]))
{
br.close(); // Close file
return fIn; // Return array
}
}
}
// Just in case file isn't found
catch(IOException e)
{
System.out.println("File not found.");
}
return null;
}
I apologize if this seems messy, I'm still new to JavaFX and Java programming.
If you think more code is needed, please let me know!
EDIT: I improved some variable naming and removed the for loop. I'm still having trouble checking when there isn't a match.
public class windowDisplay extends Application
{
// Variable declarations
private String[] fileArray = null;
private Stage mainWindow;
private boolean matchFound = false;
private int count = 1;
private int lineItems = 1;
private double totalAmount = 0.0;
private double subTotal = 0.0;
private int itemQty = 0;
private int idBook = 0;
private String bookTitle = "";
private double bookPrice = 0.0;
private double discountAmount = 0.0;
private String resultOrder = "";
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception
{
// OMITTED CODE
// These TextFields show the output depending on the input TextField's.
itemInfoOutput.setDisable(true);
orderSubtotalOutput.setDisable(true);
// Process item button.
processItem.setText("Process Item #" + count);
processItem.setMinWidth(106);
processItem.setOnAction(e ->
{
int numItems = Integer.parseInt(numItemInput.getText());
lineItems = numItems;
String bookIDs = bookIdInput.getText();
itemQty = Integer.parseInt(qtyItemInput.getText());
// Read file and check for Book ID
fileArray = bookStoreIO.readFile(bookIDs);
idBook = Integer.parseInt(fileArray[0]);
bookTitle = fileArray[1];
bookPrice = Double.parseDouble(fileArray[2]);
discountAmount = calculateDiscount(itemQty);
totalAmount = calculatePrice(itemQty, bookPrice);
itemInfoOutput.setText(idBook + " " + bookTitle + " $" + bookPrice + " " + itemQty + " " + discountAmount
+ "% $" + df.format(totalAmount));
itemInfo.setText("Item #" + count + " info:");
processItem.setDisable(true);
confirmItem.setDisable(false);
matchFound = true;
if(matchFound == false)
System.out.println("not found");
});
// OMITTED CODE
// This method calculates the discount depending on the quantity of items
public static double calculateDiscount(int inputQty){return null;}
// This method calculates the price with the discount
public static double calculatePrice(int inputQty, double price){return null;}
}
I'm also having trouble saving
itemInfoOutput.setText(idBook + " " + bookTitle + " $" + bookPrice + " " + itemQty + " " + discountAmount
+ "% $" + df.format(totalAmount));
into an String or String array to print out a list of all the corresponding matches (along with their book ID, book Title, book Price, quantity, discount , and total price).
An example is shown below:
enter image description here
EDIT 2: The right box is the main GUI. The bottom left box is what shows up when a wrong book is entered (on the 2nd order). The top left is the length of the array.
// Process item button.
processItem.setText("Process Item #" + count);
processItem.setMinWidth(106);
processItem.setOnAction(e ->
{
int numItems = Integer.parseInt(numItemInput.getText());
lineItems = numItems;
String bookIDs = bookIdInput.getText();
itemQty = Integer.parseInt(qtyItemInput.getText());
// Read file and check for Book ID
fileArray = bookStoreIO.readFile(bookIDs);
for(int i=0; i<fileArray.length; i++)
System.out.println(fileArray[i]);
if(fileArray.length >= 3)
{
idBook = Integer.parseInt(fileArray[0]);
bookTitle = fileArray[1];
bookPrice = Double.parseDouble(fileArray[2]);
discountAmount = calculateDiscount(itemQty);
totalAmount = calculatePrice(itemQty, bookPrice);
resultOrder = itemInfoOutput.getText();
itemInfoOutput.setText(idBook + " " + bookTitle + " $" + bookPrice + " " + itemQty + " " + discountAmount
+ "% $" + df.format(totalAmount));
resultOrder = idBook + " " + bookTitle + " $" + bookPrice + " " + itemQty + " " + discountAmount
+ "% $" + df.format(totalAmount);
itemInfo.setText("Item #" + count + " info:");
processItem.setDisable(true);
confirmItem.setDisable(false);
}
else
alertBox.confirmDisplay("Book ID " + idBook + " not in file");
});

I'm trying to use 2 user inputs to populate a 2d list array

I'm trying to populate a 2d list array using 2 user inputs.
Problem I'm having is that in the code below, the 1st for statement isn't producing the outcome I'm expecting, the 2nd for is doing what is needed. Also, with the code below I'm unable to close scanner.
public static void main(String[] args) {
ArrayList<String> listCon = new ArrayList<String>();
ArrayList<String> listCol = new ArrayList<String>();
Scanner txtInput = new Scanner(System.in);
char addTo = 'y';
do {
System.out.println("\nCurrent list is " + listCon + listCol + "\n");
System.out.println("Would you like to add a country to the list?\n\t"
+ "( y ) = YES\n\t( n ) = NO");
addTo = txtInput.next().toLowerCase().charAt(0);
if (addTo == 'y') {
System.out.println("Enter country name: ");
listCon.add(txtInput.next().toLowerCase());
System.out.println("Enter colour: ");
listCol.add(txtInput.next().toLowerCase());
} else if (addTo == 'n') {
int i = 1;
int countCon = listCon.size();
if(countCon == 0) {
System.out.println("No countries have been entered.");
} else {
String str = "country";
if(countCon > 1) {
str = "countries";
}
System.out.println("Thankyou for your input. We found " + countCon + " " +
str + " in the list.");
System.out.println("Listed " + str + ":\n");
for(String n : listCon) {
char[] conDigit = n.toCharArray();
conDigit[0] = Character.toUpperCase(conDigit[0]);
n = new String(conDigit);
for(String b : listCol) {
char[] colDigit = b.toCharArray();
colDigit[0] = Character.toUpperCase(colDigit[0]);
b = new String(colDigit);
System.out.println("Country " + i + " : " + n + " - \t" + b);
i = i + 1;
}
break;
}
break;
}
} else {
System.out.println("Incorrect input detected. please try again. \n");
}
} while (true);
}
}
You need to remove extra break from the first for loop to iterate. Otherwise, you break after first iteration.
for(String n : listCon) {
....
for(String b : listCol) {
...
}
break; //remove this!
}
break;
EDIT
The result im after is Country 1 : France - Blue Country 2 : UK -
White Country 3 : Ireland - Green
You need to iterate like this:
for (int i = 0; i < listCon.size() && i < listCol.size(); i++) {
String n = listCon.get(i);
char[] conDigit = n.toCharArray();
conDigit[0] = Character.toUpperCase(conDigit[0]);
n = new String(conDigit);
String b = listCol.get(i);
char[] colDigit = b.toCharArray();
colDigit[0] = Character.toUpperCase(colDigit[0]);
b = new String(colDigit);
System.out.println("Country " + i + " : " + n + " - \t" + b);
}

Categories