How to call method which is not void in the main driver? - java

I created the following java program in which a Statement in the form of String is taken. All the words of that statement are stored in the array separately.
Example - String statement = "hello world i love dogs";
get stored in the array as - {hello, world, i, love, dogs}
I wrote the following code, but I am not able to check it since when I call the methods in the main method, it don't work as required.
How can I get the output?
public class Apcsa2 {
/**
* #param args the command line arguments
*/
public String sentence;
public List<Integer> getBlankPositions(){
List<Integer> arr = new ArrayList<Integer>();
for (int i = 0; i<sentence.length();i++){
if(sentence.substring(i, i +1).equals(" ")){
arr.add(i);
}
}
return arr;
}
public int countWords(){
return getBlankPositions().size() + 1;
}
public String[] getWord(){
int numWords = countWords();
List<Integer> arrOfBlanks = getBlankPositions();
String[] arr = new String[numWords];
for (int i = 0; i<numWords; i++){
if (i ==0){
sentence.substring(i, arrOfBlanks.get(i));
arr[i] = sentence;
}else{
sentence.substring(i + arrOfBlanks.get(i), arrOfBlanks.get(i+1));
arr[i] = sentence;
}
}
return arr;
}
public static void main(String[] args) {
// TODO code application logic here
int[] arr = {3,4,5,2,4};
String sentence = "hello world I love dogs";
}
}

If i understand your objective, i think you want to count the number of words and also want to print/retrieve it. If that's the case then you don't have the complicate this that much. Use the below program.
public class Apcsa2 {
public static void main(String[] args) {
String input="hello world I love dogs";
String[] arryWords=input.split("\\s+");
//Count-Number of words
System.out.println("Count:"+arryWords.length);
//Display each word separately
for(String word:arryWords){
System.out.println(word);
}
}
}

Related

Is is possible to call custom methods on other custom methods?

I'm relatively new to Java here, and I'm exploring custom methods. I've coded a program where the user enters a string and it gets reversed. I'm trying to add another method to it to check if it's a palindrome(the same backwards and forwards like racecar). Is it possible to call a custom method on a custom method then run in in the main?
import java.util.Scanner;
public class Done {
public static String palindrome(String pal) {
if (rev.equals(string)) {
System.out.println("This string is a palindrome!");
return string;
}
}
public static String reverse(String string) {
String rev = "";
for (int i = 0; i < string.length(); i++) {
rev = rev + (string.charAt(string.length() - (i + 1)));
}
System.out.println("Reversed String:");
System.out.println(rev);
palindrome(rev);
return rev;
}
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("REVERSATRON 2000");
System.out.println();
System.out.println("Enter string to reverse: ");
reverse(scanner.nextLine());
}
}
Thanks for the help!
Methods can call as many methods as you want, and those methods can call even more methods. In fact, methods can even call themselves. I looked through your code and cleaned up some errors: this should work
import java.util.Scanner;
public class Done {
public static void palindrome(String s, String rev) {
if (rev.equals(s)) {
System.out.println("This string is a palindrome!");
}
}
public static void reverse(String s) {
String rev = "";
for (int i = 0; i < s.length(); i++) {
rev = rev + s.charAt(s.length() - (i + 1));
}
System.out.println("Reversed String:");
System.out.println(rev);
palindrome(s, rev);
}
public static void main(String[] args) {
System.out.println("REVERSATRON 2000");
System.out.println();
System.out.println("Enter string to reverse: ");
Scanner scanner = new Scanner(System.in);
reverse(scanner.nextLine());
}
}
Yes!
Methods are very helpful to break code down into segments. Calling methods within methods is very common as well. Infact, you've probably done it without realizing.
public static void main(String args[]){
...
}
Is a method. So if you call a method within it, you are doing just that.
Additionally, you can use a method within itself (this is called recursion).

How to put command line args into an array method?

