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.
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.
My goal is currently to take a string looking like
"######
# #
# # ##"
# is here my "character" and "#" is walls that should be avoided, I want my character to get out of the box and return the pathway, I realize my example is pretty bad but I hope you understand. The idea I have currently is to read in a text-file with that String, then creating an array as a 2-D grid and then work from there, the code I have currently is:
package soko;
import java.io.*;
import java.util.*;
public class Sokoban2 {
static File file;
Scanner input;
static int b;
static int c;
static String[][] array;
public Sokoban2() {
//array = new String [9][9];
}
public int readFile() throws Exception{
Scanner input = new Scanner(System.in);
file = new File("C:/Users/joaki/Desktop/sokoban/readin.txt");
input = new Scanner(file);
while (input.hasNext()) {
b = b + 1;
String line = input.nextLine();
System.out.println(line);
}
input.close();
return b;
//array = new String[5][5];
}
public void insertStuff() {
//array[1][1]="2";
}
public void printStuff() {
for (int r = 0; r<2;r++){
String line2 = "";
for (int d = 0; d <2;d++){
line2+="["+array[d][r]+"]";
}
System.out.println(line2);
}
}
public static void main(String[] args) throws Exception{
Sokoban g = new Sokoban();
g.readFile();
//g.insertStuff();
//g.printStuff();
//g.creatingGrid(c,b);
//System.out.println(b);
}
}
I really want to print my b, at least check it's value, but my program wont return any value, it's not even returning a null or 0, I've tried to print it as well, no luck there either, ideas ?
You aren't returning the value to any variable, I just ran your code and it works fine, it counts the lines in the file.
int b = g.readFile();
System.out.println(b);
If you don't return the value to a variable you won't have access to the value of b in your main because it's out of scope, more about that here:
https://www.cs.umd.edu/~clin/MoreJava/Objects/local.html
Edit:
I actually just realized that you declared b in your class as static and I decided to run it as you have it above, I still get it printing out the amount of lines.
g.readFile();
System.out.println(b);
If you are going to have your function return a value and you don't plan on storing b then get rid of the static declaration in your class and just declare it in the function that returns b.
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).
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 been coding a while for an assignment but can't figure out how
to receive a string input from the user to have the sentences filtered by unicode.
When I try to run the code, the input prompt won't happen. What am I doing wrong?
Any advice is appreciated.
package deel1;
import java.util.*;
public class Deel1 {
public static void main(String[] args) {
}
static String getInput() {
Scanner scan = new Scanner(System.in);
String zin = "";
System.out.println("Voer een zin in: ");
if (scan.hasNextLine()) {
zin = scan.nextLine().trim();
}
if (zin.equals("")) {
System.out.println("Geen invoer!");
System.exit(0);
}
return zin;
}
static String filterZin(String zin) {
for (int groteLetters = 65; groteLetters <= 90; groteLetters++) {
groteLetters = groteLetters + 32;
char kleineLetterAlfabet = (char) groteLetters;
}
int specialeTekens1 = 33;
int specialeTekens2 = 58;
int specialeTekens3 = 91;
if (specialeTekens1 <= 47 && specialeTekens2 <= 64 && specialeTekens3 <= 96) {
System.out.println("");
}
System.out.println("Gefilterd: " + zin);
}
}
Nah, come on, nobody posted an answer?
As Rohit pointed out, you never invoked the function!
//this method is the entry point
public static void main(String[] args) {
// invoke getting input, store it in local variable
String input = getInput();
//invoke filtering method, store result in lcal variable
String output = filterZin(input);
}
The filterZin method doesn't really do anything...
Bigger problem, that it is not even valid! The filterZin method is specified to have a String return type - and nothing gets returned. Add a return statement to the end, to get at least a syntactically correct method...
You wrote a method getXYZ() which returns a String when called.
This is your method definition:
static String getInput() {
//your code
return someString;
}
This says, when you'll call this method at any point in the program, this method will return a String object.
Inside your main method:
String returnString = getInput();
This is called method calling or invocation. You will not receive something until you call for it.
Now, about your program asking for input from user.
Here's a simple code for that:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//This will create a chain for input from console
System.out.println("Enter a line:");
String userInput;
try{
userInput = br.readline();
}catch(IOException e){
e.printStackTrace();
}