Why am I getting the wrong output? - java

I wrote this program to exchange first and last characters in a string.
I created two classes (abc and BackFront). There are no errors in Eclipse but I do not get any output. When I click run I get output of some other class. What am I doing wrong?
Class abc with main:
package puneeth;
import java.lang.*;
public class abc {
public void main(String[] args) {
BackFront object1 = new BackFront();
String str = "chocolate";
object1.frontBack(str);
}
}
Class BackFront:
package puneeth;
import java.lang.*;
public class BackFront {
public String frontBack(String str) {
String mid = str.substring(1,str.length());
String first = str.substring(0,3);
String last = str.substring(str.length());
return last + mid + first;
}
}

That's strange ,make sure you are running the correct file .

The string is changed, but you never physically print it for there to be output. You could do System.out.println(object1.frontBack(str); to get output from the output console.

The error in your code will make you laugh.
First of all, you need to print the returned string. Do this:
String res=object1.frontBack(str);
System.out.println(res);
Secondly, you need to make your main as STATIC. Do this:
public static void main(String [] args)
{
//your code
}
This will solve your problem. Hope this helps :)

Class BackFront:
package puneeth;
public class BackFront {
public void frontBack(String str) {
String result;
StringBuilder sb = new StringBuilder(str);
char first = sb.charAt(0);
sb.setCharAt(0, sb.charAt(sb.length() - 1));
sb.setCharAt(sb.length() - 1, first);
result = sb.toString();
System.out.println(result);
}
}
Class abc with main method:
package puneeth;
public class abc {
public static void main(String[] args) {
BackFront object1 = new BackFront();
String str = "chocolate";
object1.frontBack(str);
}
}
// Result:
// ehocolatc

What type of output are you expecting.
If you are expecting something in the output window you need this:
System.out.println( "My String" );

Related

How to remove a string from arrayList ending with another string?

Question : How to remove all Strings in rayList that end with the same Last Letter as lastLetter?
I write my code like this so i remove all string from ArrayList that has same end character as lastLetter
import java.util.*;
public class LastLetter
{
public static ArrayList<String> go(ArrayList<String> rayList, char lastLetter)
{
ArrayList<String> result = new ArrayList<String>();
for(int i = 0; i<rayList.size(); i++)
{
char last = rayList.set(i, rayList.get(raylist.size() - 1));
if(lastLetter == last)
result.add(rayList.remove(i));
}
return result;
}
}
I do not know if it is working or not and i do not understand how to make runner for this code please correct any problems from my code and make a runner so we can run this code properly.
My try to make runner:
import java.util.*;
class Runner
{
public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<String>();
list.add("fred");
list.add("at");
list.add("apple");
list.add("axe");
list.add("bird");
list.add("dog");
list.add("kitten");
list.add("alligator");
list.add("chicken");
LastLetter h = new LastLetter();
System.out.println(h.go(list),"m");
}
}
Please make a proper runner for this code.
Thank you
You should not remove elements while iterating the ArrayList, for more information read this post the simplest solution will be using removeif
rayList.removeIf(val-val.endsWith(String.valueOf(lastLetter)));
I would also suggest to take string as argument instead of char
public static ArrayList<String> go(ArrayList<String> rayList, String lastLetter) {
rayList.removeIf(val-val.endsWith(lastLetter));
return result;
}
And since go is static method in LastLetter class you can call it by using class name
LastLetter.go(Arrays.asList("My name is faheem"), "m");

How do I get rid of the <identifier> error in java when I compile this?

Identifier error either has ** or is in bold. I also do not know if the rest of the program will work.
import javax.swing.JOptionPane;
public class Multi
{
public static void main (String args[]);
**public static String dataIn (Stringinfo)**
{
String words = "Your hypotenuse is?";
String word1 = "Your second side is?";
String word2 = "Your thrid side is?";
int a = Integer.parseInt (words);
int b = Integer.parseInt (word1);
int c = Integer.parseInt (word2);
if ((a*a+b*b)== (c*c))
{
System.out.println ("Right triangle") ;
}
}
public static String dataIn (String info)
{
String answer = JOptionPane.showInputDialog(info); return answer;
}
}
You are declaring a method main like you would in an interface without a body. However, you can't do this outside an interface so main must have a body
public static void main (String args[]) { }
or be removed.
In addition to what #clcto said about your main method not having a body, there is another problem. You need to specify a data type while adding parameters just like when you create variables.
public static String dataIn (String Stringinfo)
Here String is the data type, just like in your other variables. Change String to be whatever fits your needs best.

Use returned array to another operation