I need to create class that has a setter to assign values to an array, then in the main method take command line arguments and use the method to put that in an array. I have no clue how to do this. Any help would be appreciated.
import java.util.*;
public class Number{
private double [] number = new double[3];
private double value ;
private int i;
public double[] getNumber() {
return sweet;
}
public void printNumber() {
System.out.println("Array " + Arrays.toString(number));
}
public double getValue(int i) {
return this.i;
}
public void setMethod(int i, double value) {
this.value = value;
this.i = i;
}
public class Score {
public static void main (String [] args) {
Number score = new Number();
// code to get values from keyboard into the array
edit: Thank you for your help I managed to create the new array. Now I need to be able to change the array value. In my setMethod I am guessing I need to change it to something like this..,
public void setMethod(int i, double value { //
for ( i = 0; i < this.array.length; i ++){
this.array[this.i] =this. value;
}
this.mark = mark;
this.pos = pos;
}
If you look at main() method's list of arguments, you'll see String[] args - command line arguments are passed to the main() method as arguments. You can simply read them using a for loop:
String[] yourNewArray = new String[args.length]:
for(int i = 0; i< args.length; i++) {
yourNewArray[i] = args[i];
}
Now in yourNewArray you have stored command line arguments.
It is worth to mention that yourNewArray doesn't need to be an array containg Strings. Arguments passed as command line arguments can be parsed and used as, for example integers, doubles and other types of values.
Now, as you edited your question and have new thing to figure out, I will show you an example, how you could implement method to assign new array to an existing one and another method to change single value in this array:
import java.util.*;
// This is your class - there is String[] arr - you want to be able to change whole array or its single value:
class MyClass {
String[] arr;
// To change whole array:
public void setMethod(String[] array) {
this.arr = array;
}
// To change only one value in array:
public void changeSingleValue(int index, String value) {
arr[index] = value;
}
}
public class Test {
public static void main(String[] args) {
String[] arrayFromArgs = new String[args.length];
for(int i = 0; i < args.length; i++) {
arrayFromArgs[i] = args[i];
}
MyClass obj = new MyClass();
// In this method you assign array storing command line arguments to the array in MyClass:
obj.setMethod(arrayFromArgs);
System.out.println("obj.arr: " + Arrays.toString(obj.arr));
// Here is an example of assigning another array to obj.arr:
String[] anotherArray = { "A", "B", "C", "D"};
obj.setMethod(anotherArray);
System.out.println("obj.arr: " + Arrays.toString(obj.arr));
// Here is another way to assign new values to obj.arr:
obj.setMethod(new String[]{"x", "y", "z"});
System.out.println("obj.arr: " + Arrays.toString(obj.arr));
// Simple example how to change single value in obj.arr by passing the index where and value that needs to be changed:
obj.changeSingleValue(1, "Changed");
System.out.println("obj.arr: " + Arrays.toString(obj.arr));
}
}
And the output of the above program:
obj.arr: [] // in this array you will see values passed as the command line arguments
obj.arr: [A, B, C, D]
obj.arr: [x, y, z]
obj.arr: [x, Changed, z]
Try something like the following code to copy your array:
public static void main (String [] args) {
// code to get values from keyboard into the array
String[] myArgs = new String[args.length];
for (int i = 0; i < args.length; i++) {
myArgs[i] = args[i];
}
// ...
}

All combination of string char

I have string and i need to print all the combination of the string Char's
Example
For the string "123" the output is:
1,2,3,12,13,21,23,31,32,123,132,213,231,312,321
It must be without loops, only with recursion.
Thanks!
public class CharacterRecursion
{
private String str;
private int counter;
public CharacterRecursion()
{
str = "";
counter = 0;
}
public CharacterRecursion(String str1)
{
str = str1;
counter = 0;
}
public String recurse(String str)
{
if (counter == 15)
{
return ;
}
counter++;
// return (recurse(String str _________) _________) _________;
}
public String [] toString()
{
String [] arr = new String[14];
for (int i = 0; i < 14; i++)
{
arr[i] = this.recurse();
}
return arr;
}
public static void main(String [] args)
{
CharacterRecursion recurse = new CharacterRecursion("123")
System.out.println(recurse.toString);
}
}
I think just giving you the full code would be a little to easy for you. This is the simple set up for the code that you would want. The recurse method is not completely finished, the return statement being one of the things that you will need to fix first. By answer the question, this way, I hope that I am still answering the question, but also still allowing you to fully learn and understand recursion on your one. By the way,
for the public static void main(String [] args) part
You would also put that in a separate class like so:
public class CharacterRecursion
{
private String str;
private int counter;
public CharacterRecursion()
{
str = "";
counter = 0;
}
public CharacterRecursion(String str1)
{
str = str1;
counter = 0;
}
public String recurse(String str)
{
if (counter == 15)
{
return ;
}
counter++;
// return (recurse(String str _________) _________) _________;
}
public String [] toString()
{
String [] arr = new String[14];
for (int i = 0; i < 14; i++)
{
arr[i] = this.recurse();
}
return arr;
}
public class CharacterRecursionClient
{
public static void main(String [] args)
{
CharacterRecursion recurse = new CharacterRecursion("123")
System.out.println(recurse.toString);
}
}
That would work just as well if you are required to have a client class. I hope that this help and cleared up at least a couple of things.

Printing a returning value

I've just started with Java, and so far been only playing around solving problems online, where you're not supposed to write the whole functional of a program, but only adjust a few lines of code to the already organized code.
However, I'm still struggling to organize my code in a compiling program in IntelliJ Idea, getting confused at,e.g. how methods invocations must be properly written.
Here's what I'm getting stuck with: an example from codingbat.com:
- Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo".
I've come up with a solution online, but now I wanna run it in Idea, with main method, with Scanner/BufferedReader input from console etc. Looks like I'm missing something...
import java.util.Scanner;
public class Bat
{
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
printString();
}
public String stringBits(String str) {
String result = "";
for (int i = 0; i<str.length();i += 2) {
result += str.substring(i, i+1);
}
return result;
}
public static void printString () {
System.out.println(result);
}
}
I ask your help to solve it out. What to do to make it:
Read a word from a console;
create a new string;
print it out.
Two alternatives:
make stringBits static
create an instance of the class Bat and invoke the member method
First solution - easy, not much to change
import java.util.Scanner;
public class Bat {
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
printString(stringBits(str));
}
public static String stringBits(String str) {
String result = "";
for (int i = 0; i < str.length();i += 2) {
result += str.substring(i, i + 1);
}
return result;
}
public static void printString (String string) {
System.out.println(string);
}
}
Second solution - a bit more advances
import java.util.Scanner;
public class Bat {
private String string;
public Bat(String string) {
this.string = string;
}
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
Bat bat = new Bat(str);
bat.printStringBits();
}
private String stringBits() {
String result = "";
for (int i = 0; i < string.length(); i += 2) {
result += string.substring(i, i + 1);
}
return result;
}
public void printStringBits() {
System.out.println(stringBits());
}
}
Your result variable is only accessible from within the "stringBits" method. Since the method returns a string you can do the following to print it:
System.out.println(stringBits(string)); //Call in main method in place of printString();
Edited: My code wasn't a working example. Note that stringBits has to be a static method in order to work.

No suitable method found? Please assist me in completing this?

I was wondering how can I use the remAll method on the very bottom of my code.
Whenever I try to use out.println(list.remAll());, it gives me an error saying
"No suitable method found for remAll"?
How can I fix this?
I have also tried using out.println(remAll(list));
I'm a beginner when it comes to Java and I am just learning, so pardon me if this is much simpler than it looks. P.S. Sorry if the format is wrong or something. It's my first post here.
import java.util.*;
import static java.lang.System.*;
public class StringArrayListLoader
{
public static void main(String args[])
{
Scanner kb = new Scanner(in);
out.print("Size of list? ");
int s = kb.nextInt();
ArrayList<String>list = new ArrayList<String>();
out.println("Enter the Strings: ");
for(int x = 0; x < s; x++)
{
out.print("String " + x + " :: ");
list.add( kb.next());
}
out.println("\nThe ArrayList you entered is ...");
out.println(list);
out.println(beginWithx(list) + " of the Strings begin with an \'x\'");
out.println(firstLast(list) + " of the Strings begin and end witletter.");
out.println("First String = Last String? " + firstLast2(list));
out.println(*******); // what am i supposed to put here?
}
public static int beginWithx(ArrayList<String>ar)
{
int count = 0;
for(int i = 0; i<ar.size(); i++)
if("x".equals(ar.get(i).substring(0,1)))
count++;
return count;
}
public static int firstLast(ArrayList<String>ar)
{
int counting = 0;
for(int i = 0; i<ar.size(); i++)
if(ar.get(i).substring(0,1).equals(ar.get(i).substring(ar.get(i).length()-2, ar.get(i).length()-1)))
counting++;
return counting;
}
public static boolean firstLast2(ArrayList<String>ar)
{
int counting = 0;
if(ar.get(0).equals(ar.get(ar.size()-1)))
return true;
return false;
}
public static void remAll(ArrayList<String>list, String s)
{
int i=0;
while(i<list.size())
{
if(list.get(i).equals(s))
{
list.remove(i);
}
else
{
i++;
}
}
out.println(list);
}
}
Your remAll method takes two parameters, an ArrayList<String> and a String. You must pass two parameters to call the method properly, such as
remAll(list, someOtherStringHere); // remAll has its own "out.println" calls
The method signature is
public static void remAll(ArrayList<String>list, String s)
So, you need to call it like:
remAll(list, "some string");
By inspection of the code, it will then remove all instances of "some string" from the list.

Categories

Resources