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));
}
Related
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'm new to Java and would appreciate any assistance to solve the following problem.
I would like the java program to read and print a two column (integer or double) text file and search for a value in the first column that matches with another parameter within the java code. If the match is found, to print out the corresponding value on the second column. I wrote the following code which can read and print the data in console but I'm unable to use this data in the next code to search for a value in the first column that matches with another parameter. please help,here is my code:
import java.io.File;
import java.util.Scanner;
public class readfile {
private Scanner s;
public static void main(String[] args) {
readfile r = new readfile();
r.openFile();
r.readFile();
r.closeFile();
}
public void openFile() {
try {
s = new Scanner (new File("filename.txt"));
}catch(Exception e) {
System.out.println("file not found ");
}
}
public void readFile() {
while(s.hasNext()) {
String a = s.next();
String b = s.next();
System.out.printf("%s %s\n",a, b);
}
}
public void closeFile() {
s.close();
}
}
// here is the problem!
double a = 0;
double b = 0;
if (para == a[i]) {
System.out.println("param =" + a[j]);
}else {
System.out.println("It is out of range ");
}
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.
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. :/
I have tried to develop code for project euler
Problem 17
I have successfully written a java program and the output appears as expected. But however the online judge says it is the wrong answer. Have a look at my code:
package projectEuler;
import java.util.*;
public class Problem17 {
/**
* #param args
*/
static String []units={"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
static String []special={"Ten","Eleven","Twelve","Thirteen","Fourteen",
"Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
static String []tens={"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy",
"Eighty","Ninety"};
static String hundredValue="Hundred and";
public static void main(String[] args)
{
long totalLength=0;
for(int currentNumber=1;currentNumber<=1000;currentNumber++)
{
String currentWord=getWords(currentNumber);
// System.out.println(currentNumber+"->"+currentWord.replaceAll(" ",""));
totalLength+=currentWord.replaceAll(" ","").length();
}
System.out.print("The total length of all the word is :"+totalLength);
/*Scanner input = new Scanner(System.in);
System.out.print("Enter a number :");
int num = input.nextInt();
System.out.print(getWords(num));*/
}
public static String getWords(int num)
{
//Find the equivalent word and return it
String wordValue="";
switch(String.valueOf(num).length())
{
case 1:
wordValue=operateOn_1(num);
break;
case 2:
wordValue= operateOn_2(num);
break;
case 3:
wordValue= operateOn_3(num);
break;
default:
wordValue="One Thousand";
}
return wordValue;
}
public static String operateOn_3(int num)
{
String result="";
result= Problem17.units[num/100]+" "+
Problem17.hundredValue+" "+
operateOn_2(Integer.parseInt((String.valueOf(num).substring(1))));
return result;
}
public static String operateOn_2(int num)
{
String result="";
if(String.valueOf(num).charAt(0)=='1')
{
result=Problem17.special[num%10];
}
else
{
result=Problem17.tens[Integer.parseInt(String.valueOf((String.valueOf(num)).charAt(0)))];
result+=" "+operateOn_1(num%10);
}
return result;
}
public static String operateOn_1(int num)
{
return (Problem17.units[num]);
}
}
The total length which the program found out as 21592 but it is wrong according to project euler. If any could have a look at my code and help me please...
It looks like the problem is with the word 'and'
static String hundredValue="Hundred and";
Which should not occur for numbers such as 300 (Three hundred and)
In addition to the "Hundred and"-problem described by Christopher, there is another issue:
You pass an int to operateOn_2, which you then convert to a string. This way, you miss the leading zero when converting a number like 101, which is converted to One Hundred and Eleven