Error when want to change data in csv file in java - 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);
}
}

Related

storing values with .nextLine() in array skipping lines

My previous question was closed, but the answer suggested wasn't much help to me. Sorry for the inconvenience.
I'm trying to store fname, lname, address, city, state, and zip in array customerData[30][6]. However, it seems to be skipping lines where I'd input the information.
Code
public void addCustomer() throws IOException {
Scanner scan = new Scanner(System.in);
int numCustomers = 0;
String[][] customerData = new String[30][7];
System.out.println("how many customers");
numCustomers = scan.nextInt();
BufferedWriter writer = new BufferedWriter(
new FileWriter("/Users/simonshamoon/eclipse-workspace/Final Project/src/customerdata.txt"));
BufferedWriter loginWriter = new BufferedWriter(
new FileWriter("/Users/simonshamoon/eclipse-workspace/Final Project/src/userlogin.txt"));
for (int i = 0; i < numCustomers; i++) {
System.out.println("enter customer data (fname, lname, address, city, state, zip)");
for (int j = 0; j < customerData[i].length; j++) {
customerData[i][j] = scan.nextLine();
}
writer.write(customerData[i][0] + ", " + customerData[i][1] + ", " + customerData[i][2] + ", "
+ customerData[i][3] + ", " + customerData[i][4] + ", " + customerData[i][5] + "\n");
loginWriter.write(customerData[i][0].charAt(0) + customerData[i][1] + ", " + rand.nextInt(10001) + "ASU"
+ ", Customer" + "\n");
}
writer.flush();
writer.close();
loginWriter.flush();
loginWriter.close();
}
Output
how many customers
1
enter customer data (fname, lname, address, city, state, zip)
fname
lname
123 address dr
city
state
zip
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)
at java.base/java.lang.String.charAt(String.java:709)
at Employee.addCustomer(Employee.java:156)
at Employee.displayEmployeeMenu(Employee.java:196)
at BasicMethods.promptUser(BasicMethods.java:48)
at Shop.main(Shop.java:8)
I want it so that customerData[i][0] = fname, customerData[i][1] = lname, etc etc. I've tried playing around with .nextLine and the array sizes, but I believe the problem stems from the space needed in address.
So here you create the customer data:
for (int j = 0; j < customerData[i].length; j++) {
customerData[i][j] = scan.nextLine();
}
And here is the writer code using charAt:
loginWriter.write(customerData[i][0].charAt(0) + customerData[i][1] + ", " + rand.nextInt(10001) + "ASU" + ", Customer" + "\n");
So it looks like customerData[i][0] is an empty String since it's the only use of charAt which throws the index exception.
I suggest you either output your individual data items or better yet, step through your code with a debugger.
Since you don't show the surrounding code (how is scan created; maybe it's reused but accidentally closed in the meantime?) we can only make reasonable guesses.

Problems with Output in Java

