Java 前两个数字的charAt循环不能循环
此部分不起作用:Java 前两个数字的charAt循环不能循环,java,string,char,Java,String,Char,此部分不起作用: import cs1.Keyboard; public class charAT { public static void main(String[] args) { String s; //The telephone number should be 79575757 System.out.println("Enter your telephone number"); s = Keyboard.rea
import cs1.Keyboard;
public class charAT {
public static void main(String[] args) {
String s;
//The telephone number should be 79575757
System.out.println("Enter your telephone number");
s = Keyboard.readString();
int index1 = s.charAt(0);
我做错了什么?您的第一个问题是将index1与整数值7进行比较。换成
if((char)index1 == 7){
System.out.println("The second number is "+(char)index1);
}
else {
System.out.println("This number is invalid");
}
}
}
接下来,我假设你想得到第二个数字,而不是再次显示相同的数字,所以
char index1 = s.charAt(0);
if(index1 == '7'){
首先,charAt()方法返回char
,因此您的代码应该如下所示:
index1 = s.charAt(1); //get the second character
System.out.println("The second number is "+ index1);
}
if (ch == '7') {
我将变量名从index1
更改为ch
。charAt()方法返回指定位置的char
,而不是索引
其次,您应该比较字符
:
char ch = s.charAt(0);
最后,您可以像这样连接字符串
和字符
:
index1 = s.charAt(1); //get the second character
System.out.println("The second number is "+ index1);
}
if (ch == '7') {
本例中没有循环。您的问题完全不清楚,请描述您试图对代码执行的操作,最好描述您认为编写的代码的预期行为,以及与实际情况不匹配的地方。此外,您的代码还包含几个基本错误。您可能想先深入了解一些关于java基础知识的教程!方法String.charAt(int)返回一个字符。将它存储在int中,然后再将其转换为char,这毫无意义。我知道。只是尽量保持代码的一致性。但我将编辑为使用
char
,因为它确实更有意义。