[英]How to get the length of the array equal to the length of a string?
我希望我能在这件事上表达我的观点。
在isoddeven
function 中,我根据变量 n 的长度是奇数还是偶数来计算字母或数字/特殊符号的数量。 然后我取 count 变量。
并返回它的值,以便我可以将它用作 char 数组的长度。
当我运行我的代码时,它显示的总数超过了实际计数的总数(它加倍)。 我不能在这部分使用正则表达式,它需要是一个重要的循环。
真的需要一些我应该添加的建议。 或者我的代码有什么问题吗?
这是我想要的 output:
enter a string :
rain!21
length is odd, there are 3 non-alphabetic characters in the string
enter 3 strings in the array
**********
我得到的 output 是:
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 array\n**********");
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 代码的一个很好的示例,并且有太多问题无法全部列出。 我建议您阅读“清洁代码”——它肯定会帮助您提高编码技能。
关于原始问题,请查看您的方法createArray
。 它使用n.length()
而不是你的计数器,即输入行的长度。 我认为这不是你真正想要的。
您的错误在System.out.println("enter " + n.length() +" strings in the array\n**********");
. 您正在使用n.length()
来确定它应该添加多少,所以在joy!@u77
长度为 8 将其添加到数组中。 从您的代码来看,我认为您会想要"enter " + x +" strings...
不确定您是否将其存储在x
中,但问题在于n.length()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.