I have no idea why my output is not coming out correct. For example, if the input is "Running is fun" then the output should read "Is running fun". However, the output I am getting is "Iunning".
import java.util.Scanner;
public class Problem1 {
public static void main( String [] args ) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter text: ");
String sentence = sc.nextLine();
int space = sentence.indexOf(" ");
String firstWord = sentence.substring(0, space + 1);
String removedWord = sentence.replaceFirst(firstWord, "");
String newSentence = removedWord.substring(0,1).toUpperCase() +
firstWord.substring(1).toLowerCase();
System.out.println("");
System.out.println( newSentence );
}
}
removedWord.substring(0,1).toUpperCase() this line adds the capitalized first letter of the second word in the sentence. (I)
firstWord.substring(1).toLowerCase(); adds every letter of the first word to the end of the sentence. (unning)
Thus this creates the output of Iunning. You need to add the rest of removedWord to the String, as well as a space, and the first letter of firstWord, as a lower case letter at the space in removedWord. You can do this more by using indexOf to find the space, and then using substring() to add on firstWord.toLowerCase() right after the index of the space:
removedWord = removedWord.substring(0, removedWord.indexOf(" ")) + " " +
firstWord.toLowerCase() +
removedWord.substring(removedWord.indexOf(" ") + 1,
removedWord.length());
String newSentence = removedWord.substring(0,1).toUpperCase() +
removedWord.substring(1, removedWord.length());
Output:
Is running fun
Your problem is that
firstWord.substring(1).toLowerCase()
Is not working as you expect it to work.
Given firstWord is “Running“ as in your example, then
”Running“.substring(1)
Returns ”unning“
”unning“.toLowerCase()
Obviously returns ”unning“
The problem is at String newSentence. You not make the right combination of firstWord and removedWord.
This is how should be for your case:
String newSentence = removedWord.substring(0, 1).toUpperCase() // I
+ removedWord.substring(1,2) + " " // s
+ firstWord.toLowerCase().trim() + " " // running
+ removedWord.substring(2).trim(); // fun
EDIT(add new solution. credits #andy):
String[] words = sentence.split(" ");
words[1] = words[1].substring(0, 1).toUpperCase() + words[1].substring(1);
String newSentence = words[1] + " "
+ words[0].toLowerCase() + " "
+ words[2].toLowerCase();
This works properly:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter text: ");
String sentence = sc.nextLine();
int space1 = sentence.indexOf(' ');
int space2 = sentence.indexOf(' ', space1 + 1);
if (space1 != -1 && space2 != -1) {
String firstWord = sentence.substring(0, space1 + 1);
String secondWord = sentence.substring(space1 + 1, space2 + 1);
StringBuilder newSentence = new StringBuilder(sentence);
newSentence.replace(0, secondWord.length(), secondWord);
newSentence.replace(secondWord.length(), secondWord.length()+ firstWord.length(), firstWord);
newSentence.setCharAt(0, Character.toUpperCase(newSentence.charAt(0)));
newSentence.setCharAt(secondWord.length(), Character.toLowerCase(newSentence.charAt(secondWord.length())));
System.out.println(newSentence);
}
}

Elements in Array List to appear on a new line

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.

NumberFormatException when attempting to Tokenize a String

I'm trying to tokenize a String and save it to a binary file, but when I run the program, I get a NumberFormatException. Here is my stack trace:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: " 1"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:481)
at java.lang.Integer.parseInt(Integer.java:527)
at Project6.saveBSAFile(Project6.java:187)
Here is my code, which is trying to tokenize a String and save it to a binary file:
public void saveBSAFile() throws FileNotFoundException, IOException
{
jfc.setDialogTitle("Specify a file to save");
int userSelection = jfc.showSaveDialog(this);
if (userSelection == jfc.APPROVE_OPTION)
{
File filename = jfc.getSelectedFile();
JOptionPane.showMessageDialog(null, "File to save " + filename,
"Save Review", JOptionPane.INFORMATION_MESSAGE);
FileOutputStream FOStream1 = new FileOutputStream(filename, true);
DataOutputStream DOStream1 = new DataOutputStream(FOStream1);
}
else if (userSelection == jfc.CANCEL_OPTION)
{
return;
}
int index = 0;
while (tools.getNumberOfItems() <= 10 && processRec.getToolRecords(index) != null)
{
StringTokenizer tokens = new StringTokenizer(processRec.getToolRecords(index), "|:");
toolStrTok = tokens.nextToken();
toolNameTok = tokens.nextToken();
idStrTok = tokens.nextToken();
idTok = tokens.nextToken();
qualStrTok = tokens.nextToken();
qualTok = tokens.nextToken();
stockStrTok = tokens.nextToken();
stockTok = tokens.nextToken();
priceStrTok = tokens.nextToken();
priceTok = tokens.nextToken();
idTok.trim();
qualTok.trim();
stockTok.trim();
priceTok.trim();
id = Integer.parseInt(idTok);
quality = Integer.parseInt(qualTok);
numInStock = Integer.parseInt(stockTok);
price = Double.parseDouble(priceTok);
FileOutputStream FOStream2 = new FileOutputStream(filename, true);
DataOutputStream DOStream2 = new DataOutputStream(FOStream2);
DOStream2.writeUTF(toolStrTok);
DOStream2.writeUTF(" " + toolNameTok);
DOStream2.writeUTF(" " + idStrTok + " ");
DOStream2.writeInt(id);
DOStream2.writeUTF(" " + qualStrTok + " ");
DOStream2.writeInt(quality);
DOStream2.writeUTF(" " + stockStrTok + " ");
DOStream2.writeInt(numInStock);
DOStream2.writeUTF(" " + priceStrTok + " ");
DOStream2.writeDouble(price);
DOStream2.close();
index++;
}//end loop
}//end saveBSAFile
And here is the String i'm attempting to tokenize, which is being pulled from a method in another class file(which is being referenced by a call to processRec):
public String getRecord(int index)
{
return "Tool Name: " + toolArray[index].getName()
+ "| Tool ID: " + toolArray[index].getToolID()
+ "| Tool Quality: " + toolArray[index].getQuality()
+ "| Number in Stock: " + toolArray[index].getNumberInStock()
+ "| Tool Price: " + toolArray[index].getPrice();
}//end getRecord
I've tried a few different things, such as trimming the Strings using trim() i'm attempting to tokenize, but that didnt seem to work :( I also tried reworking the code a bit but that hasn't netted me much luck, either. I'm very much a novice when it comes to exceptions and stack traces, so I was hoping someone may be able to point out any obvious(or not so obvious) mistakes I may be making. Thanks so much in advance :)
The trim() method doesn't change the original String; it's immutable.
Returns a string whose value is this string, with any leading and trailing whitespace removed.
(emphasis mine)
The trim method returns the trimmed String, but you discard the returned String. idTok is still " 1", with spaces.
Change
idTok.trim();
to
idTok = idTok.trim();
and likewise with the other tokens. Then parseInt will see the trimmed string (e.g. "1") and parse the integers correctly.

