Hi I have to create a program that can take a string that a user inputs through a input box and display the string in reverse in a output box. I also can't use StringBuilder. Before I knew that, I was able to do this using StringBuilder
import java.lang.StringBuilder;
import javax.swing.JOptionPane;
public class reverse
{
public static void main(String[] args)
{
String string = JOptionPane.showInputDialog("Please input a string");
JOptionPane.showMessageDialog(null, new StringBuilder(string).reverse().toString());
}
}`
So after I found out that I can't use StringBuilder I tried to reprogram this and this is the code I came up with
import javax.swing.JOptionPane;
public class reversethisstring
{
public static void main(String[] args)
{
String reverseMe = JOptionPane.showInputDialog("Please input a string");
for (int i = 0; i < reverseMe.length(); i++) {
reverseMe = reverseMe.substring(1, reverseMe.length() - i)
+ reverseMe.substring(0, 1)
+ reverseMe.substring(reverseMe.length() - i, reverseMe.length());
}
JOptionPane.showMessageDialog(reverseMe);
}
}
Now I am getting a error on line 12 that says
"The method showMessageDialog(java.awt.Component, java.lang.Object) in the type javax.swing.JOptionPane is not applicable for the arguments (java.lang.String)"
The code worked fine when I used "system.out.println" on the last line instead of the JOptionPane. So how can I convert this to work in a output box?
showMessageDialog takes two arguments, the first one being a Component. You can fix your code by just passing in null:
JOptionPane.showMessageDialog(null, reverseMe);
Try to change this line:
JOptionPane.showMessageDialog(reverseMe);
To some thing like this:
JOptionPane.showMessageDialog (null, reverseMe, "Title", JOptionPane.ERROR_MESSAGE);
Or like this:
JOptionPane.showMessageDialog (null, reverseMe);
Apart from the mentioned showMessageDialog(null, reverseMe); here's anoher go at reversing the String that uses the fact that Strings are build from char[]s.
public static void main(String[] args) {
String string = JOptionPane.showInputDialog(null, "Please input a string");
String reversed = reverse(string);
showMessageDialog(null, reversed);
}
private static String reverse(String forward) {
char[] x = forward.toCharArray();
String reversed = "";
for(int i = x.length-1; i >= 0; --i) {
reversed += x[i];
}
return reversed;
}
Related
I have to write a program that where one inputs a String and the program returns the backwards version of that String. I am using an indexOf method to count the letters in it and then invert it. The code I'm using is:
MAIN CLASS
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("enter word");
String word = in.nextLine;
word = in.nextLine;
String separate[];
Reverse rev = new Reverse();
rev.returnrev(word, separate);
rev.print(separate);
}
}
METHOD CLASS
public class Reverse{
public String returnrev(String word, String separate[]){
int len = word.length();
separate = new String[len];
for(int i=0;i<len;i++){
separate[i] = word.indexOf(len-i, len-i+1);
};
}
public String print(String separate[]){
int slen = separate.length;
for(int i=0;i<slen;i++){
System.out.print(separate[i]);
}
}
}
Read the API for the String.indexOf(...) method. It does not do what you think it does. The indexOf(...) method returns an "int" value, not a String value.
I think you want to use the String.substring(...) method (based on your existing logic). It does return a String value.
I have a string as follows
String str = "AUTHOR01BOOK"
In this string I want to add this number 00001. How can I do that?
I tried concatenate it but the output I got is AUTHOR01BOOK1. My code is not appending zeros. How can I do that?
You can use the print format.
String str="AUTHOR01BOOK";
int num = 000001;
System.out.printf("%s%06d", str, num);
or use the String.format function to store it in a variable:
String myConcat = String.format("%s%05d", str, num);
EDIT:
To answer raju's follow up question about doing this in a loop,
Create a method that will return the formatted string:
static String myConcatWithLoop(String str, int iteration){
return String.format("%s%05d", str, iteration);
}
then call this in your loop:
for (int i = 1; i <= 100; i++) {
System.out.println(myConcatWithLoop(str, i));
}
if you store '000001' in int datatype it will treat as an octal. That is
int a=000001;
System.out.println(a);
Output: 1
It will treat it as OCTAL number
So you cannot store a number beginning with 0 in int as compiler will typecast it. Therefore for that you have to work with Strings only :)
Another approach is use StringBuilder
public class JavaApplication {
public static void main(String[] args) {
JavaApplication ex = new JavaApplication();
String str = "AUTHOR01BOOK";
System.out.println(ex.paddingZero(str));
}
public String paddingZero(String str) {
StringBuilder sb = new StringBuilder();
sb.append(str);
sb.append("00001");
return sb.toString();
}
}
Please try the below code. It not only displays but also changes the string.
StringUtils help us to pad the left zeros.
Number 4 in the leftPad method denotes the number of zeros.
Its not a dynamic solution but it fulfills your need.
import org.apache.commons.lang.StringUtils;
public class Interge {
public static void main(String[] args) {
int i =00001;
String s= i+"";
String result = StringUtils.leftPad(s, 4, "0");
String fnlReslt = "AUTHOR01BOOK"+result;
System.out.println("The String : " + fnlReslt);
}
}
I am a novice programmer and I am trying to do projects that I find fun to help me learn more about the language then my school classes have been able to provide. I have wanted to try reversing a string but instead of having the string defined in a string I have added a scanner to be able to allow a user to input what they want. After searching for any help I haven't been able to find my issue that I am having. So far I have this:
import java.util.ArrayList;
import java.util.Scanner;
public class Reverse {
static ArrayList<String> newString = new ArrayList();
static int inputLength = 0;
static String PlaceHolder = null;
static String beReturned = null;
static int lengthArray = 0;
static String ToBeReversed;
static String hold = null;
public static void reversal(){
inputLength = ToBeReversed.length();
for (int e = 0; e <= inputLength; e++)
{
PlaceHolder = ToBeReversed.substring(inputLength -1, inputLength);
newString.add(PlaceHolder);
}
}
public static String putTogether()
{
int lengthcounter = 0;
lengthArray = newString.size();
for (int i = 0; i < lengthArray; i++)
{
beReturned = beReturned + newString.get(lengthcounter);
if (lengthcounter < lengthArray)
{
lengthcounter++;
}
}
return beReturned;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in); //create a new scanner
ToBeReversed = input.nextLine();
Reverse.reversal();
Reverse.putTogether();
}
}
For any input that I input there is no result. I don't get an Error Message or any form of return... The output is blank. I am just wondering if I made a mistake with the scanner or if it is how I am trying to store the characters/access them from the ArrayList I created. I am trying to not have others give me the answer completely with all the fixes, I hope I can just get a pointer or a hint to where I am messing up. Thank you for your time and help.
You need to print the output, for example
public static void main(String[] args) {
Scanner input = new Scanner(System.in); //create a new scanner
ToBeReversed = input.nextLine();
System.out.println("ToBeReversed = " + ToBeReversed);
Reverse.reversal();
System.out.println("newString = " + newString);
System.out.println(Reverse.putTogether());
}
I don't want to give a complete answer, as that would spoil your fun (and steal an opportunity for your to get started with using a debugger), but here are some hints...
You can use String#charAt to get an individual character from a String at a given index
Java is generally 0 indexed, that means that things like arrays, String, List start at index 0 and go through to length - 1
null + String = nullString ;)
You can run a loop backwards. for-loop doesn't have to run from 0-x in ascending order, they can run x-0 in descending order ;)
I'm trying to create a method that will accept 2 strings as arguments. The first string will be a phrase, the second also a prhase. What I want the method to do is to compare both strings for matching chars. If string 2 has a char that is found in string 1 then replace string 2's instance of the char with an underscore.
Example:
This is the input:
phrase1 = "String 1"
phrase2 = "Strone 2"
The output string is called newPhrase and it will have the string built from the underscores:
newPhrase = "___one 2"
Its not working for me I am doing something wrong.
public class DashedPhrase
{
public static void main(String[] args)
{
dashedHelp("ABCDE","ABDC");
}
public static String dashedHelp(String phrase1, String phrase2)
{
String newPhrase = "_";
for(int i = 0; i < phrase.length(); i++)
{
if(phrase.charAt(i) == phrase2.charAt(i))
{
newPhrase.charAt(i) += phrase2.charAt(i);
}
}
System.out.print(newPhrase);
return newPhrase;
}
}
To make it easier for you to understand, you can use StringBuilder and its method setCharAt().
Notice the i < phrase1.length() && i < phrase2.length() in the condition for the for loop. This is to make sure you don't get any ArrayIndexOutOfBounds exception.
public static void main(String[] args)
{
System.out.println("ABCDE");
System.out.println("ABDC");
dashedHelp("ABCDE","ABDC");
System.out.println();
System.out.println();
System.out.println("String 1");
System.out.println("Strone 2");
String phrase1 = "String 1";
String phrase2 = "Strone 2";
dashedHelp(phrase1, phrase2);
}
public static String dashedHelp(String phrase1, String phrase2)
{
StringBuilder newPhrase = new StringBuilder(phrase1);
for(int i = 0; i < phrase1.length() && i < phrase2.length(); i++)
{
if(phrase1.charAt(i) == phrase2.charAt(i))
{
newPhrase.setCharAt(i, '_');
}
}
System.out.print(newPhrase);
return newPhrase.toString();
}
Output:
ABCDE
ABDC
__CDE
String 1
Strone 2
___i_g_1
newPhrase.charAt(i) doesn't let you replace a character, it just returns it. Java's Strings are immutable. I you want to change it you should use StringBuilder. Look into the replace(int start, int end, String str) method.
Since you need to return a string that has the same length as phrase2, you need to iterate over each character of phrase2, and replace the matching characters of both phrases. And, of course, if phrase2 is longer than phrase1, you need to include the remaining characters in the answer. You can try this:
public static String dashedHelp(String phrase1, String phrase2) {
String ans = "";
String subChar = "_";
int i;
for(i = 0; i<phrase2.length(); i++) {
if(i<phrase1.length() && phrase1.charAt(i) == phrase2.charAt(i))
ans += subChar;
else
ans += phrase2.charAt(i);
}
return ans;
}
Hope it helps
Of course, if you need to output phrase1 with underscores in the places where phrase2 has equal characters, you can interchange phrase2 with phrase1 in the above code.
Testing it
The complete class would look like this:
public class MyClass {
public static String dashedHelp(String phrase1, String phrase2) {
// The method code goes here
}
public static void main(String[] args) {
System.out.println(dashedHelp("String 1", "Strone 2"));
}
}
The output of this program is ___o_e_2. This matches (approximately) your desired output.
The code in the example won't even compile.
newPhrase.charAt(i) += phrase2.charAt(i);
That's a bad assignment. It's the same as writing
newPhrase.charAt(i) = newPhrase.charAt(i) + phrase2.charAt(i);
but the expression on the left side of the '=' isn't something to which you can properly assign a value.
Requirement:
The program looks if a string is equal to the one or any of the characters entered by the user. The user may enter any numbers of entries separated by commas.
In essence the code should be
if user inputs one value (X) // in[0] = X;
if(str.equals(in[0]))
{
// do something
}
if user inputs two values (X,Y) // in[0] = X; in[1] = Y;
if(str.equals(in[0]) || str.equals(in[1]))
{
// do something
}
if user inputs three values (X,Y,Z) // in[0] = X; in[1] = Y; in[2] = Z;
if(str.equals(in[0]) || str.equals(in[1]) || str.equals(in[2]))
{
// do something
}
And so on......
As you can see I cannot write such a dynamic if statement.
I would have liked to have something like the below work. Any suggestions?
Trial code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class test {
public static void main (String[] args) throws Exception {
System.out.println("Enter the characters separated by commas");
BufferedReader consoleinput = new BufferedReader(new InputStreamReader(System.in));
String input = consoleinput.readLine();
input = input.toUpperCase();
String[] in = input.split(",");
String str = "N";
if (str.equals(in))
{
System.out.println("Match found");
}
else
{
System.out.println("No match");
}
}
}
What you want is some sort of loop.
foreach(string str : in) {
//code here
}
The Apache Commons CLI library provides an API for parsing command line options passed to programs
Do you look for something like this?
if (Arrays.asList(in).contains(str)) {
// do something
}