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.
Related
I'm trying to make a code that takes a users input and prints their schedule, but I'm running into a problem with my do-while loop.
My program will not rerun. I'm getting an error that says:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2 at com.company.Main.main(Main.java:25)
Here is my code:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String rerun;
do {
System.out.println("What is your name?");
String name = input.nextLine();
System.out.println("How many courses do you have?");
int numCourse = input.nextInt();
input.nextLine();
String[][] timetable = new String[numCourse][2];
for (int j = 0; j < numCourse; j++) {
System.out.println("What is the name of your course #" + (j + 1) + "?");
String course = input.nextLine();
timetable[j][0] = course;
System.out.println("What is your teachers name for " + course + "?");
String teacher = input.nextLine();
timetable[j][1] = teacher;
}
System.out.println("Hello " + name + ", here is your timetable:");
for (int i = 0; i <= numCourse; i++) {
System.out.format("\n%-30s%-30s", "Course #" + (i+1) + ": " + timetable[i][0],"Teacher: " + timetable[i][1]);
}
System.out.println("Would anyone else like to print their schedule? (yes/no)");
rerun = input.next();
}while(rerun.equalsIgnoreCase("yes"));
System.out.println("Goodbye!");
}
}
Problem is in second for loop where you display your from array. put next() inplace of nextLine() because sometimes it skip the position.
Change
for (int i = 0; i <= numCourse; i++) {
System.out.format("\n%-30s%-30s", "Course #" + (i+1) + ": " + timetable[i][0],"Teacher: " + timetable[i][1]);
}
To
for (int i = 0; i < numCourse; i++) {
System.out.format("\n%-30s%-30s", "Course #" + (i+1) + ": " + timetable[i][0],"Teacher: " + timetable[i][1]);
}
Suppose your numCorse is 2. In your code, loop start from 0 and terminate after 2 so, Your loop working right while i is 0 and 1 but if i is going to 3 you get exception ArrayIndexOutOfBound.
I have an assignment that is very basic but it's all-new ground for me still. The program is supposed to ask the user(s) to enter their name, surname, grade, and subject. If the subject is not IT their input gets set aside. However, if the subject entered is IT their name, surname and grade will be used later on again to display a message that looks as followed:
DisplayedMessage
The information can differ depending on what the user(s) entered. Now the question comes in. I typed the code correctly but at the end where I display the message using JOptionPane it showed an error saying: "Unreachable Statement". (To clarify it happened next to the line of code) It was strange because it was almost identical to the memo of the assignment yet it had the error. It might have been the Netbeans being confused in a way but I redid the assignment at home and it worked as it should seen here:
String name, surname, subject, message = "IT Learners:\n\n";
int grade, counter = 0;
for (int i = 0; i < 3; i++) {
name = JOptionPane.showInputDialog("Enter Your Name Here: ");
surname = JOptionPane.showInputDialog("Enter Your Surname Here: ");
subject = JOptionPane.showInputDialog("Enter Your Subject Here: ");
grade = Integer.parseInt(JOptionPane.showInputDialog("Enter Your "
+ "Grade Here: "));
if (subject.equalsIgnoreCase("IT")) {
message += name + " " + surname + " is in grade "
+ grade + ".\n";
counter++;
}
}
JOptionPane.showMessageDialog(null, message + "There is a total of "
+ counter + " IT Learners.");
The next section of code is a copy of the code I wrote on the terminal during the period. I personally can't see the error and I came here to ask is it correct or is there a small error that I just can't seem to find.
Code I did at school:
String name, surname, subject, message = "IT Learners:\n\n";
int grade, counter = 0;
for (int i = 0; i < 3; i++) {
name = JOptionPane.showInputDialog("Enter Your Name Here: ");
surname = JOptionPane.showInputDialog("Enter Your Surname Here: ");
subject = JOptionPane.showInputDialog("Enter Your Subject Here: ");
grade = Integer.parseInt(JOptionPane.showInputDialog
("Enter Your Grade Here: "));
if (subject.equalsIgnoreCase("IT"))
{
message += name + " " + surname + " is in grade "
+ grade + ".\n";
counter++;
}
}
JOptionPane.showMessageDialog(null, message + "There is a total of "
+ counter + " IT Learners.");
It truly looks identical, was it just the Netbeans being confused or is there just a fine detail I am missing?
Entire code:
import javax.swing.JOptionPane;
/**
*
* #author (My Name)
*/
public class ITLearners {
public static void main(String[] args) {
// TODO code application logic here
String name, surname, subject, message = "IT Learners:\n\n";
int grade, counter = 0;
for (int i = 0; i < 3; i++) {
name = JOptionPane.showInputDialog("Enter Your Name Here: ");
surname = JOptionPane.showInputDialog("Enter Your Surname Here: ");
subject = JOptionPane.showInputDialog("Enter Your Subject Here: ");
grade = Integer.parseInt(JOptionPane.showInputDialog("Enter Your "
+ "Grade Here: "));
if (subject.equalsIgnoreCase("IT")) {
message += name + " " + surname + " " + " is in grade "
+ grade + ".\n";
counter++;
}
}
JOptionPane.showMessageDialog(null, message + "There is a total of "
+ counter + " IT Learners.");
}
}
I feel quite silly right now. The problem in the code done at school was that an i in the for loop condition was a 1. Like this:
for ( int i = 0; 1 < 3; i++; )
Lesson learned out of this: make sure you type everything correctly. With the 1 there I created an unintentionally infinite loop without realizing it. Thank you so much for the help, especially #AcidResin!
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);
}
}
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));
I need help, obviously. Our assignment is to retrieve a file and categorize it and display it in another file. Last name first name then grade. I am having trouble with getting a loop going because of the error "java.util.NoSuchElementException" This only happens when I change the currently existing while I loop I have. I also have a problem of displaying the result. The result I display is all in one line, which I can't let happen. We are not allowed to use arraylist, just Bufferedreader, scanner, and what i already have. Here is my code so far:
import java.util.;
import java.util.StringTokenizer;
import java.io.;
import javax.swing.*;
import java.text.DecimalFormat;
/*************************************
Program Name: Grade
Name: Dennis Liang
Due Date: 3/31/11
Program Description: Write a program
which reads from a file a list of
students with their Grade. Also display
last name, first name, then grade.
************************************/
import java.util.*;
import java.util.StringTokenizer;
import java.io.*;
import javax.swing.*;
import java.text.DecimalFormat;
class Grade {
public static void main(String [] args)throws IOException {
//declaring
String line = "";
StringTokenizer st;
String delim = " \t\n\r,-";
String token;
String firstname;
String lastname;
String grade;
String S69andbelow="Students with 69 or below\n";
String S70to79 ="Students with 70 to 79\n";
String S80to89= "Students with 80 to 89\n";
String S90to100= "Students with 90 to 100\n";
int gradeint;
double gradeavg = 0;
int count = 0;
File inputFile = new File("input.txt");
File outputFile = new File("output.txt");
FileInputStream finput = new FileInputStream(inputFile);
FileOutputStream foutput = new FileOutputStream(outputFile);
FileReader reader = new FileReader(inputFile);
BufferedReader in = new BufferedReader(reader);
Scanner std = new Scanner(new File("input.txt"));
Scanner scanner = new Scanner(inputFile);
BufferedWriter out = new BufferedWriter(new FileWriter(outputFile));
Scanner scan = new Scanner(S69andbelow);
//reading linev
line = scanner.nextLine();
st = new StringTokenizer(line, delim);
//avoiding selected characters
try {
while(st.hasMoreTokens()) {
firstname = st.nextToken();
lastname = st.nextToken();
grade = st.nextToken();
//storing tokens into their properties
gradeint = Integer.parseInt(grade);
//converting token to int
gradeavg = gradeavg + gradeint;
//calculating avg
count++;
//recording number of entries
if (gradeint <=69) {
S69andbelow = S69andbelow + lastname + " "
+ firstname + " " + "\t" + grade + "\n";
} // saving data by grades
else if (gradeint >= 70 && gradeint <= 79) {
S70to79 = S70to79 + lastname + " " + firstname
+ " " + "\t" + grade + "\n";
} // saving data by grades
else if (gradeint >= 80 && gradeint <=89) {
S80to89 = S80to89 + lastname + " " + firstname
+ " " + "\t" + grade + "\n";
} // saving data by grades
else {
S90to100 = S90to100 + lastname + " " + firstname
+ " " + "\t" + grade + "\n";
} // saving data by grades
}//end while
System.out.println(S69andbelow + "\n" + S70to79 + "\n"
+ S80to89 + "\n" + S90to100);
//caterorizing the grades
gradeavg = gradeavg / count;
//calculating average
DecimalFormat df = new DecimalFormat("#0.00");
out.write("The average grade is: "
+ df.format(gradeavg));
System.out.println("The average grade is: "
+ df.format(gradeavg));
Writer output = null;
output = new BufferedWriter(new FileWriter(outputFile));
// scanner.nextLine(S69andbelow);
//output.write(S69andbelow + "\n" + S70to79 + "\n"
// + S80to89 + "\n" + S90to100);
// output.close();
}
catch( Exception e ) {
System.out.println(e.toString() );
}
// Close the stream
try {
if(std != null )
std.close( );
}
catch( Exception e ) {
System.out.println(e.toString());
}
}
}
my input file looks like this:
Bill Clinton 85 (enter)
Al Gore 100 (enter)
George Bush 95 (enter)
Hillery Clinton 83(enter)
John McCain 72(enter)
Danna Green 87(enter)
Steve Delaney 76(enter)
John Smith(enter)
Beth Bills 60(enter)
It would help to point things out just in case I don't follow you all the way through.
An easy way of finding a problem in this would be to comment out most of the code and find out each step at a time. So start with being able to read the file. Then print to the screen. Then print the organized data to the screen. Finally print the organized data to the file.
This should be a fairly simple