This question already has answers here:
How do I convert from int to String?
(20 answers)
How to Convert an int to a String? [duplicate]
(6 answers)
Closed 7 years ago.
private JTextField resultTextField;
resultTextField.setText(" "); ...
private class InputListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Stack<Integer> operandStack = new Stack<Integer>();
Stack<Character> operatorStack = new Stack<Character>();
String input = inputTextField.getText();
StringTokenizer strToken = new StringTokenizer(input, " ", false);
while (strToken.hasMoreTokens())
{
String i = strToken.nextToken();
int operand;
char operator;
try
{
operand = Integer.parseInt(i);
operandStack.push(operand);
}
catch (NumberFormatException nfe)
{
operator = i.charAt(0);
operatorStack.push(operator);
}
}
int result = sum (operandStack, operatorStack);
resultTextField.setText(result);
The last line that reads: "resultTextField.setText(result);" in the code provided, I'm trying to convert the 'result' variable to a String but having no success. The compile error message I get is:
PrefixExpression.java:96: error: method setText in class JTextComponent cannot be applied to given types;
resultTextField.setText(result);
^
required: String
found: int
reason: actual argument int cannot be converted to String by method invocation conversion.
I've tried several methods already provided in answers to other 'convert int to String' questions in here, but none of them work. How do I convert 'result' to a String? Thanks for your help.
This will convert an int to a string:
resultTextField.setText(Integer.toString(result));
EDIT: As mentioned below there is no need to import java.lang as it will be available always.
You can use the Integer.toString(number) or String.valueOf(number) function. This function can take an integer and turn it into a String.
Try adding:
String numResult = Integer.toString(result);
or
String numResult = String.valueOf(result);
You could do a hack
resultTextField.setText(result + "");
Just do this: (new Integer(result)).toString() and you should be OK.
Related
This question already has answers here:
Get string character by index
(13 answers)
Closed 4 years ago.
I'm attempting to create a new array of indexes from str2 parameter, but getting this error: "Array required, but string found."
I'm learning Java, and only comfortable writing in Javascript. Could someone explain what this error message means?
public class Scramblies {
public static boolean scramble(String str1, String str2) {
String alphabet = "abcdefghijklmnopqrstuvwxyz";
int[] inOfStr2Nums = new int[str2.length()];
for (int i = 0; i < str2.length(); i++){
inOfStr2Nums[i] = alphabet.indexOf(str2[i]);
}
System.out.println(inOfStr2Nums);
}
}
To fix the error:
inOfStr2Nums[i] = alphabet.indexOf(str2.charAt(i));
This question already has answers here:
Replace a character at a specific index in a string?
(9 answers)
Closed 4 years ago.
public class Main {
public static void main(String[] args) throws Exception {
String name = "eric";
String nameForYou = name.replaceAll(".","*");
String afterGuess="";
System.out.println("Guess my name: "+nameForYou+" "+name.length());
String yourguess = "c";
for (int i=0;i<name.length();i++) {
if ((yourguess.charAt(0) == name.charAt(i))){
afterGuess = nameForYou.replace(nameForYou.charAt(i),yourguess.charAt(0));
}
}
System.out.println(afterGuess);
}
}
I want output as:
Guess my name: **** 4
***c
I don't want it to replace all the "*"
Your strategy does not work, because replace replaces the first character that it finds, which is not necessarily the character in the right position.
Since Java String is immutable, a better approach for your replacement code should be to make a char array of the appropriate length, and convert it to String only for printing:
String name = "eric";
char[] nameForYou = name.replaceAll(".","*").toCharArray();
System.out.println("Guess my name: "+new String(nameForYou)+" "+name.length());
String yourguess = "c";
for (int i=0;i<name.length();i++) {
if ((yourguess.charAt(0) == name.charAt(i))){
nameForYou[i] = yourguess.charAt(0);
}
}
System.out.println(new String(nameForYou));
Java arrays are mutable, so you have direct control over characters at a specific index. You could also use StringBuilder if you prefer not to deal with arrays directly.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I've been trying to create a program that censors a word but I was having difficulty with that so I tried going back to some of the fundamental code and testing it and I am coming across an odd result.
import java.util.Scanner;
public class TextCensor
{
public static void main(String[] args)
{
String input;
Scanner keyboard = new Scanner(System.in);
input = keyboard.nextLine();
int length = input.length() - 1;
if (length + 1 >= 3)
{
for (int i=0; i<(length - 1); i=i+1 )
{
char first = input.charAt(i);
char second = input.charAt(i+1);
char third = input.charAt(i+2);
String censorCheck = "" + first + second + third;
if (censorCheck == "tag")
{
System.out.println("success");
}
else
{
System.out.println(censorCheck);
}
}
}
else
{
System.out.println(input);
}
}
}
If I input the string "adtag" I will obtain the following output:
adt
dta
tag
yet "success" will never be printed despite the fact that I have printed a censorCheck that is equal to "tag".
String is an object. You have to compare objects by equals():
censorCheck.equalsIgnoreCase("tag")
Ignore case works fir upper letters as well.
Only for primitives you can use comparison by ==:
3 == 3
You are trying to check whether both instance of String is same or not instead of checking contents of both string.
You should try censorCheck.equals("tag") .
To compare whether contents of two string are equal or not in JAVA you should use the equals() method. You cannot compare the value of two string by the == operator . In your case use if (censorCheck.equals("tag")) and see if you get the desired result.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I'm writing a simple code to test the value that was inputted to my constant value.
I declared this code as my constant value.
String LetMeThrough = "drunk";
String GotAnID = "drunk";
This is the whole code.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner DrunkTest = new Scanner(System.in);
String InputDrunk;
String InputDrunkAgain;
String LetMeThrough = "drunk";
String GotAnID = "drunk";
System.out.print("Type drunk: ");
InputDrunk= DrunkTest.next();
System.out.print("Re Type drunk: ");
InputDrunkAgain = DrunkTest.next();
if(InputDrunk == LetMeThrough & InputDrunkAgain == GotAnID){
System.out.print("You're not DRUNK");
}
else
System.out.print("You're F***** DRUNK");
}}
The problem is that if I type "drunk" on both.
I will get "You're F****** DRUNK" instead of the "You're not DRUNK".
When the inputted values is the same as my constant values.
You must use String::equals method to compare.
This question already has answers here:
Checking if String x equals any of the Strings from String[]
(12 answers)
Closed 9 years ago.
while writing my program I have run into another nooby road block.
if(StringTerm[0].equals("wikipedia"))
{
StringBuilder SearchTermBuilder = new StringBuilder();
for(int i = 1; i < StringTerm.length; i++)
{
SearchTermBuilder.append(StringTerm[i] + " ");
}
// This is the string it outputs.
WIKI_ID = "Wikipedia";
SearchTerm = SearchTermBuilder.toString();
SearchTermFull = WikiBaseLinkReference.WIKI_WIK + SearchTermBuilder.toString();
}
This code checks for input from a console command "/wiki" and checks to see if the first string after the word "wiki" matches "wikipedia" and if so, it builds a string to match what I want it to do.
This is all well and good, and the program works fine, but I want users to be able to use different keywords to get the same results.
For Example: If I type /wiki wikipedia, it would do the same as /wiki pediawiki
If I made an array of different names called WIKIPEDIA
public static String WIKIPEDIA[] = {"wikipedia","pediawiki"};
How would I tell the if statement to check to see if the text entered equals one of the strings inside of my array? Every time I try to use an || or operator it throws me some errors.
Thanks in advance.
You need a version of "any":
public boolean any(String[] array, String s) {
for(String value : array) {
if(s.equals(value)) { return true; }
}
return false;
}
Then
if(any(WIKIPEDIA, "wikipedia")) {
}