Show the Java args[] in one line [duplicate] - java

This question already has answers here:
Print multiple lines output in java without using a new line character
(9 answers)
Closed 7 years ago.
I wrote this
public class Main {
public static void main(String[] args) {
for (int i =0; i < args.length; i++){
System.out.println(args[i]);
}
}
}
in cmd typed:
C:\> javac Main.java
C:\> java Main first second third
The console showed me
first
second
third
Questin is how to make that cmd shows me arguments in one line?

Should be something like this.
public class Main {
public static void main(String[] args) {
for (int i =0; i < args.length; i++){
System.out.print(args[i] + " ");
}
}
}

You are using System.out.println().
The println method will terminate current line by writing the line separator string for you. (Which in your case is the newline character.)
Instead, you want to use System.out.print().
Like so:
System.out.print(args[i] + " ");
This will print your argument, followed by a space instead of a newline character.

Use System.out.print() instead of println().

If you want the printing to continue in the same line, you need to invoke a print() method instead of a println() method.
Also, since this resembles the echo program, if you want it to be perfect, you want to have space between the strings, but not before the first or after the last.
With Java 4 and older:
public class Main {
public static void main(final String[] args) {
for (int i = 0; i < args.length; i++) {
if (i > 0)
System.out.print(" ");
System.out.print(args[i]);
}
System.out.println();
}
}
With Java 5-7 you could use foreach-loops, although in this special case that's not really better, it's just for completeness:
public class Main {
public static void main(final String... args) {
boolean isFirst = true;
for (final String arg : args) {
if (isFirst)
isFirst = false;
else
System.out.print(" ");
System.out.print(arg);
}
System.out.println();
}
}
With Java 8:
public class Main {
public static void main(final String... args) {
System.out.println(String.join(" ", args));
}
}
If you want your program to be fast - which would not be necessary in this case, this again is just for completeness - you would want to first assemble the String and then print it in one go.
With Java 4 and older:
public class Main {
public static void main(final String[] args) {
final StringBuffer sb = new StringBuffer();
for (int i = 0; i < args.length; i++) {
if (i > 0)
sb.append(' ');
sb.append(args[i]);
}
System.out.println(sb);
}
}
With Java 5-7:
public class Main {
public static void main(final String... args) {
final StringBuilder sb = new StringBuilder();
for (final String arg : args)
sb.append(arg);
if (args.length > 0)
sb.setLength(sb.getLength() - 1); // skip last space
System.out.println(sb);
}
}
With Java 8 (no difference):
public class Main {
public static void main(final String... args) {
System.out.println(String.join(" ", args));
}
}
The code which I prefer:
import static java.lang.String.join;
import static java.lang.System.out;
public class Main {
public static void main(final String... args) {
out.println(join(" ", args));
}
}
Hope this helps, have fun with Java!

Related

String repeat with method

So I need to write a method which accepts one String object and one integer and repeat that string times integer.
For example: repeat("ya",3) need to display "yayaya"
I wrote down this code but it prints one under the other. Could you guys help me please?
public class Exercise{
public static void main(String[] args){
repeat("ya", 5);
}
public static void repeat(String str, int times){
for(int i = 0;i < times;i++){
System.out.println(str);
}
}
}
You are printing it on new line, so try using this :
public static void repeat(String str, int times){
for(int i = 0;i < times;i++){
System.out.print(str);
}
}
You're using System.out.println which prints what is contained followed by a new line. You want to change this to:
public class Exercise{
public static void main(String[] args){
repeat("ya", 5);
}
public static void repeat(String str, int times){
for(int i = 0; i < times; i++){
System.out.print(str);
}
// This is only if you want a new line after the repeated string prints.
System.out.print("\n");
}
}
Change System.out.println() to System.out.print().
Example using println():
System.out.println("hello");// contains \n after the string
System.out.println("hello");
Output:
hello
hello
Example using print():
System.out.print("hello");
System.out.print("hello");
Output:
hellohello
Try to understand the diference.
Your example using recursion/without loop:
public class Repeat {
StringBuilder builder = new StringBuilder();
public static void main(String[] args) {
Repeat rep = new Repeat();
rep.repeat("hello", 10);
System.out.println(rep.builder);
}
public void repeat(String str, int times){
if(times == 0){
return;
}
builder.append(str);
repeat(str, --times);
}
}
public class pgm {
public static void main(String[] args){
repeat("ya", 5);
}
public static void repeat(String str, int times){
for(int i = 0;i < times;i++){
System.out.print(str);
}
}
}

Increased cohesion in simple java program