I've read a text from file into an array. I'd like to iterate through this array in another class (to reverse an array and find every 5th element). I have a problem with use this array in another class - this class cannot see array. Could anyone help me?
package iterators;
import java.util.*;
import java.io.*;
import iterators.*;
public class Dunno{
int i = 1;
String[] something() throws IOException {
BufferedReader read = new BufferedReader(new FileReader("file.txt"));
StringBuilder sb = new StringBuilder();
String text = read.readLine();
while (text != null) {
sb.append(text);
sb.append("\n");
text = read.readLine();
}
String all = sb.toString();
String film = all;
String znak = ",";
String[] tab;
tab = film.split(znak);
for (i = 0; i < tab.length; i++) {
System.out.println(tab[i]);
}
return tab;
}
}
And 2nd class:
public class Dunno1{
Dunno dunn=new Dunno();
dunn.something();
public String dunn(){
//Iterate
}
}
In your second class you're calling the first class method in class scope, you're not calling it in a method or in main. Here is how you should do it:
public class Dunno1 {
public static void main(String[] args) throws IOException {
Dunno1 d1 = new Dunno1();
Dunno dunn = new Dunno();
String[] d = dunn.something();
d1.dunn(d);
}
public String dunn(String [] d) {
return null;
// Iterate
}
}
You need to construct an object of your second class as well so that you can call the dunn method and pass it the String array you're getting from your first class (That's why the signature of the method in my answer is different).
public class Dunno1{
Dunno dunn=new Dunno();
dunn.something();
public String dunn(){
//Iterate
}
}
The above doesn't compile, because you can't execute instructions directly inside classes. Classes must contain field declarations, constructors and methods. But not instructions.
The following would compile:
public class Dunno1{
public void foo() {
Dunno dunn = new Dunno();
String[] array = dunn.something();
// iterate over the array.
}
}
This is realy basic stuff that you should learn by reading a Java book, or a tutorial. Not by asking questions on StackOverflow.

String helper method

I need a little help on how i could put in a helper method. This is the helper method I wrote.
public static String helper(String help) {
help = help.toLowerCase();
help = help.replaceAll("\\s+", "");
}
and this is how i used it in main method.
String help = RecursivePalindrome.helper(x);
If I keep it like this then on the helper method they ask me for a return value but if i put the return help; then the method doesn't execute correctly. If I change the helper method to void then i cant put String help on my main method.
This is what happens when i run the program:
Enter a word to test whether it is a palindrome or not(press quit to end.): RaceCar
'RaceCar' is not a palindrome.
See i put the helperclass to ignore the upper cases but it wont. RaceCar would be a palindrome but the uppercase makes the program say its not.
I think you need this:
public static String helper(String help) {
help = help.toLowerCase();
help = help.replaceAll("\\s+", "");
help = help.replaceAll("\\p{Punct}", "");
return help;
}
Calling helper will return a String with all characters lowercased and every occurrence of whitespace or punctuation characters removed.
Example: helper("Race Car#") will return "racecar"
Your method should return String. Also String in Java is immutable, any modification of string returns new string. Try this:
public static String helper(String help) {
return help.toLowerCase().replaceAll("\\s+", "");
}
Here is a quick palindrom calculator I created that works for RaceCar.....using ako's helper method.
public class Main {
public static void main(String [] args){
System.out.println(palindrom(helper("RaceCar")));
}
public static String helper(String help){
return help.toLowerCase().replaceAll("\\s+", "");
}
public static boolean palindrom(String pal)
{
int end = pal.length()-1;
for(int i = 0; i<=pal.length()/2;i++)
{
if(pal.charAt(i)== pal.charAt(end-i));
else
{
return false;
}
}
return true;
}
}

I have to test Java

I was told in my class that I have to write and test my code in the main method, I wrote it, but I dont know how to test it. How I am supposed to test my methods? I am supposed to take user input, and then get the get the first letter, last letter, etc.
import java.util.Scanner;
public class Word
{
public static void main(String[] args)
{
}
public String word;
public void Word()
{
String word = "";
}
public void Word(String word1)
{
String word = word1;
}
public String getWord()
{
return word;
}
public void setWord(String newWord)
{
String word = newWord;
}
public void getFirstLetter()
{
String firstLetter = word.substring(0, 1);
}
public void getLastLetter()
{
String lastLetter = word.substring(word.length() - 1, word.length());
}
public void removeFirstLetter()
{
String noFirstLetter = word.substring(1, word.length());
}
public void removeLastLetter()
{
String noLastLetter = word.substring(0, word.length() - 1);
}
public int findLetter (String parameter)
{
word.indexOf(parameter);
return 1;
}
}
You test your methods by calling them with some defined input and compare the results with your expected output.
Example:
Suppose you have a method like this:
public static int add(int a, int b) {
return a + b;
}
You'd test it like this:
int result = add( 3, 5);
if( result != 8 ) {
//method is wrong
}
So basically you define a "contract" of what input the method gets and what the result should be (in terms of return value or other changed state). Then you check whether you get that result for your input and if so you can assume the method works correctly.
In order to be quite sure (you often can't be perfectly sure) you'd test the method several times with different types of input (as many as reasonable, to test different cases, e.g. short words, long words).
You often also test how your method handles wrong input, e.g. by passing null or empty strings.
You should have a look at tools like junit.
You can create a simple Test class and test your class and its behavior.
imports ...;
public class MyTest{
#Test
public void testMyClass(){
Word w= new Word();
w.setWord("test");
Assert.assertEquals(w.getFirstLetter(), "t");
}
}
With tools like Eclipse you could nicely run such a test.
Just a hint: you're very close you need an instance of Word, than you can call your methods
public static void main(String[] args) {
Word test = new Word();
test.setWord("something");
// here you might read javadoc of the String class on how to compare strings
}
EDIT:
I overlooked this:
public void setWord(String newWord)
{
String word = newWord;
}
The code you've written creates a variable word and newWord is assigned to it and then disappears.
If you (obviously) want to set a member of a class you should use this wich references the instance (you created in main()).
public void setWord(String newWord) {
this.word = newWord;
}
Since I would say this is homework, I will try not to explicitly give the answer. In the main method, you should set your word, then call each method and print the output to verify it is correct.
Agree with Jason. If you wanna test something, simply System.out.println() it. In your methods though, your return type is not a String but a void, so you could change that, and print it out on the main program run.
If not, just put the System.out.println() in your void methods. Shouldn't have much of a problem!

Categories