Program Runs but No Output?

Sorry, I'm a bit clueless when it comes to this and I'm having a bit of trouble with this specific portion of my program.
The goal is, when someone inputs a three word string, to rearrange it in such a way that "Emma Charlotte Leonard" becomes " Leonard, Emma, C".
This is what I have so far for that specific method:
public String lastFirst (String str)
{
Scanner keyboard = new Scanner(System.in);
System.out.println ("Enter your name");
String lastFirst = keyboard.nextLine();
String middleAndLast = lastFirst.substring(lastFirst.indexOf(" ")+ 1);
String last = middleAndLast.substring(middleAndLast.indexOf(" ") + 1);
String first = lastFirst.substring(0, lastFirst.indexOf(" "));
String middle = middleAndLast.substring(0, middleAndLast.indexOf(" "));
char middleInitial = middle.charAt(0);
return("\"" + last + ", " + first + ", " + middleInitial + "\"");
}
Any help would be appreciated, sorry if I haven't put enough information.
I believe this is what you are trying to achieve:
public class RearrangeName{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println ("Enter your name");
String inputStr= keyboard.nextLine();
System.out.println(lastFirst(inputStr));
}
public static String lastFirst (String str){
String middleAndLast = str.substring(str.indexOf(" ")+ 1);
String last = middleAndLast.substring(middleAndLast.indexOf(" ") + 1);
String first = str.substring(0, str.indexOf(" "));
String middle = middleAndLast.substring(0, middleAndLast.indexOf(" "));
char middleInitial = middle.charAt(0);
return("\"" + last + ", " + first + ", " + middleInitial + "\"");
}
}
See the Demo here
Do you want output to be "Leonard, Charlotte, L" or "Leonard, Emma, C".
Current output of your program is the second option. And if you desired first output then you should declare middleInitial as String middleInitial =last.charAt(0);.
Try following example it is return the "Emma Charlotte Leonard" as " Leonard, Charlotte, L"
public class Example{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Example exp = new Example();
System.out.print("Enter your number : ");
System.out.println(exp.getName(input.nextLine()));
}
private String getName(String name){
String arr[] = name.split(" ");
return arr[2]+ ", "+arr[1]+", "+arr[2].substring(0, 1);
}
}

Categories