Hello all,

I am trying to take input from user using scanner. The problem is, when the loop starts, it skips taking input for the first iteration. Here is the code:

import java.util.Scanner;

public class TrigTriangles{

   public static void main(String[] args){
      int N;
      double a,b,c;
      double A,B,C;
      Scanner s = new Scanner(System.in);
      C=90;
      char[] charArray;

      String input;
      System.out.println("Enter N: ");
      N = s.nextInt();

      for(int i = 0; i < N; i++){
         System.out.println("Enter line: ");
         input = s.nextLine();
         System.out.println(input);
        /*  charArray = input.toCharArray();
         if(Character.isUpperCase(input.charAt(0))){
            System.out.println("It is uppercase!");
         }
         */


      }
   }

}

Java Doc: Scanner.nextLine();
"Advances this scanner past the current line and returns the input that was skipped."

Try using Scanner.next();

Also, its better to move everything into methods, and calling them. Also, do some research on BufferredReader's.
Ex.

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
inputString = in.readLine();

It's a real problem with Scanner's design - so many people fall into this trap.
You have some input with an int followed by some text, eg
101
John Doe
... and you try to read it with

int num = scanner.nextInt();
String name = scanner.nextLine();
... and name is an empty String ("")!

Here's why:
Your input looks like this with the new line characters shown explicitly
101\nJohn Doe\n
nextInt takes the int value from the scanner, and stops when it finds a chaacter that's not part of an int, so it takes the "101", leaving this in the scanner
"\nJohn Doe\n"
then nextLine takes everything up to the first \n character - a zero-length String ("").

Possible fixes:
1. Add add extra nextLine() between the nextInt and the real nextLine to clear the unwanted \n. This may be difficult if the nextInt and the nextLine are in different areas of code which are not always executed together.
2. Give up on nextInt (etc) and just read whole lines and parse then into ints (etc) with Integer.parseInt (etc) - in which case you can junk the whole scanner and use a BufferedReader instead. new BufferedReader(new InputStreamReader(System.in))

Your loop is working one less than N. Therefore you must use

for(int i = 0; i <= N; i++){

this is working ...

Why?
The user enters N and the original code then loops N times.
Your "correction" makes it loop N+1 times, which is not what the user exepects.

use substring() method;

input.subString(beginIndex, endIndex);

commented: irrelevant -3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.