Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException - java

I'm just a newbie in java, so please help me, i think the problem is in the switch stament
String customer[]=new String[2];
int old[]=new int[2];
for(i=0; i<customer.length;i++){
System.out.println("\nEnter information of customer#" +(i+1));
System.out.print("Enter customer name"+(i+1)+":");
customer[i]=data.readLine();
System.out.print("Enter old reading of costumer#"+(i+1)+":");
old[i]=Integer.parseInt(data.readLine());
}
System.out.println("\n\nSample Menu");
System.out.println("1. Display Transaction\n2.Pay Water Bill");
System.out.print("Enter your choice:");
choice=Integer.parseInt(data.readLine());
In this part the System.out.println(customer[i]+"."); is not working
switch(choice){
case 1:
System.out.println("This is to display the transaction!");
System.out.println(customer[i]+"."); \
break;
case 2:
System.out.println("This is to pay the water bill!");
break;
default: System.out.println("Exit`!");
break;
}
}
}

The problem is that when you exit your loop, the value of i is 2, not 1.
The increment expression is invoked after each iteration through the
loop.
So when accessing System.out.println(customer[i]+"."); you go out of bounds since the last element of your array is at index 1 (arrays are 0 base indexed).
If you take this snippet of code:
int i;
for(i = 0; i < 2; i++){}
System.out.print(i);
It outputs 2.

At that point variable i has incremented to 2 So you would have to reset it first. Ofcourse you get IOOB exception because you are referencing missing place in array (only places 0 and 1 exist)

This is how your code works :
for(i=0; i<customer.length;i++){
............................
............................
}
Hence, i takes values :
i is (i < customer.length)
0 YES
1 YES
2 NO <LOOP BREAKS>
Now, when it comes to the switch statement, the following happens:
switch(2) { //ALWAYS
..........
..........
}
Hence, the switch(1) case, or the System.out.println(customer[i]+".") is never reached. It's quite a common mistake.
What you need is a do while loop for your menu.
So :
// Initialize Values
for(i=0; i<customer.length;i++){
............................
............................
}
// Loop through the Options
do {
// ASK FOR USER INPUT AS YOU ARE DOING
switch(choice) { //ALWAYS
..........
..........
}
} while(choice != 1 || choice != 2);
The do while ensures that no matter what, your command will be executed for the menu, when it is given. So for example, in the do while, your default exit statement will always be printed.

Related

How to provide a list of products in online store via switch? How to use the exit to the main menu? (or another way)

