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!
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.
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.
How do I not store values from the program when it loops back again. For example, if I plan to enter two families, first I will ask for the details of the first family and display their names, and then I want to use the same variables to collect the next family and display their names without having stored information from the previous family.
public static void main(String[] args) {
// TODO code application logic here
String ans;
String res;
double cont;
int cot;
String name;
String order = "";
do {
ans = JOptionPane.showInputDialog(null,"What is the name of the "
+ "family?" );
res = JOptionPane.showInputDialog(null, "How many member in the " + ans +
" family?");
cot = Integer.parseInt(res); // Converts res String to a number
for (int count = 1; count < cot; count ++) {
name = JOptionPane.showInputDialog(null, " Enter first name: " + count);
order += name + " " + ans + "\n";
}
JOptionPane.showMessageDialog(null, "Members of the " + ans
+ " Family" + "\n" + order);
cont = JOptionPane.showConfirmDialog(null, "Do you want to add another "
+ "family", "Membership", JOptionPane.YES_NO_OPTION);
}while (cont == JOptionPane.YES_OPTION);
if (cont == JOptionPane.NO_OPTION){
JOptionPane.showMessageDialog(null," Come Back Again");
}
}
}
Your order variable is a String that you are adding the names to. Just reset it at the beginning of the loop:
...
do {
order = "";
...
I am having an issue with my code not printing out all of what is in a text document. My assignment is to take what is in a .txt file and put in a new .txt file I guess you could say "fancier."
This is the text file I am given.
Thomas Smith 3 2.25 44
Kim Johnson 2 55.60 35
John Doe 33 2.90 21
Karen Java 1 788.99 65
This is the "fancy" output I need(only It needs to output all of them).
The first name is: Thomas
The last name is: Smith
The total number of items bought is: 3
The customer's total is: 6.75
The customer's total rounded (cast) is: 6
The age of the customer is: 44
I think I have just been staring at it so long I'm just over looking it...
Scanner inFile = new Scanner(new FileReader("customer.txt"));
double options;
System.out.println("How would you like to input your data?\n1 Input information from customer.txt\n2 Input information from the keyboard.");
options = console.nextDouble();
if (options == 1){
//Variable to store first name
String firstName;
//Variable to store last name
String lastName;
//Variable to store how many items bought
int itemsBought;
//Variable to store the price per item
double itemPrice;
//Variable to store their age
int age;
while (inFile.hasNext()){
//Gets the first name
firstName = inFile.next();
//Gets the last name
lastName = inFile.next();
//Gets number of items bought
itemsBought = inFile.nextInt();
//Gets the price per item
itemPrice = inFile.nextDouble();
// Gets their age
age = inFile.nextInt();
PrintWriter outFile = new PrintWriter("programOutputFile.txt");
outFile.println("The customers first name is: " + firstName);
outFile.println("The customers last name is: " + lastName);
outFile.println("The customer bought " + (int)itemsBought + " items.");
outFile.println("The customers total is " + itemPrice);
outFile.println("The total cost rounded " + (int)itemPrice);
outFile.println("The customers age is: " + (int)age);
outFile.close();
}
}
else if (options == 2) {
String firstname;
String lastname;
int items = 0;
double price = 0;
int age1 = 0;
int counter; //loop control variable
counter = 0;
int limit; //store the number of items
System.out.print("Enter the number of entries you have "); //Line 1
limit = console.nextInt(); //Line 2
while (counter < limit) {
// It is asking for the user to input their first name
System.out.println("Please tell me what is your first name? ");
firstname = console.next();
// It is asking for the user to input their last name
System.out.println("What is your last name? ");
lastname = console.next();
// It is asking for the number of items they purchased
System.out.println("How many items did your purchase? ");
items = console.nextInt();
// Here it is asking for the total price they paid
System.out.println("What was the cost of each item? ");
price = console.nextDouble();
System.out.println("How old are you? ");
age1 = console.nextInt();
double total = items * price;
counter++;
if (counter != 0){
//Outputs the length of Firstname
System.out.println("The name is " + firstname.length() + " letters in your first name.");
//Outputs the first letter of LastName
System.out.println("The first letter of your last name is: " + lastname.charAt(0));
//Outputs the number of items bought
System.out.println("You bought " + items + " items.");
//Outputs Price
System.out.println("Your total price was " + total);
//Outputs the Price as a int number
System.out.println("Your total price rounded is " + (int)total);
//Outputs the age
System.out.println("They are " + age1 + " years old.");
PrintWriter outFile = new PrintWriter("programOutputFile.txt");
//Outputs the information given above into a .txt file
outFile.println("The customers first name is: " + firstname);
outFile.println("The customers last name is: " + lastname);
outFile.println("The customer bought " + (int)items + " items.");
outFile.println("The customers total is " + total);
outFile.println("The total cost rounded " + (int)total);
outFile.println("The customers age is: " + (int)age1);
outFile.close();
}
else
System.out.println("Invalid. Please try again.");
}
}
inFile.close();
}
As of right now it will print out Karen Java's line instead of Karen, John, Kim, and Thomas's. I have option 2 finished but again I am having the same problem of it only prints out the last input.
Any advise would be greatly appreciated!
You reopen the file in your loop each time you write. This has the effect of overwrite any previous contents of the file (the previous output you just wrote). declare outfile before the while loop and close it after.
I have a problem with the following code
public static void SideBet(int numberDice,int bet,int money) {
System.out.println("You established a " + "\""+ "point" + "\"" + ". " + "Your " + "\""+ "point" + "\"" + " is " + numberDice + ". " + "You have to roll a(n) " + numberDice + " to win your bet, "+ bet +" chips." );
System.out.println();
System.out.println("You can put side bets for 4,5,6,8,9 or 10.");
SideBetChoice = Console.readLine("Would you like to make any side bets ? (Type " + "\""+ "Yes" + "\"" + " or "+ "\""+ "No" + "\"" + ", then hit Enter.)");
int s = 0;
int r = 0;
if (SideBetChoice.equals("Yes")) {
System.out.println("You can put as many side bets as you would like for the numbers 4,5,6,8,9 or 10.");
int SideBetNumber = Console.readInt("How many side bets would you like to make ? (Introduce a number, minimum 1, maximum 6.)");
int[] SBNArray = new int[SideBetNumber];
int[] sbArray = new int[SideBetNumber];
for (s = 0; s <= (SideBetNumber -1) ; s++) {
SBNArray[s] = Console.readInt("On which number would you like to put a side bet ?");
sbArray[s] = Console.readInt("Currently you have " + money + " chips, how much would you like to bet ?");
money = money - sbArray[s];
System.out.println("Thank you for your " +sbArray[s]+ " chip side bet on number " +SBNArray[s]+".");
System.out.println();
}
}
if (SideBetChoice.equals("No")) {
return;
}
sbArray and SBNArray does not get a value and it keeps crashing ...
Can anyone help me out and tell me what is wrong, why the 2 arrays do not get a value, therefor they are null ?
There is no readInt()-method in Console.
Also I'm not sure if you're using console correctly, it should look like this:
Console console = System.console();
console.readLine("Type something");
Just use readLine() and convert it to an int:
Console console = System.console();
String input = console.readLine("Type a number");
try
{
int myNumber = Integer.parseInt(input);
}
catch(NumberFormatException e)
{
System.out.println("This ain't a number!");
}
Also please never use Capital Letters for Variables' Names or method-names, it's very confusing because you could think it would be a Class or a Type.
So please change the name of SBNArray and SideBetNumber, SideBetChoice etc. etc.
Only Constants should be written with only Capital Letters and Classes and Types start with Capital Letters.
EDIT:
Sorry, it seems that you're using BreezyGUI.Console, therefore there is a readInt()-method.
Could you give more information?
I'd like to know if the text of the readInt() is even displayed.