如何使数组的长度等于字符串的长度?



我希望你能理解我的观点。

  • isoddeven函数中,我根据变量n的长度是奇数还是偶数来计数字母或数字/特殊符号的数量。然后取count变量

    并返回它的值,这样我就可以使用它作为字符数组的长度。

当我运行我的代码时,它显示的总数超过了实际计数的总数(它加倍)。我不能在这部分使用后悔,它需要一个循环计数。

真的需要一些建议,我应该添加什么。或者我的代码实际上有什么问题?

我想要的输出:

enter a string :
rain!21
length is odd, there are 3 non-alphabetic characters in the string
enter 3 strings in the array
**********

我得到的输出:

enter a string :
joy!@u77
length is even, there are 4 aplabetic characters in the string
**********
enter 8 strings in the array
**********
下面是我的代码:
import java.io.*;
public class Stringarray {
BufferedReader input = new BufferedReader (new InputStreamReader (System.in));
String n;
String arr[] = new String [4];
int c = 0, c2 = 0, i;
char ch;

public static void main (String args[]) throws IOException {
Stringarray obj = new Stringarray ();

obj.Constructor ();
obj.stringInput ();
obj.IsOddEven ();
obj.createArray ();
obj.replaceDigit ();
}//main

public void Constructor () {
System.out.println("your name and section here ");
}//constructor

public int stringInput () throws IOException {
System.out.println("enter a string :");
n = input.readLine();
return n.length();
}//stringInput

public int IsOddEven () {
if (n.length() % 2 == 0) {
for ( i = 0; i<n.length(); i++){
ch = n.charAt(i);
if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' ){
c++;//letters
}
}
System.out.println("length is even, there are " + c + " aplabetic characters in the string");
}
else {
for (i = 0; i<n.length(); i++){
if (ch >= '0' && ch <= '9'){
c++;//digits
}
else {
c2++;//special characters
}
}
System.out.println("length is odd, there are " + c+c2 + " non-alphabetic characters in the string");
}
int x = c + c2;
System.out.println("**********");
return x;
}//IsOddEven

public void createArray() throws IOException {
System.out.println("enter " + n.length() +" strings in the arrayn**********");
for (int i = 0; i<n.length(); i++){
n = input.readLine();
arr[i] = n;
}
System.out.println("**********");
}//createArray

public void replaceDigit () {
System.out.println("all digits in the array are replaced with #");
for (int i = 0; i<arr.length; i++){
arr[i] = arr[i].replaceAll("[^a-zA-Z!]", "#");
System.out.println(arr[i]);
}
}//replaceDigit

}

你的代码是一个很好的例子,一个sphagetti代码,有太多的问题,列出他们所有。我建议你读一读《Clean Code》——它肯定会帮助你提高你的编码技能。

关于最初的问题,看看你的方法createArray。它使用n.length()代替你的计数器,即输入线的长度。我想这并不是你真正想要的。

您的错误是在System.out.println("enter " + n.length() +" strings in the arrayn**********");。您正在使用n.length()来确定它应该添加多少,因此在joy!@u77的情况下,长度为8,将其套管为数组添加8。从你的代码来看,我认为你会想做"enter " + x +" strings...。不确定是否将其存储在x中,但问题在于n.length()

相关内容

最新更新