【发布时间】:2020-11-23 19:11:27
【问题描述】:
没有分隔符,字符串本身来自格式如下的文件:
BB
GB
GB
背景
GG
GB
GB
GB
GB
GG
使用下面的代码后,我留下了 BBGBGBBGGGGBGBGBGBGG,从token = in.nextLine( ) 之后的打印语句中打印出来;我对这个程序的目标是将每 2 个字符分配给它们的变量并递增它们以获得计数。我只是不知道如何正确地增加和分配它们。任何帮助表示赞赏。
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class Family
{
public static void main (String args[]) throws IOException {
//variables defined
int numGB = 0;
int numBG = 0;
int numGG = 0;
int numBB = 0;
int totalNum = 0;
double probBG;
double probGG;
double probBB;
String token ="";
int spaceDeleter = 0;
int token2Sub = 0;
File fileName = new File ("test1.txt");
Scanner in = new Scanner(fileName); //scans file
System.out.println("Composition statistics for families with two children");
while(in.hasNextLine())
{
token = in.nextLine( ); //recives token from scanner
System.out.print(token);
if(token.equals("GB"))
{
numGB = numGB + 1;
}
else if(token.equals("BG"))
{
numBG = numBG + 1;
}
else if(token.equals("GG"))
{
numGG = numGG + 1;
}
else if(token.equals("BB"))
{
numBB = numBB + 1;
}
else if(token.equals(""))
{
spaceDeleter =+ 1; //tried to delete space to no avial
}
else
{
System.out.println("Data reading error");
}
}
【问题讨论】:
-
您是什么意思“将每 2 个字符 分配给它们的变量”?
-
你可能想看看
String.substring() -
@Spectric 例如 numBG 需要在字符串中每次出现“BG”时增加 1
-
@RIVERMAN2010 谢谢,我用了 token = token.substring(0);在每个循环之后
标签: java string printing delimiter next