我知道如何对整数进行排序以及如何将字符转换为ASCII码但我在如何将它们组合在一起时遇到了一些麻烦。
基本上我有这个代码将String转换为ASCII。但是我想在打印之后或打印之前使用选择排序。你知道吗?
public static void main (String [] args)throws IOException{
BufferedReader input = new BufferedReader (new InputStreamReader (System.in));
System.out.println("Enter Full Name: ");
String str = input.readLine();
for (int i = 0; i < str.length(); i++){
char c = str.charAt(i);
int k = (int) c;
System.out.println(c + " = " + k);
}
}
}
答案 0 :(得分:1)
我已经解决了你的问题。我已经更新了您的源代码,它正如您所期望的那样工作。 请注意几点:
只需复制粘贴此代码即可。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class StackOverflow {
public static void main(String[] args) throws IOException {
BufferedReader input = new BufferedReader (new InputStreamReader (System.in));
System.out.println("Enter Full Name: ");
String str = input.readLine();
int[] array = new int[str.length()];;
for (int i = 0; i < str.length(); i++){
char c = str.charAt(i);
int k = (int) c;
array[i] = k;
}
System.out.println("Before Selection Sort");
for(int i:array){
System.out.print(i+" ");
}
System.out.println();
selectionSort(array);//sorting array using selection sort
System.out.println("After Selection Sort");
for(int i:array){
System.out.print(i+" ");
}
}
public static void selectionSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++){
if (arr[j] < arr[index]){
index = j;//searching for lowest index
}
}
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
}
}
&#13;
输出中:
输入全名:
拉梅什
选择前排序
114 97 109 101 115 104
选择后排序
97 101 104 109 114 115
答案 1 :(得分:0)
尝试将k值存储在与字符串长度相同的整数数组中。 然后对其应用选择排序。
像:
public static void main (String [] args)throws IOException{
BufferedReader input = new BufferedReader (new InputStreamReader (System.in));
System.out.println("Enter Full Name: ");
String str = input.readLine();
int[] str_ascii = new int[str.length()];
for (int i = 0; i < str.length(); i++){
char c = str.charAt(i);
int k = (int) c;
str_ascii[i] = k;
System.out.println(c + " = " + k);
}
//now selection sort the array str_ascii
}
}