Search code examples
javabluej

Java, Scanner and BlueJ. Something is going stupidly wrong


That's my first post here. I'm try to run a really simple program and I'm sick of it!

I try to run and just after the second entry it stops. I read somewhere that you have to require input before using any output command. I thought that it was my mistake but not really, everything looks fine (although it is not well written, I was just getting started actually). Anyway, here is the code:

import java.util.*;

public class corretorGramatical { 
  public static void main(String [ ] args) {   

     String word;
     String category;
      int i = 0;
      int numberOfWords;
      char code;

       Scanner entry = new Scanner(System.in);
      System.out.println("What is the code?");
      code = entry.nextLine().charAt(0);

    switch(code){
        case 'd':

        System.out.println ("How many words do you want to enter");
         numberOfWords = entry.nextInt();
       // entrada.nextLine();


        for(i = 1; i == numberOfWords; numberOfWords--) {
        System.out.println ("What is the word?");
        word = entry.nextLine();
        System.out.println ("What is the category?");
        category = entry.nextLine(); 
        System.out.println (word + ", " + category);
        } 
        break;

case 'g':
        System.out.println ("I only accept d");
        break;

case 'c':
      System.out.println ("I only accept d");
        break;

case 'f':
        System.out.println ("I only accept d");
        break;
  }        
}   
}

Solution

  • Bad for loop, it doesnt happen.

    for(i = 1; i == numeroDePalavras; numeroDePalavras--) {
        System.out.println ("Qual é a palavra?");
        palavra = entry.nextLine();
        System.out.println ("Qual a categoria?");
        categoria = entry.nextLine(); 
        System.out.println (palavra+categoria);
    }
    

    Dont know what exactly you want (don't know language), but probably you wanted this:

     switch(codigo){
        case 'd':
    
        System.out.println ("Diga quantas palavras seu dicionario tera");
         numeroDePalavras = entry.nextInt();
       // entrada.nextLine();
        System.out.println ("Qual é a palavra?");
    
        for(i = 1; i < numeroDePalavras; numeroDePalavras--) {
        //Item[] itens = new Item[numeroDePalavras];
        System.out.println ("Qual é a palavra?");
        palavra = entry.nextLine();
        System.out.println ("Qual a categoria?");
        categoria = entry.nextLine(); 
        System.out.println (palavra+categoria);
      //  itens[numeroPalavras] = new Item(palavra, categoria);
        }
        break;