function not entering a loop - java

Hi i'm trying to program a tool that allow us to manage a small shop , i've managed to get evey functionality to work`but this last function is getting me crazy
public void ajoutCommandesCli() {
Commandes com = new Commandes();
Magasin m = this;
Client c = new Client();
Scanner sc = new Scanner(System.in);
System.out.println("quel est votre numero client ?");
int numcli = sc.nextInt();
System.out.println("testosterone");
System.out.println(this.listecli.capacity());
for (int i = 0; i <= this.listecli.size(); i++) {
if (numcli == listecli.get(i).num) {
int index = this.listecli.indexOf(i);
c = this.listecli.get(index);
System.out.println("test aaaa");
com.saisirCommandes(this, c);
} else {
System.out.println("réessayer?");
System.out.println("1-oui");
System.out.println("2-non");
int choix = sc.nextInt();
if (choix == 1) {
this.ajoutCommandesCli();
} else {
System.out.println("testitestos");
MenuMagasin.afficherMenu(this);
}
}
}
}
this function doesnt even enter the first for loop and i dont know why .
Magasin has a vector of client ,but java tells me my vector capacity is 10 but the teacher told us vector just has no definite capacity , i havent inputed any lenghth for the vector.this is getting me crazy please help me guys .I'm sorry if my question sounds stupid but i need help.

Your question lacks information, you should make a minimal-reproducible-example as shown here.
I'd recommend running your program in debug mode, and view the value of this expression :
numcli==listecli.get(i).num
does your program ever run the if statement's code ?
is you list listecli empty ?
what's the error message you getting ?

Related

Java Scanner.next is blocked seemingly without reason

I'm trying to get user inputs in a while:
package com.projet.geometrie;
import java.util.List;
import java.util.ArrayList;
import java.util.Scanner;
class TestGeo{
public static void main(String[] args) {
Scanner input_reader = new Scanner(System.in);
boolean retour = false;
boolean first = true;
List<Vertex> listePoints = new ArrayList<>();
while (!retour) {
System.out.println("Entrez une coordonnée au format : x,y");
String coord = input_reader.next();
String[] coordSplit = coord.split(",");
int x = Integer.parseInt(coordSplit[0]);
int y = Integer.parseInt(coordSplit[1]);
if (!first) {
if (x != listePoints.get(0).getX() && y != listePoints.get(0).getY()) {
Vertex nouveauPoint = new Vertex(x, y);
listePoints.add(nouveauPoint);
if (listePoints.size() > 1) {
}
} else {
retour = true;
}
} else {
first = false;
Vertex nouveauPoint = new Vertex(x, y);
listePoints.add(nouveauPoint);
}
}
input_reader.close();
Section test = new Section(listePoints);
System.out.println("Nombre de sommets : " + listePoints.size());
System.out.println("Aire du polygone : " + test.getAire());
System.out.println("Centroide X : " + test.getCoordCentroide().get(0) + " Y : " + test.getCoordCentroide().get(1));
}
}
But at some point, after I enter the input, my code just gets stuck. I write the input, press enter and it just skips a line, as it is no longer reading the input. It mostly happens after 3 iterations, but sometimes it's 2, other times it's 4. In debug mode it just get stuck at trying to read.
Anyone has an idea of what I did wrong?
I'm using jdk 10.0.2, let me know if any other information could be useful, I'm new to java.
*EDIT : Posted the full code with which I'm experiencing the bug. The class Vertex is just a grouping of 2 int and was tested, I know it works. This class is supposed to take coordinates input from the user and add the point to a list of point. If the last point entered is the same as the first one, it stops and show some information about the created polygon.
Finally got it to work by using .nextInt() and asking the user to enter the x and the y separately (as 2 different inputs). I think it had something to do with the fact that strings were involved in the process, though I'm not sure why it would be problematic. If anyone has an explanation I would be glad to know more even if it's working now.

Someone have a look at my source code for a number guessing game that seems to keep failing [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Hello please may someone run my code and assist me in debugging it. I'm having a lot of troubles trying to figure it out and i have not a lot of guidance when it comes to coding.
the problem with my code right now is that it runs certain parts twice. please annotate the issue and any
reccomendations to fix it. Thanks in advance
a brief of what i'm trying to do:
number guessing game
the idea is that the computer will generate a random number and will ask the user if they know the number
if the user gets the answer correct they will get a congrats message and then the game will end but if the user
enters a wrong number they get a try again message and then they will try again
import javax.swing.*;
import java.lang.*;
public class Main {
public static void main(String[] args) {
/*
number guessing game
the idea is that the computer will generate a random number and will ask the user if they know the number
if the user gets the answer correct they will get a congrats message and then the game will end but if the user
enters a wrong number they get a try again message and then they will try again
the problem with my code right now is that it runs certain parts twice. please annotate the issue and any
recomendations to fix it. Thanks in advance
*/
enterScreen();
if (enterScreen() == 0){
number();
userIn();
answer();
}
}
public static int enterScreen (){
String[] options = {"Ofcourse", "Not today"};
int front = JOptionPane.showOptionDialog(null,
"I'm thinking of a number between 0 and 100, can you guess what is is?",
"Welcome",
JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE,
null, options, "Yes" );
if(front == 0){
JOptionPane.showMessageDialog(null, "Goodluck then, you might need it. :D");
}
else {
JOptionPane.showMessageDialog(null, "okay i dont mind");
}
return front;
}
private static int number(){
double numD;
numD = (Math.random() * Math.random()) * 100;
int numI = (int) numD;
System.out.println(numD);
return numI;
}
private static int userIn(){
String userStr = JOptionPane.showInputDialog("What number do you think im thinking of?");
int user = Integer.parseInt(userStr);
return 0;
}
private static void answer(){
// here is the problem
if(userIn() == number()){
JOptionPane.showMessageDialog(null, "Well done! You must be a genius.");
}
else {
JOptionPane.showMessageDialog(null, "Shame, TRY AGAIN!");
userIn();
}
}
}
Your problem is this part:
enterScreen();
if (enterScreen() == 0) {
number();
userIn();
answer();
}
You can leave out the first enterScreen(). Because you call it again in the if statement. If you look at the return type of the method: public static int, it returns and int. This makes it so that the outcome of the method is directly available in the if statement. The fist enterScreen is basicly useless, because you dont use the result.
You could do this:
int num = enterscreen();
if (num == 0) {
number();
userIn();
answer();
}
Which is basicly the same as:
if (enterScreen() == 0) {
number();
userIn();
answer();
}
You call enterScreen() twice. Just call it once, and compare the value returned only once.
Also, StackOverflow typically is not for "Here's my code, fix it" kind of not questions.
https://stackoverflow.com/help/how-to-ask
You call enterScreen() and userIn() functions twice or more. Please Computer Science and coding. Hint: Computer's execute intructions from top to bottom.

Why is my code giving me an ArrayIndexOutOfBoundsException? [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
Hello I am a beginner programmer and I have tried various different methods to get my code to work, but all of them have failed. I would be very thankful if someone could show me what it wrong with my code and how to fix the arrayindexoutofboundsexception error. Thank you so much in advance!!!
Here is my code:
public static void main(String[] args) {
// TODO code application logic here
// getting the number of rows and columns for the maze from the user
Scanner scanner = new Scanner(System.in);
System.out.print("How many rows are in the maze? ");
int rows = scanner.nextInt();
int[][] maze = new int[rows][];
System.out.print("How many columns are in the maze? ");
int columns = scanner.nextInt();
maze[rows] = new int[columns];
// getting the data/danger levels for each row from the user
for (int c = -1; c < maze[rows].length; c++) {
System.out.print("Enter the danger in row " + (c + 1) + ", " + "separated by spaces: ");
maze[rows][c] = scanner.nextInt();
}
System.out.println(maze[rows][columns] + "\n");
}
}
intial value for c variable is -1.
so when you do this
maze[rows][c] = scanner.nextInt();
you get the error since -1 index doesn't exists.
Change it to
maze[rows][c+1] = scanner.nextInt();
You start loop-counter c at value -1, but array starts with index [0]. The loop increment (c++ as last argument in for-loop) is executed at the end of each loop iteration, not at its beginning.
The problem is this line:
maze[rows] = new int[columns];
Arrays in Java are 0-indexed, so if I create a maze with 3 rows, the last index is 2. What you want is this:
maze[rows - 1] = new int[columns]
A quick note that you can debug simple programs very quickly in an IDE like IntelliJ Idea by setting breakpoints and seeing the execution of your program step-by-step:

Having trouble with java loops

I am doing a project for school where i need to make a game about guessing the number from the computer. The problem I have is that my code won't print out the sentence "Het is fout" Which means that they are wrong. It also wont print the sentence that they tried to many times even tho it stops when they are over the limit. My teacher won't help me so I am desperate for some help. This is the code I wrote:
while(leesinvoer() != toeval)
{
aantalkeer = aantalkeer + 1;
if(leesinvoer() == toeval)
{
System.out.println("Het is goed het goede nummer was:"+ toeval);
}
else
{
System.out.println("Het is fout");
}
if(aantalkeer > pogingen)
{
System.out.println("U heeft te vaak beprobeerd");
}
}
System.out.println(toevalsgetalmaken(grens));
}
public static int toevalsgetalmaken(int grens)
{
Random toeval = new Random();
int toevalsgetal = toeval.nextInt(grens);
return toevalsgetal;
}
public static int leesinvoer()
{
String tekst = JOptionPane.showInputDialog(null,"Doe een gok","GOKJE",3);
int getal = Integer.parseInt(tekst);
return getal;
}
Would appreciate any help
You have to invoke leesinvoer() once for each time you check it in your if() statement.
But your code is invoking leesinvoer() twice in each loop: once from while statement, and once from the if statement.
So, instead of while(leesinvoer() != toeval) do while(true), but better yet, (since this should give you a compiler warning saying "condition is always true",) do for(;;) which essentially loops forever.
Then, after each System.out() statement, (which essentially signifies a decision, which should end the loop,) do break; to exit the loop.
Goedenavond! C-:=

How do I use JOptionPane in a while loop?

The code segment below is a part of a bigger program, but I think this is where I'm having the issue. So, I am trying to use a while loop to ask for input over and over until the program is done, and the dialog box is not coming up and I don't know why. I would really appreciate it if someone could take a look and tell me what I'm doing wrong. If you want to see the entire program just tell me.
Code
boolean done = true;
while(!done)
{
Grid grid = new Grid();
boolean userDone = true;
int compRandom = (int) (Math.random() * 9) + 1;
String input1 = JOptionPane.showInputDialog("Please input a number 1-9 for where you would like to place your piece: ");
Integer input = Integer.parseInt(input1);
boolean done = true;
must be
boolean done = false;

Categories