How to send an array to a method from specific location - java

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

Related

array search with exception in Java

Can you please help me with this. I need to find a value in array and if there is no such a value make an exception about it.
i did wth if else in a loop it is print 4 time NOT FOUND. Thank you very much.
public class Search {
public static int arraySearch(int [] array, int value){
for(int i = 0; i < array.length; i++){
if(array[i] == value){
System.out.println(value);
}
}
}
public static void main(String[] args) {
int [] array = { 23, 6, 9, 10};
arraySearch(array, 6);
}
}
As I pointed out in the comments, throwing an exception when searching for a missing element in an array is not really the best solution, but in another comment you say this is a requirement, so here it goes.
There are a couple of things we need to do
A custom exception we're going to throw, because there's no exception in the standard library for "I have not found an element in an array", and for good reason;
The arraySearch method needs to declare it throws the exception
The arraySearch method should return a value, not print it
If no value is returned (i.e. if we reached the end of the loop and have not returned yet) arraySearch should throw our custom exception
main needs to catch the exception and act accordingly
Here's the code. Be sure to understand it, don't just copy and paste it.
public class Search {
private static class ElementNotFoundException extends Throwable {}
public static int arraySearch(int [] array, int value) throws ElementNotFoundException {
for(int i = 0; i < array.length; i++){
if(array[i] == value){
return value;
}
}
throw new ElementNotFoundException();
}
public static void main(String[] args) {
int [] array = { 23, 6, 9, 10};
try {
System.out.println(arraySearch(array, 60));
} catch (ElementNotFoundException e) {
System.out.println("Element not found");
}
}
}
Finally, I suspect you misunderstood your homework and you actually need to return the index of the element you found, not its value (which is not very useful). I'll leave that as an exercise for you to solve.
This is one approach. The actual exception throwing can be built in.
public class Search {
public static int arraySearch(int[] array, int value) {
int result = -1;
for (int i = 0; i < array.length && result < 0; i++) {
if (array[i] == value) {
// Found! We want to know the index. We know the value
result = i;
}
}
return result;
}
public static void main(String[] args) {
int[] array = { 23, 6, 9, 10 };
System.out.println(arraySearch(array, 6));
}
}

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

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

Can I create an int array from String arguments using 'for each' loop?

I wrote the following code which gave a compile time error.
public static void main(String[] args) {
for (int number : args) {
number = Integer.parseInt(args);
System.out.println(number);
int sum = 0;
sum += number;
System.out.println(sum);
}
}
There are two problems in your code:
In the for-each statement, you must use a single variable (String) of array (String[]) to be input from array one by one. However your code uses int for String[]. Types mismatch.
The variable sum should be declaired outside of the loop. Unless sum is newly created for every loop. Scope is inappropriate.
Then the code would be modified like below:
public static void main(String[] args) {
int sum = 0;
for (String arg : args) {
int number = Integer.parseInt(arg);
System.out.println(number);
sum += number;
System.out.println(sum);
}
}
Try this:
public static void main(String[] args) {
for (String numberText : args) {
int number = Integer.parseInt(numberText);
System.out.println(numberText);
int sum = 0;
sum += number;
System.out.println(sum);
}
}
you do not need to convert that value from int to its object type reference, unless you are using string ,just remove
int number=Integer.parseInt(args);
and one thing you must pass array to for each loop .you can try like this example :
hope this will help
public static void main(String[] args) {
int sum = 0;
int[] arg = { 1, 2, 3, 4, 5, 6 };
for (int value : arg) {
sum += value;
System.out.println(sum);
}
}
}

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