我很好奇是否有一种简单的方法可以将输入到下面程序中的int或数字转换为字母或字符,而无需进行大的更改或重写程序。这就是我所拥有的:
import java.util.Scanner;
public class SLP4 {
public int find(final int[] data, final int key) {
for (int i = 0; i < data.length; ++i) {
if (data[i] > key)
return -1;
else if (data[i] == key)
return i;
}
return -1;
}
public static void main(String[] args) {
final int arr[] = new int[10];
System.out.println("Enter 10 numbers");
Scanner input = new Scanner(System.in);
for (int i = 0; i < arr.length; i++) {
arr[i] = input.nextInt();
}
SLP4 search = new SLP4();
System.out.print("Enter the number to find its place: ");
int num = input.nextInt();
int n = search.find(arr, num);
if ((n >= 0) && (n < arr.length)) {
System.out.println("Found at element: " + n);
} else {
System.out.println("Not Found");
}
}
}
答案 0 :(得分:0)
您可以将int
与空String
:
int numberVar = 0; //example value
String convertedInt = "" + numberVar;
这会将数字变成String
。要扭转,您需要做的就是
int shortcut = Integer.parseInt(convertedInt, 10); //shortcut == numberVar
我已将您的问题解释为想要将int
转换为String
,但您确实使用了字词,因此可以进行更多解释。
答案 1 :(得分:0)
将您的find
方法更改为
public int find(final char[] data, final char key) {
for (int i = 0; i < data.length; ++i) {
if (data[i] == key)
return i;
}
return -1;
}
输入为
final char arr[] = new char[10];
System.out.println("Enter 10 chars");
Scanner input = new Scanner(System.in);
for (int i = 0; i < arr.length; i++) {
arr[i] = ((String) input.next()).charAt(0);
}
System.out.print("Enter the number to find its place: ");
char num=((String) input.next()).charAt(0);
int n = search.find(arr, num);
if ((n >= 0) && (n < arr.length)) {
System.out.println("Found at element: " + n);
} else {
System.out.println("Not Found");
}
修改强>
假设输入每个字符后输入<{1}}