Java..Array required, but string found [duplicate] - java

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));

Related

Referencing a variable using a string of the same name in Java? [duplicate]

This question already has answers here:
Accessing the value of a variable by its name as string in Java
(2 answers)
Different between parseInt() and valueOf() in java?
(11 answers)
Closed last month.
In Java, let's say I have...
let hello = 10;
Is it possible to retrieve hello's value (10) using the string reference 'hello'?
Something like valueOf(....'hello'....) = 10
This is how you can retrive in Java. Also let is used in JavaScript not in Java.
public class Test {
public static void main(String[] args) {
String hello = "10";
int helloNum = Integer.valueOf(hello); //converting String "10" into int 10
int num = 10;
String numString = String.valueOf(num);//converting int 10 to string "10"
}
}

Wrong output- Converting Java String to Array. Numbers are correct before inserting into array? [duplicate]

This question already has answers here:
Java: parse int value from a char
(9 answers)
How can I convert a char to int in Java? [duplicate]
(4 answers)
Closed 2 years ago.
I have this problem where I need to create a method that takes in a String and creates an integer array of each character. I have checked each step of the for loop and the array before and after the loop, and I am lost.
It correctly shows each character as '3' '4' and '5', however once it is inserted into the array, it always prints [51, 52, 53]. I am so lost where those numbers even came from? Thanks so much...
public class CodingBat {
public static void main(String[] args) {
String text = "345";
int[] create = new int[text.length()];
for(int i = 0; i < text.length(); i++) {
System.out.printf("Current array: %s\n", Arrays.toString(create));
//System.out.println(text.charAt(i));
create[i] = text.charAt(i);
System.out.printf("Adding %c\n", text.charAt(i));
}
System.out.println(Arrays.toString(create));
}
}
You're inserting a char into a int array, if i remember, the numbers that you see printing the array are the ASCII code.
So, if you want to get the number, use:
create[i] = Character.getNumericValue(text.charAt(i))

Convert int to String [duplicate]

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.

Searching for a String in a String array [duplicate]

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")) {
}

How to create String of length consisting of same character repeated multiple times? [duplicate]

This question already has answers here:
Simple way to repeat a string
(32 answers)
Create a string with n characters
(27 answers)
Closed 9 years ago.
If i want a String s which would consist of n instances of character A, can this be done cleaner in Java other then
public static String stringOfSize(int size, char ch) {
StringBuilder s = new StringBuilder();
while (size-- > 0) {
s.append(ch);
}
return s.toString();
}
Can we do better? Just wondering.
Nothing wrong with this code at all... But maybe you can use Arrays.fill():
public static String stringOfSize(int size, char ch)
{
final char[] array = new char[size];
Arrays.fill(array, ch);
return new String(array);
}
You could do the following:
return StringUtils.repeat(ch, size);
Note: StringUtils is not built-in to the JDK - see http://commons.apache.org/proper/commons-lang/

Categories

Resources