You seem a little confused about where to declare your variables. If you declare a variable inside your main method, then you can only get at those variables while you are in that method.
So when you have
Quote:
public static void main(String[] args)
{//start main
String str,s1;
...
s1=JOptionPane.showInputDialog("Input a sentence");
}//End main
|
That s1 can only ever be accessed when you are in the main method.
When you declare a varibale of the same name outside the main method:
Quote:
public class StringsAndArrays
{//start class
String str,s1,first;
public static void main(String[] args)
{//start main
String str,s1;
s1=JOptionPane.showInputDialog("Input a sentence");
}//end Main
|
Then the main method will use the variables declared inside the braces, and ignore the ones outside it.
In short your main method will be using one set of variables (the ones defined inside it) and the other methods wil be using another set of variables (the ones defined within the class).
Anyway, I have fixed up your code, and written the two other methods (words and repeat).
Code:
import javax.swing.*;
public class StringsAndArrays
{//start class
public static void main(String[] args)
{//start main
str=JOptionPane.showInputDialog("Input a sentence");
backward(str);
words(str);
repeat(str);
}//end main
//Prints out the string s backwards
public static void backward (String s)
{//start backward
s = s.reverse();
System.out.println("The sentence, after being revised is: " +s);
}//end backward
//Prints out the number of spaces in the string + 1
public static void words(String s)
{//start words
int w=1;
for(int i=0; i<s.length(); i++){
if(s.charAt(i)==' '){
w++;
}
}
System.out.println("The number of words in the sentence is: " +w);
}//end words
public static void repeat (String s)
{//start repeat
char c = s.charAt(0);
int num=0;
for(int i=0; i<s.length(); i++){
if(s.charAt(i) == c){
num++;
}
}
System.out.println(""+ c +": is repeated: " +num+ " times.");
}//end repeat
}//end class
This uses parameter passing, which I noticed you didn't use, so I hope you can understand it.
It isn't perfect, as it will crash if the user enters a string of length 0 (just presses enter). The words method is also far from foolproof, as all it does is count the number of space characters and add one to it. there are better ways of counting the number of words, though this is probably sufficient for someone just learning.
Hope you can understand it, if not just ask.