Java getString method

Jamie picture Jamie · Oct 9, 2015 · Viewed 15.9k times · Source

So I have the questions in the top part, but I want to have all the questions at the top, and when I need to ask the questions, I can just pull them down using a variable defined as the question. Right now however, the code is asking the questions from where the questions are, not using the variable "ask" and asking from System.out.print(ask). Any ideas on how to get it to do that?

import java.util.Scanner;

public class Greetings {

    public static void main(String[] args) {

        Scanner newscanner = new Scanner(System.in);

        String ask = getString(newscanner, "Please enter your first name: ");

        // String ask2 = getString(newscanner, "Please enter your last name: ");

        // String ask3 = getString(newscanner, "Please enter your year of birth:
        // ");

    }

    public static String getString(Scanner newscanner, String ask) {

        System.out.print(ask);

        String first = newscanner.next();

        String firstletter = first.substring(0, 1).toUpperCase();

        return firstletter;

    }

}

Answer

AlphaModder picture AlphaModder · Oct 9, 2015

Perhaps what you are looking to do is have the question be printed, and then the answer typed on the line below it? If so, what you need to do is change the first call in getString from System.out.print to System.out.println, which should add on a newline after the question, moving the input to the next line.

EDIT: This is what it might look like now:

Please enter your first name:John

And here's what it would change to:

Please enter your first name:
John