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).
Related
I have three classes. An abstract class, a derived class and a main class. I am trying to print the method in the derived class in the main class.
public abstract class newsPaperSub {
public String name;
public abstract void address();
public double rate;
}
Derived class:
import java.util.Scanner;
public class PhysicalNewspaperSubscription extends newsPaperSub {
#Override
public void address () {
String subAddress = " ";
Scanner input = new Scanner(System.in);
int i;
int digitCount = 0;
for (i = 0; i < subAddress.length(); i++) {
char c = subAddress.charAt(i);
if (Character.isDigit(c)) {
digitCount++;
System.out.println("Pease enter an address: ");
subAddress = input.nextLine();
if (digitCount <= 1) {
rate = 15;
System.out.println("Your subscrption price is: " + rate);
}
}
}
}
}
Main class: I havent been able to figure out what to exactly put in the main class in order to print the function in the derived class. I have tried a couple things with no luck. Any help would be greatly appreciated.
public class demo {
public static void main (String [] args) {
}
}
Just put inside of the main method
PhysicalNewspaperSubscription subscription= new PhysicalNewspaperSubscription()
and then call your method
subscription.address()
in the main method as well.
Simply put:
public class demo {
public static void main (String [] args) {
PhysicalNewspaperSubscription pns = new PhysicalNewspaperSubscription();
pns.address();
}
}
... but your code will not do anything.
The reason being because though you have a Scanner to read in something from the console, it'll never run that piece of code because the following loop structure never runs:
for (i = 0; i < subAddress.length(); i++) {
...
}
The reason it does not run is because when you declare subAddress you set it to an empty String (String subAddress = " ";), so when the loop checks the condition (i < subAddress.length()) it'll evaluate FALSE, because 0 < 0 is FALSE and hence not run the loop.
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);
}
}
}
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.
I have the following code, and I have sort the array list alphabetically in the main method, as the user inputs his strings.
Here is my code:
import java.util.Scanner;
import java.util.ArrayList;
class Main{
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<String>();
Scanner scan = new Scanner(System.in);
String name;
do{
System.out.println("Enter the next name: ");
name = scan.nextLine();
String toUpperCase = titleCase(name);
if(!toUpperCase.equals("Stop")){
names.add(toUpperCase);
}
} while(!name.equalsIgnoreCase("STOP"));
System.out.println(names.toString());
}
public static String titleCase(String s){
String output = s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
return output;
}
}
Please don't give any generic answers, I've been struggling with this for a while now. If the answer seems simple to you, it probably isn't for me.
replace this line:
names.add(toUpperCase);
with this:
int index = names.size();
for (int i = 0; i < names.size(); i++) {
if (names.get(i).compareTo(toUpperCase) > 0) {
index = i;
break;
}
}
names.add(index, toUpperCase);
so, every time you have new string from user - you will insert it into proper position of your array list
this method is quite slow, but ok for home assignment
As suggested in the comments, the most simple way of maintaining a sorted data structure upon each insert is to use a TreeSet or any other data structure that maintains sorted order internally. Instead of declaring an ArrayList<String> you would simply need to modify your code to this:
Set<String> names = new TreeSet<>();
Scanner scan = new Scanner(System.in);
String name;
do {
System.out.println("Enter the next name: ");
name = scan.nextLine();
String toUpperCase = titleCase(name);
if(!toUpperCase.equals("Stop")){
names.add(toUpperCase);
}
} while(!name.equalsIgnoreCase("STOP"));
From Javadocs for TreeSet:
the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.
Please try below code. You can replace the sorting algorithm with more efficient algorithm like merge sort/selection sort etc..
import java.util.Scanner;
import java.util.ArrayList;
class alsort{
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<String>();
Scanner scan = new Scanner(System.in);
String name;
do{
System.out.println("Enter the next name: ");
name = scan.nextLine();
String toUpperCase = titleCase(name);
if(!toUpperCase.equals("Stop")){
names.add(toUpperCase);
}
} while(!name.equalsIgnoreCase("STOP"));
System.out.println(names.toString());
for(int i=0;i<name.length();i++){
for(int j=i;j<=name.length();j++){
if(names.get(i).compareTo(names.get(j))>0){
String tmp=names.get(i);
names.set(i, names.get(j));
names.set(j, tmp);
}
}
}
System.out.println(names.toString());
}
public static String titleCase(String s){
String output = s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
return output;
}
}
public class SortedArrayList<T> extends ArrayList<T> {
/**
*
*/
private static final long serialVersionUID = 1L;
#SuppressWarnings("unchecked")
public void insertSorted(T value) {
add(value);
Comparable<T> cmp = (Comparable<T>) value;
for (int i = size()-1; i > 0 && cmp.compareTo(get(i-1)) < 0; i--)
Collections.swap(this, i, i-1);
}
public static void main(String[] s){
SortedArrayList<String> myList = new SortedArrayList<String>();
myList.insertSorted("ddd");
myList.insertSorted("aaa");
myList.insertSorted("xyz");
System.out.println(myList);
}
}
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.