0

I am new to Java, and I need help with this code that keeps cutting short after the "do-while" loop. As in, the program ends after it is compiled and I enter a positive integer (its what satisfies the loop). I even copied the code into another file and it compiled fine. I have been scratching my head for an hour and cannot figure it out.

import java.util.Scanner;
public class BarakLoops
{
  public static void main(String[] args)
  {
    Scanner input = new Scanner(System.in);

    //Get positive values from user; declare variable(s)
    int number=-1;

    //Operate do while loop for positive int
    while (number <= 0) {
      System.out.println("Please enter a positive integer:");
      number = input.nextInt();
    }


    //Ask user for name and loop
    String name = input.nextLine();
    int length = name.length();

    for(int i=0;i<=length;i++) {
      System.out.println(name);
    }

    input.close();
  }
}

Compiler: DrJava - Eclipse 4.5 I have not found this answer elsewhere, please take your time to read.

Farid B
  • 13
  • 2
  • 5
  • What do you mean "cutting short"? Also, that is a `while` loop (**not** a do-while loop). And what is your code intended to do? – Elliott Frisch Mar 03 '19 at 05:04
  • @ElliottFrisch I mean the program ends when I enter a posotive integer, as that is what satisfies the loop. – Farid B Mar 03 '19 at 05:05
  • 1
    I'll bet `input.nextLine()` returned immediately with an empty string instead of waiting for the user to type something. Classic `nextInt()` followed by `nextLine()` issue. – Kevin Anderson Mar 03 '19 at 05:06
  • @KevinAnderson What would you recommend I use instead? This is all we were taught up to this point in class... ;( – Farid B Mar 03 '19 at 05:10
  • Add `input.nextLine();` before `String name = input.nextLine();` **and** it's a bad idea to have `input.close();` in your `main` method (since that **also** closes the **global** `System.in` - not a big deal when you immediately exit, but it can bite you if refactor that code into a method). – Elliott Frisch Mar 03 '19 at 05:13
  • @ElliottFrisch Yes that fixed it thanks, but God is Java such a pain, I learned C++ before-hand and it so much more logical and user-friendly. Java has too many words. C++ just got to the point. :) – Farid B Mar 03 '19 at 05:20
  • Odd; I learned C++ before Java as well and I stuck with Java because I preferred it (writing portable C++ in 1997 was a **pain**). Best of luck! – Elliott Frisch Mar 03 '19 at 05:27

0 Answers0