String repeat with method - java

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);
}
}
}

Related

StackOverflow Error in program and I cant find the reason

void recur(int i)
{
if(i==n)
return;
String sub="";
for(int j=i+1;j<n;j++)
{
sub=s.substring(i,j);
if(isPalindrome(sub))
System.out.println(sub);
}
recur(i++);
}
I am encountering a StackOverflowError at the
sub=s.substring(I,j);
statement.
s="geeks", initial value of I=0;
recur(i++);
The value of the expression i++ is the value of i at the current time; and afterwards you increment it.
As such, you are basically invoking:
recur(i);
i++;
And so you are just invoking recur again with the same parameter.
Try:
recur(++i);
Try This
public class P {
public static final String s="geeks";
static void recur(int i){
int n=6; //Size of string
if(i==n)
return;
String sub="";
for(int j=i+1;j<n;j++)
{
sub=s.substring(i,j);
//Any Function
System.out.println(sub);
}
recur(++i);
}
public static void main(String[] args) {
P.recur(0);
}
}

subroutine taking an array as a parameter in Java

In the following program, the user is supposed to enter a String (name of a City) and the program should return the index of the corresponding City in the array.
But I get an error, in the subroutine indexCities the following message:
"nameCity cannot be resolved".
I guess it is a problem of variable scoping but I don't figure out how I should do.
Thanks for your help.
import java.util.Scanner;
public class villes {
public static void main(String[] args) {
String cities[] = {"Vierzon","Salbris","Nouans","LB","LFSA","Orleans"};
Scanner input = new Scanner(System.in);
String nameCity = input.nextLine();
indexCities(cities);
}
public static int indexCities(String cities[]) {
for (int i = 0; i < cities.length; i++) {
if(nameCity.equals(cities[i])) {
System.out.println(i);
break;
}
}
}
}
nameCity is a local variable inside your main method. You can not access it outside the method.
One option for you is to pass the nameCity also as an argument in indexCities method. Also return type of your indexCities method should be void since you are not returning anything.
public static void main(String[] args) {
String cities[] = {"Vierzon","Salbris","Nouans","LB","LFSA","Orleans"};
Scanner input = new Scanner(System.in);
String nameCity = input.nextLine();
indexCities(cities, nameCity);
}
public static void indexCities(String cities[], String nameCity){
for (int i = 0; i < cities.length; i++) {
if(nameCity.equals(cities[i])) {
System.out.println(i);
break;
}
}
}
You could do it in this way:
public static void main(String[] args) {
String cities[] = { "Vierzon", "Salbris", "Nouans", "LB", "LFSA", "Orleans" };
int index = indexCities(cities, "Vierzon");
System.out.println("Index of city Vierzon is: " + index);
}
public static int indexCities(String cities[], String cityName) {
List<String> cityList = Arrays.asList(cities);
return cityList.indexOf(name);
}
Scope of variable nameCity is limited to main function. You can not access it outside of main function.
The variable is out of scope when you try to use it inside the method indexCities. One solution is making the variable nameCity an instance variable by moving it's definition out of the main method, but your code can be improved in several ways too. Check some option below:
This will print the index of the city you're looking for inside the array:
import java.util.Scanner;
public class villes {
public static void main(String[] args) {
String cities[] = {"Vierzon","Salbris","Nouans","LB","LFSA","Orleans"};
Scanner input = new Scanner(System.in);
String nameCity = input.nextLine();
indexCities(nameCity, cities);
}
public static void indexCities(String copyOfNameCity, String cities[]){
for (int i = 0; i < cities.length; i++) {
if(copyOfNameCity.equals(cities[i])) {
System.out.println(i);
break;
}
}
}
}
You you can improve it by making the method return a value. Like this:
import java.util.Scanner;
public class villes {
public static void main(String[] args) {
String cities[] = {"Vierzon","Salbris","Nouans","LB","LFSA","Orleans"};
Scanner input = new Scanner(System.in);
String nameCity = input.nextLine();
int cityIndex = indexCities(nameCity, cities);
System.out.println(cityIndex == -1 ? "City not found" : "City found in index " + cityIndex);
}
public static int indexCities(String nameCity, String cities[]){
for (int i = 0; i < cities.length; i++) {
if(nameCity.equals(cities[i])) {
return i;
}
}
return -1;
}
}
Another way is:
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class test2 {
public static void main(String[] args) {
String cities[] = {"Vierzon", "Salbris", "Nouans", "LB", "LFSA", "Orleans"};
Scanner input = new Scanner(System.in);
System.out.print("Enter the name of city to be searched -> ");
String nameCity = input.nextLine();
int cityIndex = indexCities(nameCity, cities);
System.out.println(cityIndex == -1 ? "City not found" : "Found at position " + cityIndex);
input.close();
}
public static int indexCities(String cityName, String cities[]) {
List<String> cityList = Arrays.asList(cities);
return cityList.indexOf(cityName);
}
}

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

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!

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 send an array to a method from specific location

Here is an example of what I'm looking for:
public static void main(String[] args) {
if(args.length>2){ print(args.getArrayFromIndex(2)); }
else { print(args); }
}
public static void print(String... list){
for(String str : list){ System.out.println(str); }
}
I want to know if there is some build-in method for that or the only option is to create new array from index 2 and sent it
In Java 6 or later you can use Arrays.copyOfRange method that takes the original array, the initial index (inclusive), and the last index (exclusive), and returns a copy of the specified range:
if(args.length>2){
print(Arrays.copyOfRange(args, 2, args.length));
}
You can use Arrays.copyOfRange to copy array from index to another index.
Alternatively, if you really do not want to create a new array, you can modify your print()
public static void main(String[] args) {
if(args.length>2){ print(0,1,args); }
else { print(0, args.length-1,args); }
}
//start and end are inclusive
public static void print(int start, int end, String... list){
for(int i=start; i< end+1 ; i++){
System.out.println(list[i]); }
}
If you worry about resources spent on creating new array instance, try this:
public static void print(int startFrom, String... list){
...
}
You can use it by Java.util like this
if(args.length>2){
{
String[] partOfArray = Arrays.copyOfRange(args, 2, args.length - 1);
print(partOfArray);
}
How about overloading print method to also use range value?
static public void main(String[] args) throws Exception {
String[] arr = { "0", "1", "2", "3" };
if (arr.length > 2) {
print(2, arr);
} else {
print(arr);
}
}
public static void print(int start, String... list) {
for (int i = start; i < list.length; i++) {
System.out.println(list[i]);
}
}
public static void print(String... list) {
print(0, list);
}

Categories