Java. There is an online store, classes of products, constructors, etc. (I have all I need) There is also an array of products.
The switch statement provides a choice, the user need to select the number of product on the console. I want the user to be able to select several products (not only one product), so I added scanners (I hope there is nothing bad in scanner) I have a method which directs user to the main menu, is called in this code as firstMethod ();
The problem with the transition to the main menu through the switch statement. When I press 1, 3 and so on - the products are displayed, but when I press 6 then firstMethod (the method that calls the main menu in this online store) really work, but not "in time". When I press 1, the 1 case is executed, the program is waiting for my input of the next number. I press 6 (to go to main menu) and for some reason the program displays case 2. Then I press 6 and console displays case 3, and so on. Two more times and the console displays the main menu, this is really what I want to be shown right that moment when I press number 6.
Tell me please - what is wrong with that? How to go to the main menu (call the method) with this operator, or is it better to use another one? Write it please.
So I want firstMethod to work when user press 6 number. Can I do this via switch or I need another operator? Please help I will be really gratefull.
public static void switch1() {
Product[] products = {
new Fridge(),
new Fridge(),
new Fridge(),
...
...
...
};
Scanner scan = new Scanner(System.in);
System.out.println("1 - " + products[0]);
System.out.println("2 - " + products[1]);
System.out.println("3 - " + products[2]);
System.out.println("4 - " + products[3]);
System.out.println("5 - " + products[4]);
System.out.println("6 - Go to main menu");
System.out.println("Which one do u want to buy?");
int i = Scanner.nextInt();
switch (i) {
case 1:
System.out.println(products[0]);
Scanner.nextInt();
case 2:
System.out.println(products[1]);
Scanner.nextInt();
case 3:
System.out.println(products[2]);
Scanner.nextInt();
case 4:
System.out.println(products[3]);
Scanner.nextInt();
case 5:
System.out.println(products[4]);
Scanner.nextInt();
case 6:
firstMethod();
}
It seems like the only visible problem is that there are no break; statements at the end of each of your case blocks.
For example:
switch (i) {
case 1:
System.out.println(products[0]);
Scanner.nextInt();
break;
...
Also, just calling Scanner.nextInt(); won’t do anything unless you use the value returned by the call.
You also said you wanted the user to be able to select multiple products, so in order to do that, you could put the switch in a loop, such as a while loop, and have it loop until a condition is met to stop it.
Edit: The following code shows a small example of what your code structure could be:
boolean loop = true;
while (loop) {
int i = scan.nextInt();
switch (i) {
case 1:
System.out.println(product[0]);
break;
//... cases 2-5 are similar to case 1
case 6:
firstMethod();
loop = false;
break;
}
}
This can be done in a much more efficient manner without a switch at all.
Scanner scan = new Scanner(System.in);
for (int i = 0; i < products.length; i++) {
System.out.println((i + 1) + " - " + products[i]);
}
System.out.println((products.length + 1) + " - Go to main menu");
System.out.println("Which one do u want to buy?");
while (true) {
int selection = Scanner.nextInt();
if (selection > 0 && selection <= products.length) {
System.out.println(products[selection - 1]);
} else {
break;
}
}
firstMethod();

Java Code Not reachable

Please have a look on my code its showing code not reachable.
private static void createUser() {
HashMap<String, String> membership = new HashMap<String, String>();
System.out.println("Enter the Name of the User: ");
String nameOfUser=sc.next();
System.out.println("Enter the Membership tier which you prefer");
System.out.println("1. Member - 5 % discount \n 2. Bronze - 10 % discount \n 3. Silver - 15% discount \n "
+ "4. Gold - 20 % discount \n 5. Platinum - 25 % discount");
String typeOfMembership = null;
while(true){
int memberChoice=sc.nextInt();
switch(memberChoice){
case 1:
typeOfMembership="Member";
membership.put(nameOfUser,typeOfMembership);
break;
case 2:
typeOfMembership="Bronze";
membership.put(nameOfUser,typeOfMembership);
break;
default:
System.out.println("Please select one of the available Member Type.");
}
}
for (Map.Entry<String, String> entry : membership.entrySet()) {
System.out.println("Member Created Successfully with name "+entry.getKey()+" and "+entry.getValue()+" tier.");
}
}
Its showing code unreachable from this line onwards
for (Map.Entry<String, String> entry : membership.entrySet()) {
You have an infinite loop while(true) so you will never reach the for loop.
Note: the breaks you have will only break the switch.
Suggestion:
One way to fix it is to exchange the hard coded true, to something like isMemberSelected that you set to false in the default case. You could probably also switch to a do-while-loop.
You could even break it out to a separate method memberships = createMembers();
I think you have an infinite loop at while(true) this will always evaluate to true hence the execution of the script will stay in the loop. Try a different loop guard which shouldn't always evaluate to true.

Incrementing a variable within a loop in Java

I'm working on a dice game in which I want to allow the user to keep some of their rolls, and then reroll others. I store their first 5 rolls in an array called dieArray and then print the contents of this array, each die being numbered, and then ask the user which die he/she wants to keep, looping one at a time.
The idea was to then add the value of the die that the user chose to keep to a new array that I called keepArray.
My current code for this loop is as follows
while(bool != false){
System.out.print("Would you like to keep a die? y/n: ");
char ch = scanner.next().charAt(0);
if(ch == 'n') {
System.out.println("Exiting----------------------------------------------");
bool = false;
}
else{
System.out.print("Which die number would you like to keep?: ");
int keep = scanner.nextInt();
int i = 0;
keepArray[i] = die.dieArray[keep];
i++;
System.out.println("i value is " + i);
}
}
The issue I am having is that my i within the else statement is not being incremented. I feel that I am not understanding the fundamentals of while loops in Java, because as I see it each time the else loop is accessed, which should be every time the user answers "y" when asked if he/she wants to keep a die, my i should be incremented by 1. Clearly it is not.
Your i variable is being recreated on every round. You need to declare int i = 0; above the loop.

I'm trying to exit while loop (while also using a for loop) in java

I am working on a project in which I must calculate mortgage. It's supposed to have a loan selection menu in which 1) uses default values to calculate the mortgage. 2) will allow the user to enter in custom values. 3) allows the user to exit the program and have the calculated values displayed. I have a for loop to allow the program to run up to 10 times (it can be less though). I'm currently using a do-while loop to exit the program when 3 is the selection. However it's not exiting. I"m not sure what is wrong and am hoping for an explanation and some tweaks I could implement to ensure it does what it's supposed to.
do
{
int selection = 0;
for(int i=0; i<loanArray.length; i++)
{
System.out.println("Please choose from the following choices below: ");
System.out.println("\t1) Promotional Loan (preset loan amount, rate, term)");
System.out.println("\t2) Unique Loan (enter in loan values)");
System.out.println("\t3) Quit (Exit the program)");
System.out.println("Please enter your selection(1-3): ");
selection = s.nextInt();
if(selection ==1)
{
loanArray[i] = new Mortgage();
System.out.println(loanArray[i].toString());
}
else if (selection ==2)
{
loanArray[i].storeLoanAmount();
loanArray[i].storeInterestRate();
loanArray[i].storeTerm();
System.out.println(loanArray[i].toString());
}
else if(selection == 3)
{
programSelection = false;
programRunning = false;
}
}//end of for array loop
}while (programSelection == true); //end of selection while loop
System.out.println("Exit Test"); //print statement to test if selection screen exited
I haven't actually tested this, but I think the problem is exiting the for loop. The quickest way to test that is just to use a break statement with a label.
outerLoop:
do
// ...
else if(selection == 3)
{
break outerLoop;
}
}//end of for array loop
}while (programSelection == true); //end of selection while loop
Break statements with labels are discussed in the Java tutorial.
Add a break; after the programRunning = false;
you have got the correct the logic the reason is the for loop.
while (programSelection == true)
will only be executed after the for loop. Need to be cautious as well because if the loanArray length is 1 you might think the code works well,actually it doesnt.

Java: Reading from a text file && Check whether the graph is complete or not

I have a school assignment that I finished most of, but I can't figure out how to read from a text file, and I'm having a certain problem regarding the code, The task I was given is:
"Write a program to read an input file named “input.txt”. The file
consists of several graphs. Each graph starts with a line containing
the number of vertices n, where 1 < n < 200. Each vertex is labeled by
a number from 0 to n-1. The second line contains the number of edges
l. After this, l lines follow each containing two vertex numbers
representing an edge. An input with n = 0 marks the end of the input
and is not to be processed.
You have to choose an appropriate data structure to represent the
graph. Indicate whether its Complete/has a self loop/ has an isolated
vertex "
Sample Input:
4
5
0 1
2 0
0 3
1 2
2 3
3
3
0 1
1 2
2 0
0
Sample output:
Not Complete/No Self-Loop/No Isolated Vertex
Complete/No Self-Loop/No Isolated Vertex
I used adjacency matrix, I wrote code that reads the edges, decided whether it has a self loop and whether there's an isolated vertex.
1- I wrote a code for finding whether it's complete or not, but it doesn't behave the way I want it, it always shows that It's not complete.
2- I am not familiar with the way to read inputs from a text file, so please I need help.
The part where I have to make it read any amount of matrices, is kinda easy (but leaving a hint for it is always welcomed hehe), but I just wanna make sure I know how to do the two steps above before I do it, I'd really appreciate leaving comments so I could learn whatever step you help me with, anyway, this is the program:
package phase1project;
import java.util.Scanner;
public class Phase1Project {
public static void main(String[] args) {
int max = 2000; //declare the max element for the array
int[][] adj= new int[max][max]; //declare the array
int n; //nodes
int l; // to determine the max number of edges
int loopChecker = 0;//To check whether there's a loop or not
int isolatedCounter = 0;
int completeCounter = 0;
int subCounter = 0;
int origin; //to determine where the edge starts
int destination; //to detemine where the edge stops
int i,j; //for the loop
Scanner input = new Scanner(System.in); //to scan inputs
System.out.println("Enter the number of vertices: ");
n=input.nextInt();
while(n<1 || n>200){ //nodes/vertices should be between 1 and 200
System.out.println("\nWrong input! Insert a numbe between 1 and 200\n");
n=input.nextInt();
}
System.out.println("Enter the number of edges: ");
l=input.nextInt();
System.out.println("Enter the begining of the edge then press enter then enter the end side of the edge to input it correctly.\n");
for(i=0;i<=(l-1);i++){ //a loop that populates the adjacency matrix
System.out.println("Enter edge "+i+": >> (0 0) to quit: ");
origin = input.nextInt();
destination = input.nextInt();
adj[origin][destination]=1;
}
System.out.println("\n\n\nThis is how your graph looks like:\n");
for(i=0;i<=(n-1);i++){
for(j=0;j<=(n-1);j++)
System.out.printf("%4d",adj[i][j]);
System.out.printf("\n");
}
//////////////////////////////////////////////////////////////
//Loop Checker starts from here
for(i=0;i<=(n-1);i++){
if(adj[i][i]==1){//If there's a 1 in the same place
loopChecker=1;
break;
}
}
if(loopChecker==1){
System.out.println("Self Loop");
}
else{
System.out.println("No Self Loop");
}
//Loop Checker ends here
///////////////////////////////////////////////////////////////
//checks whether the graph is complete
for(i=0;i<=(n-1);i++){
subCounter=0;//reset
for(j=0;j<=(n-1);j++){
if(adj[i][j]==1){
subCounter+=1;//buffer variable
}
if(subCounter==(n-1)){
completeCounter+=1;//this counter incriments if the whole line has 1s that equal n-1
}
}
}
if(completeCounter == n){
System.out.println("Complete");
}
else
System.out.println("Not Complete");
//end of complete or not check
/////////////////////////////////////////////////////////////////////
subCounter =0;//reset
//checks whether the graph has an isolated vertex or not
for(i=0;i<=(n-1);i++){
for(j=0;j<=(n-1);j++){
if(adj[i][j]==0){
subCounter+=1;//buffer variable
}
if(subCounter==n){
isolatedCounter=1;
break;
}
}
subCounter=0;//reset
}
if(isolatedCounter==1){
System.out.println("There's an isolated vertex");
}
else
System.out.println("There's no isolated vertex");
//end of isolated check
///////////////////////////////////////////////////////////////////
}
}
I hope I'm not breaking any rule by posting this, if I did please tell me.
Thanks in advance ;)

Categories

Resources