我在工作中遇到了這個小問題,並想看看我是否可以編寫一個小程序來解決它。顯然,我不能在java中寫一個該死的東西。哈哈我卡住了,但有一部分解決了。我花了兩天的好時間試圖讓它工作,沒有運氣。這是我的問題。我有一個txt文件,每行生成1-1000個數字。我想計算我的做法多少次或9這個數字1 & 1000之間的頻率如下:1和1000之間的數字頻率或9的數量 - Java
- 從文本文件中讀取數字和int數組中把它們粘。
- 將工作號碼或數組中的點[0]轉換爲字符串 選擇一條路線。
3-A。與charAt(0)進行比較,並且如果適當,則增量爲012-D4-將字符串轉換爲char數組,並將char數組中的索引0與9進行比較,並在適當的情況下進行增量。
邊注意:如果比較charArray [1] =='9'來編譯它,你必須註釋掉else。如果你評論這一點,它將完美地用於計算第一位數字中的9。第二和第三位數字比較不起作用。謝謝你,對於愚蠢的問題感到抱歉。
生成文本文件的一種簡單方法是在列1中使用Excel類型,然後在第二行中使用2,然後在第三行中使用3(同一個單元格),然後高亮顯示所有三個數字並將加號包含三個單元的單元格的右下角。這將填充到1000.我不附加我的txt文件,因爲你可以很容易地生成你自己的。
**不做作業
到目前爲止我的代碼如下:
package com.numbers;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class Numbers
{
static int[] array = new int[1002];
static char[] charArray = new char[4];
public static void main(String[] args) throws FileNotFoundException
{
Scanner scan = new Scanner (System.in);
System.out.print("Enter the name of the file : ");
String whatfile = scan.nextLine();
Scanner readnumber = new Scanner (new FileReader(whatfile));
int firstDigit = 0;
int secondDigit = 0;
int thirdDigit = 0;
for (int i = 0; i < 1000; i++)
{
array[i] = readnumber.nextInt();
String testString = "";
// System.out.println("the number being passed to parse is : " + numberAtIndex);
// Approach 1
testString = Integer.toString(array[i]);
if(testString.charAt(0) == '9')
{
firstDigit = firstDigit + 1;
}
// System.out.println("test string contains : " + testString);
// Approach 2
charArray = testString.toCharArray();
if(charArray[0] == '9')
{
firstDigit = firstDigit + 1;
}
/*
* If you comment out this 'else if' it will work. please comment out one of the approaches above (use only 1) My problem is that
* I can't seem to figure out how to search for nines in the second & third digit location.
* If it is in an array shouldn't I be able to compare the charArray[1] to a nine and have it increment if true?
*/
else if (charArray[1] == '9')
{
secondDigit = secondDigit + 1;
}
} // end for
// System.out.println("this is what is stored in array spot 0 : " + array[0]); //should be 1
System.out.println("the number of 9's in the first digit place holder is : " + firstDigit);
System.out.println("the number of 9's in the second digit place holder is : " + secondDigit);
// System.out.println("the number of 9's in the third digit place holder is : " + thirdDigit);
} // End of main
} // end of class
那麼究竟什麼是錯在這裏?什麼不適合你? – brc
你想檢查數字列表中數字9的出現次數嗎? – galchen
您的描述是關於計算9的數量,但您的代碼似乎試圖分別跟蹤每列中有多少個9 - 這是什麼?你爲什麼要把這些數字放在一個文本文件中?你不能只是有一個for循環來生成數字嗎?並且,假設您已經使用了文本文件計劃,那麼您爲什麼會在假設具有特定長度的文本文件的for循環中讀取它們?爲什麼不使用while循環,所以你可以用任何一組數字來提供它_any_文本文件?爲什麼當你不回頭引用它們時,你很難將每個數字存儲在一個數組中? – nnnnnn