[英]facing problem in loop while solving this code in java
我在 java 中使用 while 循環時遇到問題。 我已經搜索了很多。 但無法解決它。 特別使用 and 運算符,自減運算符。
其實我想在java中做同樣的代碼。 但是在java中我不能在這些條件下使用while循環。
int dataSet;
scanf ("%d", &dataSet);
while ( dataSet-- ) {
char a;
int result = 0;
while ( scanf ("%c", &a) && a != 'X' ) {
result += function (a);
}
printf ("%d\n", result);
}
return 0;
我正在編輯我的答案。 看起來您指向代碼的內部 while 循環。
新編輯:您無法在 Java 中實現純scanf功能。 讀取要么通過運行參數,要么通過文件。
所以你可以把期望的字符放在某個文件中,然后一個一個地讀取它們。 我將與您分享一個類似的片段。 希望有幫助!
Scanner sc = new Scanner(new File("input.txt")); // to read file
int dataSet = 10;
while(dataSet-- >0) {
String a=""; // using String here for storing letters
int result = 0;
while(!a.equals("X")) {
a = sc.next();
result += function(a);
}
System.out.println(result);
}
舊編輯:如果只有當條件讓你感到困擾時
試試這個“==”運算符
Java 不將 0 理解為false
while ( dataSet-- != 0 )
這是代碼...
converter1 c1=new converter1();
Scanner s1 = new Scanner(System.in);
int data;
data=s1.nextInt();
while(data-- != 0){
char a=0;
int sum=0;
do {
a = s1.next().charAt(0);
sum += c1.function(a);
} while( a != 'X');
System.out.println(sum);
但是對於輸出輸入,它需要像這樣的字符之間有空格......(ABCX)......
沒有這樣的空格....( ABCX ) 它不會給出輸出。
為了避免輸入中出現空格,您可以讀取整個輸入,然后進一步解析以獲取單個輸入
Scanner sc = new Scanner(System.in);
String inputCollective = sc.next();
char[] inputArray = inputCollective.toCharArray();
for (char ch: inputArray) {
int number = Integer.parseInt(ch+"");
System.out.println(number);
}
PS:代碼看起來是修復類型的! ..但如果有幫助那就太好了:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.