Sage
Sage

Reputation: 1

how to separate input in String array? Space? (beginner)

Below is the code.

public static void main(String[] args) {
    for(String e : args) {
        System.out.println(e);
    }
}

when I input one, the output is one I understand this.

But, When input one two the output is not one two but one and two.

Isn't the space a character? if not, is the space separate each inputs in a String array?

Upvotes: 0

Views: 129

Answers (6)

eunelyky
eunelyky

Reputation: 92

The space character is what separates the elements in the args array, which by the way, can be given any valid variable name. See https://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html

If you want your program to print one two in one line, pass both words as one string and run your program like this:

java -jar yourJarFile.jar "one two"

You can also look at this answer What is "String args[]"? parameter in main method Java

Upvotes: 0

user16123931
user16123931

Reputation:

You can easily read input from Console using BufferedReader.

Code :

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input1 = br.readLine();

Upvotes: 0

Debi Prasad
Debi Prasad

Reputation: 312

In Java args contains supplied command-line arguments as an array of String objects.
if you run your program as one two then args will contain ["one", "two"].
So What you are basically doing is traversing through the String array printing each of its elements.
This is the reason you are getting "one", "two" instead of "one two"

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

The Above is the equivalent code of what you have done in your one.

Upvotes: 0

DL33
DL33

Reputation: 204

You're talking about program arguments. These are intended to specify some options at program launch, and they are always split by the space symbol.

If you want to have user input in your program, check out Scanner - it is the simplest way. It provides you with methods like nextInt() to read a number, or nextWord() to read a word (separated by spaces), or nextLine() to read a line without separating by spaces.

Upvotes: 0

Erich Kitzmueller
Erich Kitzmueller

Reputation: 36987

It's actually the calling program (usually the shell) that splits the arguments.

For example, in a bash shell, you can call the program like this and get one two in one line, since it is one argument for your program:

java -jar YourProgram.jar "one two" 

Upvotes: 1

Abstract
Abstract

Reputation: 1005

The args variable is space-delimited. When you pass arguments into main from the command line, each space will indicate a different argument. E.g. C:\program.exe stuff1 stuff2 will treat stuff1 and stuff2 as two separate array elements.

Upvotes: 0

Related Questions