【发布时间】:2016-05-06 11:03:41
【问题描述】:
我正在尝试运行模拟器,但有几个问题,主要是....
- 代码没有在程序结束时打印出值
- 代码实际上并没有创建文件
-我很累,所以请原谅我犯的任何愚蠢的错误或我遗漏的细节。
我已经搜索了这个网站,我找到了这个
What is the simplest way to write a text file in java
和
how to write to text file outside of netbeans
我以为我可以编辑第一个链接中的代码为我工作,但这不起作用(你在这里看到的就是这个)
第二页看起来更简单,但没有周围的代码,所以我不确定上下文是什么以及我将如何实现它
import java.util.Random;
import java.util.Scanner;
import java.io.*;
/*
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
*/
public class SimClass {
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in) ;
Random randomNumbers = new Random();
//create object from random class
//create self explanaroty input parameters
int pkt_in_q = 0 ;
int pkt_dropped = 0;
int input ;
int output ;
int buffer ;
int x ;
double y ;
//ask for values for buffer size. input rate, output rate
y = randomNumbers.nextDouble();
//attempt to assign a random number to the variable and
/*here you should get user input.
buffer size, # of repitions , if
*/
//fix this
System.out.print("Enter an integer for the input rate ");
input = keyboard.nextInt();
System.out.print("Enter an integer for the output rate ");
output = keyboard.nextInt();
System.out.print("What is the buffer size ");
buffer = keyboard.nextInt();
for (x = 1000000; x >=0 ; x--)
{ /*
simulate # of packets dropped/in the que,
create file, write results to file, output results,
*/
if (y > input/(output/buffer))
{
if (pkt_in_q < buffer)
{
pkt_in_q++ ;
}
else
{
pkt_dropped++ ;
}
//if statement should terminate here
}
else
if (pkt_in_q > 0)
{
pkt_in_q -- ;
}
}
/*
create file, write results to file, output results,
*/
try { /*this seeems to be the problem, the program is either not doing
anything with this or not making the results visible
*/
String content =( " pkt_in_q is " + pkt_in_q +
"pkt_dropped is " + pkt_dropped);
File file = new File("C:/Temp/inputFile.txt");
// if file doesnt exists, then create it
if (!file.exists())
{
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
try (BufferedWriter bw = new BufferedWriter(fw))
{
bw.write(content);
bw.close();
}
System.out.println("packets dropped value is = " +
pkt_dropped + "packets in q value is = " + pkt_in_q);
}
catch (IOException e)
{
//e.printStackTrace();
}
}
}
【问题讨论】:
-
您是否尝试过调试您的代码?这比发布到 Stack Overflow 恕我直言更有帮助。
-
为什么要抑制异常?他们会告诉你出了什么问题。
-
蒂姆我正在使用netbeans并且代码没有抛出任何错误,“运行”按钮旁边的“调试”选项也是灰色的,表明代码没有错误并且我的错误是合乎逻辑的或组织。 Takeshi,我不确定你指的是什么。请详细说明。我会说我对代码有大约 80% 的理解。多于。就像我说的那样,我从其他地方复制了代码。
-
你需要了解代码中的try、catch、异常和cmets。 e.printStackTrace() 将显示您遇到的错误,但您正在捕获异常并且不显示任何内容。 e.printStackTrace 被注释掉。
标签: java read-write