java - 在多维数组中设置一个数字等于一个单词
问题描述
目前正在为Tomasulo's Algorithm
. 我试图从multidimensional
数组中取出一个数字,将其设置为一个单词。
这是从如下所示的文本文件中读取的:
10
7
0 2 2 1
0 3 3 2
0 4 2 3
2 5 2 4
2 6 3 5
3 7 3 4
前两行被绕过用于其他事情,但之后我希望将每行的第一个数字设置为一个单词,例如'0'
to 'add'
、'1'
to 'sub'
、'2'
to'mult'
和'3'
to'div'
我该怎么做?
int IntQue[][] = new int[10][4];
Scanner scanInt = new Scanner(file);
n = 0; // for the number of instructions
displayCycle = 0; // cycle to be displayed
if (scanInt.hasNext()) {
n = scanInt.nextInt(); // number of instructions taken from file
displayCycle = scanInt.nextInt(); // cycle number taken from file
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < 4; j++) {
IntQue[i][j] = scanInt.nextInt();
}
}
解决方案
我可能会使用 switch 语句来处理这个问题,因为你只处理最多 10 个可能的结果 (0-9)。在每种情况下,我都会将转换后的值存储在一个单独的字符串数组中,该数组可以按文件中的行数进行索引。以下程序应该处理所有事情,包括存储尾随数字:
更新:这个程序实际上与其他提交的程序非常相似,但应该回答整个问题
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class TomasuloAlgorithimDriver {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("C:/PathToFile/File.txt");
Scanner scanInt = new Scanner(file);
String line = "";
int cycle = 0;
//Initializations are specific to your example
String[] convertedFirstNums = new String[6];
int[][] nums = new int[8][3];
while (scanInt.hasNextLine()) {
line = scanInt.nextLine();
cycle++;
if(cycle > 2) {//Only executes after first two lines are parsed
//Grab first integer for conversion
String firstNum = "" + line.toCharArray()[0];
convertedFirstNums[cycle-3] = switchInteger(Integer.parseInt(firstNum));
//Parse the rest of the line, ignoring the first integer
int ind = 0;
for(char c : line.substring(1).toCharArray()) {
switch(c) {
case ' ': //Skip all spaces in the line
break;
default: //Take following integers and saves them to num array
String num = "" + c;
nums[cycle-1][ind] = Integer.parseInt(num);
ind++;
break;
}
}
} else {
//Pick up first two lines
nums[cycle-1][0] = Integer.parseInt(line);
}
}
scanInt.close();
for(int i=0; i < nums.length; i++) {
if(i < 2) //Print first two numbers from first two lines
System.out.printf("%d\n", nums[i][0]);
else {
System.out.print(convertedFirstNums[i-2] + " : ");
for(int j=0; j < nums[i].length; j++) {
System.out.printf("%d ", nums[i][j]);
}
System.out.println();
}
}
}
public static String switchInteger(int i) {
switch(i) {
case 0: return "add ";
case 1: return "sub ";
case 2: return "mult";
case 3: return "div ";
}
return "err ";
}
}
推荐阅读
- xamarin - 一次只有一个扩展器以 xamarin 形式扩展
- r - 为什么在实例化 R 变量名称时使用点表示法?
- spring-boot - Spring Boot 微服务和 lsyncd 文件确认
- xml - 使用其他来源的数据填充 XML 的免费解决方案
- django - 这个url路径是什么意思?
- html - WeasyPrint:在 PDF 中包含任意复杂的页眉和页脚
- microservices - 微服务之间的循环依赖是一种反模式吗?
- google-sheets - 在谷歌表中记录数据更改的问题
- python - xlwings:当第一个单元格为空时,如何读取所有值?
- python - 我无法将 pdf 文件发布到在 docker 容器中运行的烧瓶 api