gpt4 book ai didi

java - 如何制作字符数组扫描仪?

转载 作者:行者123 更新时间:2023-11-30 06:49:38 26 4
gpt4 key购买 nike

比如如何让用户可以输入 char 数组的值?

这是我尝试实现的尝试,但出现语法错误:

    char [] bacteriaStrand = new char[9];
String bacteria = bac.next();
bacteriaStrand = bacteria;

这是迄今为止我的全部代码:

import java.util.Scanner;
public class SodiknBrukDNAAnalysispt3v1
{
public static void main(String[] args)
{
Scanner bac = new Scanner(System.in);
char [] treatmentStrand = {'T','C','G','A','G','A','G','T','A','T','C','C','C','A','G'};
char [] bacteriaStrand = new char[9];
char [] splicedStrand = new char[treatmentStrand.length + bacteriaStrand.length];
System.out.println("NIH Treatment Splicer v. 1");
System.out.println(" ");
System.out.print("Treatment Strand: ");
for (int t = 0; t < treatmentStrand.length; t++)
{
System.out.print(treatmentStrand[t]);
}
System.out.println(" ");
System.out.print("Bacterium Strand: ");
String bacteria = bac.next();
bacteriaStrand = bacteria;
for (int b = 0; b < bacteriaStrand.length; b++)
{
System.out.print(bacteriaStrand[b]);
if (bacteriaStrand[b] != 'A' || bacteriaStrand[b] !='C' || bacteriaStrand[b] !='T' || bacteriaStrand[b] !='G')
{
System.out.println("Error! You can only input capital A, C, T, and G.");
}
}
}
}

最佳答案

如果您想要一个 char[](基元),您可以使用返回 char[] 的方法。

源代码:

public static char[] toCharArray(String input){
StringTokenizer stringTokenizer = new StringTokenizer(input, " ");
char[] chars = new char[stringTokenizer.countTokens()];

for (int i = 0; i < chars.length; i++)
chars[i] = stringTokenizer.nextToken().charAt(0);

return chars;
}

实现:

char[] bacteriaStrand = toCharArray(bacteria);

- 或 -

如果您的字符串未分隔:

*已编辑*

That second example can be easily implemented by just calling String#toCharArray(), which returns a copy of the characters in the string. – Obicere

String string = "STRING";
char[] chars = string.toCharArray();

谢谢

关于java - 如何制作字符数组扫描仪?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43079880/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com