Java recursive System.out.println() - java

package test;
import java.util.Scanner;
public class Char {
public static void main(String[] args) {
char c = 0;
Scanner scan = new Scanner(System.in);
printeaza(c, scan);
}
public static char printeaza(char c, Scanner sc) {
c = sc.next().charAt(0);
if (sc.hasNext()) {
System.out.println(printeaza(c, sc));
return c;
} else {
return c;
}
}
}
What i'm trying to do is type letters from the keyboard and then have them diplayed in reverse. I know it can be made very easy with a for loop and char arrays but i'm curious about making it recursively and using only one char variable. I almost made it but it seems it prints all but the first letter.
So if I type: "a s d f" instead of "f d s a" i get only "f d s". I think I know why, it's because the Println statement it's only inside the if statement but I kind of run of ideeas about how to make the function "catch" the first letter as well. I hope you can have a look, thanks!

Your first call to printeaza(c, scan) (made from public static void main) needs to be wrapped with a System.out.println(..) as well.
Like this:
package test;
import java.util.Scanner;
public class Char {
public static void main(String[] args) {
char c = 0;
Scanner scan = new Scanner(System.in);
System.out.println(printeaza(c, sc)); // <-- changed line
}
public static char printeaza(char c, Scanner sc) {
c = sc.next().charAt(0);
if (sc.hasNext()) {
System.out.println(printeaza(c, sc));
return c;
} else {
return c;
}
}
}
Incorporating Cruncher's advise, I'd write it like this:
package test;
import java.util.Scanner;
public class Char {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println(printeaza(sc));
}
public static char printeaza(Scanner sc) {
char c = sc.next().charAt(0);
if (sc.hasNext()) {
System.out.println(printeaza(sc));
}
return c;
}
}

The problem is that a call to printeaza doesn't print its own character, only that of it's recursive call.
In other words, printeaza(c, scan); in main needs to be changed to System.out.println(printeaza(c, scan);
Also, I would just like to point out that using recursive calls for user input like this is not a very good idea to be honest. :/

Related

InputMismatch error trying to take integer as user input

I am trying to take an integer as user input and store it in a list until the user hits 'q'. At the moment the user inputs 'q', the loop gets terminated.
The code is showing an InputMismatch error:
import java.util.*;
public class SampleArrayList {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s;
int n;
List<Integer> array = new ArrayList();
while (true) {
n = sc.nextInt();
s = sc.nextLine();
if (s.equals("q")) {
break;
} else {
array.add(n);
}
}
Collections.sort(array);
System.out.println(array);
}
}
Just try this,
Inside your while loop to get input for a string use,
s = sc.next();
Instead of sc.nextLine();.
Are you trying to implement it like the example below?
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s;
List<Integer> array = new ArrayList();
while (true) {
s = sc.nextLine();
if (s.equalsIgnoreCase("q")) {
break;
}
int num = Integer.parseInt(s);
array.add(num);
}
Collections.sort(array);
System.out.println(array);
}
}
Looks like q is trying to be stored as an int, so this should work:
All numbers stored as a String can be parsed as an int with the parseInt() method.
s = sc.nextLine();
if (!s.equals("q"))
{
array.add(Integer.parseInt(s));
}
else
{
break;
}

Cannot convert from void to char [duplicate]

This question already has an answer here:
What does "Incompatible types: void cannot be converted to ..." mean?
(1 answer)
Closed 4 years ago.
I just started programming in Java so I'm still pretty much a noob. I tried to check if a sentence contains a specific word. This is my code:
public static void run(String sentence) {
System.out.print("Please provide a string");
Scanner sc = new Scanner(System.in);
String str1 = sc.next();
if(str1.contains("Andy")) {
System.out.print("V");
}
else {
System.out.print("X");
}
}
And I have to run the following test:
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class Assignment1_3Test {
#Test
public void runTestOnlyAndy() {
char output = Assignment1_3.run("Andy");
assertEquals('V', output);
}
#Test
public void runTestNoAndy() {
char output = Assignment1_3.run("This does not contain the word An-dy");
assertEquals('X', output);
}
#Test
public void runTestNoText() {
char output = Assignment1_3.run("");
assertEquals('X', output);
}
#Test
public void runTestAndyAtTheEnd() {
char output = Assignment1_3.run("This contains the word Andy");
assertEquals('V', output);
}
#Test
public void runTestAndyMiddle() {
char output = Assignment1_3.run("This contains the word Andy in the
middle of the sentence");
assertEquals('V', output);
}
}
Now when I run this test I get the following error: Type mismatch: cannot convert from void to char. I don't know how to fix this, but I think it's just a small thing and it really frustrates me that I don't know how to fixt it. So if someone could give me tip on how to fix this, it would be really appreciated!
Change your run method to the one below. Note that you are not using the string parameter. You should probably refactor to the refactored version instead.
public static char run(String string) {
Scanner sc = new Scanner(System.in);
System.out.print("Please provide a string");
String str1 = sc.next();
if(str1.contains("Andy")) {
return 'V'
} else {
return 'X'
}
}
Refactored version:
public static char containsAndy(String string) {
return string.contains("ANDY") ? 'V' : 'X';
}
If you want your method to be easy to test, you should not read the sentence inside the method, but provide it as argument. See the below main for an example:
public static void main(String args[]) {
System.out.print("Please provide a string");
String sentence= sc.next();
System.out.print("Sentence contains Andy: " + containsAndy(sentence));
}

Not being able to return an int from incrementation

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.

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).

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.

Categories

Resources