I have a small java program that collects 10 words written by a user and prints them in specified orders. As it stands, the program works, but it is not cohesive.
My issue stems from not knowing enough about the concept of cohesion to work on fixing this, as well as being new to Java/OO languages.
I believe that the class Entry is way way way too cluttered, and that another class should take on some of this class' functions.
Any hint or clue, cryptic or otherwise would be greatly appreciated!
The lack of a input reader in Dialogue.java is intentional, as the original code uses proprietary code.
These are the three classes: entry, dialogue and printer.
Entry.java
public class Entry {
public static void main(String[] args){
String[] wordArray = new String[10];
Dialogue d = new Dialogue();
wordArray = d.read(wordArray);
Printer p = new Printer();
p.printForwards(wordArray);
p.printBackwards(wordArray);
p.printEveryOther(wordArray);
}
}
Dialogue.java
public class Dialogue {
public String[] read(String[] s){
String[] temp;
temp = new String[s.length];
for(int i=0;i<s.length;i++){
String str = anything that reads input("Enter word number" + " " + (i+1));
temp[i] = str;
}
return temp;
}
}
Printer.java
public class Printer {
public void printForwards(String[] s){
System.out.println("Forwards:");
for(int i=0;i<s.length;i++){
System.out.print(s[i] + " ");
if(i==s.length-1){
System.out.println("");
}
}
}
public void printBackwards(String[] s){
System.out.println("Backwards:");
for(int i=s.length-1;i>=0;i--){
System.out.print(s[i]+ " ");
if(i==0){
System.out.println("");
}
}
}
public void printEveryOther(String[] s){
System.out.println("Every other:");
for(int i = 0; i < s.length; i++){
if(i % 2 == 0){
System.out.print(s[i] + " ");
}
}
}
}// /class
It looks okay overall, the truth is it is a very simple task where as OOP is better suited for more complex programs. That being said, here are a few pointers/examples.
You can also do your printing more OOP style.
The purpose of this is build reusable, modular code. We do this by abstracting String array manipulations (which previously existed in the Printer class) to it's own class.
This is also very similar/also known as loose-coupling. We achieve loose-coupling by splitting the string processing functionality and the printing functionality.
Change you Printer class to StringOrderer or something along those lines:
public class StringOrderer {
private String[] array;
public class StringOrderer(String[] array) {
this.array = array;
}
public String[] getArray() {
return array;
}
public String[] everyOther(){
String[] eos = new String[array.length];
for(int i = 0; i < s.length; i++){
if(i % 2 == 0){
eos[eos.length] = s[i];
}
return eos;
}
public String[] backwards() {
...
And then in your main class add a method like such:
private static void printStringArray(String[] array) {
for (int i=0; i<array.length; i++) {
System.out.print(array[i]);
}
}
Then call it in your main method:
StringOrderer s = new StringOrderer(wordArray);
System.out.println('Forward:');
printStringArray(s.getArray());
System.out.println('Every other:');
printStringArray(s.everyOther());
System.out.println('Backwards:');
...
Extra tip - You can also add methods in your main class like so:
public class Entry {
public static void main(String[] args){
String[] wordArray = readWordArray()
Printer p = new Printer();
p.printForwards(wordArray);
p.printBackwards(wordArray);
p.printEveryOther(wordArray);
}
private static String[] readWordArray() {
Dialogue d = new Dialogue();
return d.read(new String[10]);
}
}
to make it more readable.

Why does println not show up - Java

I am a newb with Java so don't bite me please..
I've made this method, but it will not show up in the console screen, why?
public class ADSopgave2K1 {
public static void main(String[] args) {
}
public void print(String s, int pos) {
s = "";
pos = s.length();
int count = s.length();
char[] ray;
System.out.println("Enter a word: ");
Scanner userInputF = new Scanner(System.in);
s = userInputF.nextLine();
ray = s.toCharArray();
for (int t = 0; t < s.length(); t++) {
System.out.println(ray[t]);
return;
}
}
}
You did not call that method yet. Try to call your method.
public static void main(String[] args) {
ADSopgave2K1 intance=new ADSopgave2K1();
intance.print();
}
Edit
public void print() {
System.out.println("Enter a word: ");
Scanner userInputF = new Scanner(System.in);
String s = userInputF.nextLine();
char[] ray = s.toCharArray();
for (int t = 0; t < s.length(); t++) {
System.out.println(ray[t]);
}
}
When you run your program, Java will call main(String[] args).
But this is an empty function, so you will not see any output.
Becasue, you did not call anything in main(String[] args) method. Make your print method static and call this to your main method.
public static void print(String s, int pos){
}
EDIT:
public static void main(String[] args){
print("test",1);
}
ADSopgave2K1 r=new ADSopgave2K1();
r.print("jai", 4);
Create an object of your class in side main method and then call its method.
You should call print() method.
public class ADSopgave2K1 {
public static void main(String[] args)
{
print("Hello World", 1);
}
public void print(String s, int pos)
{
s = "";
pos = s.length();
int count = s.length();
char[] ray;
System.out.println("Enter a word: ");
Scanner userInputF = new Scanner(System.in);
s = userInputF.nextLine();
ray = s.toCharArray();
for (int t = 0; t < s.length(); t++) {
System.out.println(ray[t]);
return;
}
}
}
You have to call your method inside main() by creating instance for your class
either you make print method static and call it with correct argument
Or
make instance of ADSopgave2K1 class and call it with correct args

How to parse the command parameter in java?

For example, the user run my programme like this
myprogram -p1 my_name, -p2 my_address, -p3 my_gender
But the user may type this, and it still valid:
myprogram -p2 my_address, -p1 my_name,-p3 my_gender
How can I parse it in Java? Thanks.
You can use something like this:
public static void main (String[] args) {
for(int i = 0; i < args.length; i++) {
if(args[i].equals("-p1")) {
// args[i+1] contains p1 argument
} else if(args[i].equals("-p2")) {
// args[i+1] contains p2 argument
}
}
}
Make sure to check whether the i+1 argument is there, otherwise an exception will be thrown.
There are more advanced methods of going this, you could e.g. use hashing to map the flag to the processing function. But, for this purpose, I guess this will do.
What I do not understand is the use of comma's in your sample. What are they used for?
If you're looking for a DIY, then maybe this might be starting point.
public class Foo
{
private static final String[] acceptedArgs = { "-p1", "-p2", "-p3" };
public void handleCommandArgs(String... args)
{
if (args != null)
{
for (int argIndex = 0; argIndex < args.length; argIndex++)
{
for (int acceptedIndex = 0; acceptedIndex < acceptedArgs.length; acceptedIndex++)
{
if (args[argIndex] != null && args[argIndex].equals(acceptedArgs[acceptedIndex]))
{
String arg = args[argIndex], param = args[argIndex + 1];
performRoutine(arg, param);
}
}
}
}
}
private void performRoutine(String arg, String param)
{
System.out.println(arg + " ->" + param.replace(",", ""));
}
public static void main(String[] args)
{
(new Foo()).handleCommandArgs(args);
}
}
Sample from Java Tutorials #Oracle
public static void main (String[] args) {
for (String s: args) {
System.out.println(s);
}
}
The params come in a vector of String.

How can you write a function that accepts multiple types?

I have a function that should work on int[] and on String[] now i have made the same function with a int parameter and an String parameter however if it has to go this way its a bit copy paste work and doesn't look very organized is there a way to solve this and put these 4 functions in 2?
static public void print(String s)
{
System.out.println(s);
}
static public void print(int s)
{
System.out.println(s);
}
static public void printArray(String[] s)
{
for (int i=0; i<s.length; i++)
print(s[i]);
}
static public void printArray(int[] s)
{
for (int i=0; i<s.length; i++)
print(s[i]);
}
Thanks
Matthy
With autoboxing / autounboxing, you can do this:
public static void print(Object s) {
System.out.println(s.toString());
}
public static <T> void printArray(T[] arr) {
for (T t : arr) {
print(t);
}
}
The one drawback is that the argument to printArray must be an array of a reference type, but unlike the varargs solution this will work for any reference type.
Edit: regarding the varargs solution and #matthy's question about combining the two methods into one (ie generifying it), you could also do something like this:
static public <T> void print(T... ts) {
for (T t : ts) {
System.out.print(t + " ");
}
System.out.println("");
}
However, you still cannot call it on an array of primitives:
int[] x = { 1, 2 };
print(x);
Because Java takes T to be int[] and will execute the toString method of the array rather than iterate through the contents. If you call it on an array of Integer or other reference type then it will work also.
static public void print(String...strings){
for(String str : strings){
System.out.println(str);
}
}
static public void print(int...ints){
for(int i : ints){
System.out.println(i);
}
}
Well, the Basic class java.lang.Object matches String as well as int, byte, ... (Autoboxing converts them to Integer, Byte and so on). The method String.valueOf() lets you create a string of these. (toString() is available too)
Use Generics, if applicable to your code:
static <T> void printArray(T[] s)
{
for (int i=0; i<s.length; i++)
System.out.println(s[i]);
}
Combining the previous answers yield:
public class Test {
static <T> void print(T... ts) {
for (T t : ts)
System.out.println(t);
}
public static void main(String... args) {
String[] strArr = { "one", "two" };
Integer[] intArr = { 3, 4 };
String str = "five";
int i = 6;
print(strArr);
print(intArr);
print(str);
print(i);
}
}
Output:
one
two
3
4
five
6
class MyClass {
public static void main(String[ ] args) {
String name ="David";
int age = 42;
double score =15.9;
char group = 'Z';
System.out.println(group + "\n" + name + " \n" + age + " \n" + score);
}
}

Categories