gpt4 book ai didi

java - for循环只读取最后一个值

转载 作者:太空宇宙 更新时间:2023-11-04 06:13:30 25 4
gpt4 key购买 nike

我的程序中有一个错误,使我的循环仅读取输入字符串的最后一部分。我希望程序计算字符串中每个字符的数量。我不希望答案告诉我如何更有效地存储这些值,而不需要将所有内容重复 26 次。请回答我在这里提出的问题。抱歉,如果这是重复的!我只是不知道要指定什么,因为没有明显的错误。

import java.util.Scanner;

public class stringprogram {
public static void stringinputmethod()
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a String");
String strs = scan.nextLine();

int numa = 0;
int numb = 0;
int numc = 0;
int numd = 0;
int nume = 0;
int numf = 0;
int numg = 0;
int numh = 0;
int numi = 0;
int numj = 0;
int numk = 0;
int numl = 0;
int numm = 0;
int numn = 0;
int numo = 0;
int nump = 0;
int numq = 0;
int numr = 0;
int nums = 0;
int numt = 0;
int numu = 0;
int numv = 0;
int numw = 0;
int numx = 0;
int numy = 0;
int numz = 0;

String randaf;

for(int i=0; i<=strs.length();i++)
{
randaf = strs.substring(i);

if(randaf.equals("a"))
{
numa = numa + 1;
}
else if(randaf.equals("b"))
{
numb = numb + 1;
}
else if(randaf.equals("c"))
{
numc = numc + 1;
}
else if(randaf.equals("d"))
{
numd = numd + 1;
}
else if(randaf.equals("e"))
{
nume = nume + 1;
}
else if(randaf.equals("f"))
{
numf = numf + 1;
}
else if(randaf.equals("g"))
{
numg = numg + 1;
}
else if(randaf.equals("h"))
{
numh = numh + 1;
}
else if(randaf.equals("i"))
{
numi = numi + 1;
}
else if(randaf.equals("j"))
{
numj = numj + 1;
}
else if(randaf.equals("k"))
{
numk = numk + 1;
}
else if(randaf.equals("l"))
{
numl = numl + 1;
}
else if(randaf.equals("m"))
{
numm = numm + 1;
}
else if(randaf.equals("n"))
{
numn = numn + 1;
}
else if(randaf.equals("o"))
{
numo = numo + 1;
}
else if(randaf.equals("p"))
{
nump = nump + 1;
}
else if(randaf.equals("q"))
{
numq = numq + 1;
}
else if(randaf.equals("r"))
{
numr = numr + 1;
}
else if(randaf.equals("s"))
{
nums = nums + 1;
}
else if(randaf.equals("t"))
{
numt = numt + 1;
}
else if(randaf.equals("u"))
{
numu = numu + 1;
}
else if(randaf.equals("v"))
{
numv = numv + 1;
}
else if(randaf.equals("w"))
{
numw = numw + 1;
}
else if(randaf.equals("x"))
{
numx = numx + 1;
}
else if(randaf.equals("y"))
{
numy = numy + 1;
}
else if(randaf.equals("z"))
{
numz = numz + 1;
}
}
System.out.println("a: "+numa +"\nb: "+ numb +"\nc: "+ numc +"\nd: "+ numd +"\ne: "+ nume +"\nf: "+ numf +"\ng: "+ numg +"\nh: "+ numh +"\ni: "+ numi +"\nj: "+ numj +"\nk: "+ numk +"\nl: "+ numl +"\nm: "+ numm +"\nn: "+ numn +"\no: "+ numo +"\np: "+ nump +"\nq: "+ numq +"\nr: "+ numr +"\ns: "+ nums +"\nt: "+ numt +"\nu: "+ numu +"\nv: "+ numv +"\nw: "+ numw +"\nx: "+ numx +"\ny: "+ numy +"\nz: "+ numz);
}

public static void main(String[] args)
{
stringinputmethod();
}
}

最佳答案

substring 方法将从指定的索引到字符串末尾返回一个新字符串。您想要的是 String.charAt(index) 它将返回指定位置的字符

关于java - for循环只读取最后一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28397780/

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