Java 循环读取字符
我想在循环中读取char变量Java 循环读取字符,java,loops,char,system.in,Java,Loops,Char,System.in,我想在循环中读取char变量a,并在循环的每一步将变量k递增一 以下是java代码: public class Hello { public static void main(String arg[]) throws IOException { int k, i; char a; k=0; for (i=0; i<=3; i++) { k++; a=(char) System.in.read(); System.out
a
,并在循环的每一步将变量k
递增一
以下是java代码:
public class Hello {
public static void main(String arg[]) throws IOException {
int k, i;
char a;
k=0;
for (i=0; i<=3; i++) {
k++;
a=(char) System.in.read();
System.out.println(k);
}
}
}
我需要这个结果:
A //variable a
1
2
3
B //variable a
4
a //variable a
1
c //variable a
2
b //variable a
3
y //variable a
4
也许我需要一些其他方法来读取循环中的字符(不是SYSTEM.in.read()),但我对java是新手 试试这个:
static Scanner keyboard = new Scanner(System.in);
public static void main (String args[]) {
int k = 0;
String a;
while(true){
a = keyboard.nextLine();
k++;
System.out.println(k);
}
}
试试这个:
static Scanner keyboard = new Scanner(System.in);
public static void main (String args[]) {
int k = 0;
String a;
while(true){
a = keyboard.nextLine();
k++;
System.out.println(k);
}
}
您可以使用
Scanner
类,该类更可预测地使用输入:
public static void main(String arg[]) throws IOException {
int k, i;
char a;
k = 0;
Scanner in = new Scanner(System.in);
for (i = 0; i <= 3; i++) {
k++;
a = in.next().charAt(0);
System.out.println(k);
}
}
publicstaticvoidmain(字符串arg[])引发IOException{
int k,i;
字符a;
k=0;
扫描仪输入=新扫描仪(系统输入);
对于(i=0;i您可以使用Scanner
类,该类更可预测地使用输入:
public static void main(String arg[]) throws IOException {
int k, i;
char a;
k = 0;
Scanner in = new Scanner(System.in);
for (i = 0; i <= 3; i++) {
k++;
a = in.next().charAt(0);
System.out.println(k);
}
}
publicstaticvoidmain(字符串arg[])引发IOException{
int k,i;
字符a;
k=0;
扫描仪输入=新扫描仪(系统输入);
对于(i=0;ipublicstaticvoidmain(字符串args[]){
int charCount=0;
扫描仪sc=新的扫描仪(System.in);
while(sc.hasNext()&&charCount++publicstaticvoidmain(字符串args[])){
int charCount=0;
扫描仪sc=新的扫描仪(System.in);
虽然(sc.hasNext()&&charCount++您仍然可以使用System.in.read
方法,但在引入第一个字符后,无需按enter
:
我认为上面的答案解决了您的问题。但是,我想向您解释一下为什么会发生这种情况:您可能编写A
并按enter
。程序读取A
和enter
,这是两个字符:\r\n
-因此,for循环在第一次迭代A
,在第二次\r\n和在第三个\n…中,您仍然可以使用System.in.read
方法-但在引入第一个字符后,不必按enter
:
我认为上面的答案解决了您的问题。但是,我想向您解释一下为什么会发生这种情况:您可能编写A
并按enter
。程序读取A
和enter
,这是两个字符:\r\n
-因此,for循环在第一次迭代A
,在第二次\r\n和在第三个\n…不清楚你在问什么,你不想使用System.int.read()
?不清楚你在问什么,你不想使用System.int.read()
?为什么有.charAt(0)
?检查修改后的答案。感谢您选择它。您也可以对其进行投票,也可以对您认为有用的其他答案进行投票。:-)没问题。我对其他答案以及您的答案进行投票,以帮助您建立声誉。继续做好工作!:-)为什么会有。charAt(0)
?检查修改后的答案。感谢您的选择。您也可以对其进行更新投票,也可以对您认为有用的其他答案进行更新投票。:-)没问题。我对其他答案以及您的答案进行了更新投票,以帮助您建立声誉。继续做好工作!:-)