Why is my program not scanning and outputting the text file properly? - netbeans

I'm currently having trouble with my text file. When I run my program, it is supposed to print the students on academic warning, but when I run it, it only prints the header and does not scan the text file. Is this a problem with my Netbeans or with my program?
Here is the program assignment in more detail:
Write a program that will read in a file of student academic credit data and create a list of students on academic
warning. The list of students on warning will be written to a file. Each line of the input file will contain the
student name (a single String with no spaces), the number of semester hours earned (an integer), the total
quality points earned (a double). The following shows part of a typical data file:
Smith 27 83.7
Jones 21 28.35
Walker 96 182.4
Doe 60 150
The program should compute the GPA (grade point or quality point average) for each student (the total quality
points divided by the number of semester hours) then write the student information to the output file if that
student should be put on academic warning. A student will be on warning if he/she has a GPA less than 1.5 for
students with fewer than 30 semester hours credit, 1.75 for students with fewer than 60 semester hours credit,
and 2.0 for all other students. The file Warning.java contains a skeleton of the program. Do the following:
Set up a Scanner object scan from the input file and a PrintWriter outFile to the output file inside the try
clause (see the comments in the program). Note that you’ll have to create the PrintWriter from a FileWriter,
but you can still do it in a single statement.
Inside the while loop add code to read and parse the input—get the name, the number of credit hours, and
the number of quality points. Compute the GPA, determine if the student is on academic warning, and if so
write the name, credit hours, and GPA (separated by spaces) to the output file.
After the loop close the PrintWriter.
Think about the exceptions that could be thrown by this program:
• A FileNotFoundException if the input file does not exist
• A NumberFormatException if it can’t parse an int or double when it tries to - this indicates an error in
the input file format
• An IOException if something else goes wrong with the input or output stream
Add a catch for each of these situations, and in each case give as specific a message as you can. The program
will terminate if any of these exceptions is thrown, but at least you can supply the user with useful information.
Test the program. Test data is in the file students.dat. Be sure to test each of the exceptions as well.
Code:
package Chapter11LabProgram;
import java.util.*;
import java.io.*;
public class Warning
{
// --------------------------------------------------------------------
// Reads student data (name, semester hours, quality points) from a
// text file, computes the GPA, then writes data to another file
// if the student is placed on academic warning.
// --------------------------------------------------------------------
public static void main(String[] args) {
int creditHrs; // number of semester hours earned
double qualityPts; // number of quality points earned
double gpa; // grade point (quality point) average
String line, name, inputName = "/Users/Downloads/students.dat.txt";
String outputName = "/Users/Downloads/students.dat.txt";
try {
// Set up scanner to input file
PrintWriter outFile = new PrintWriter(new FileWriter(outputName));
Scanner scan = new Scanner(new File(inputName));
// Set up the output file stream
// Print a header to the output file
outFile.println();
outFile.println("Students on Academic Warning");
outFile.println();
// Process the input file, one token at a time
while (scan.hasNext()) {
line = scan.nextLine();
creditHrs = Integer.parseInt(line.split("\\s+")[1]);
qualityPts = Double.parseDouble(line.split("\\s+")[2]);
gpa = qualityPts / creditHrs;
//outFile.print(line);
if (gpa < 1.5 && creditHrs < 30)
{
outFile.write(line + "\r\n");
}
else if (gpa < 1.75 && creditHrs < 60)
{
outFile.write(line + "\r\n");
}
else if (gpa < 2)
{
outFile.write(line + "\r\n");
}
//outFile.println ();
// Get the credit hours and quality points and
// determine if the student is on warning. If so,
// write the student data to the output file.
}
//outFile.println ("test");
outFile.close();
} catch (FileNotFoundException exception) {
System.out.println("The file " + inputName + " was not found.");
} catch (IOException exception) {
System.out.println(exception);
} catch (NumberFormatException e) {
System.out.println("Format error in input file: " + e);
}
}
}
My text file:
Smith 27 83.7
Jones 21 28.35
Walker 96 182.4
Doe 60 150
Wood 100 400
Street 33 57.4
Taylor 83 190
Davis 110 198
Smart 75 2 92.5
Bird 84 168
Summers 52 83.2
Any help would be appreciated! Thank you!

Related

How do I calculate the number of ticks per measure from a MIDI file

I am trying to calculate the number of ticks per measure (bar) from a MIDI file, but I am a bit stuck.
I have a MIDI file from which I can extract the following information (provided in meta messages):
#0: Time signature: 4/4, Metronome pulse: 24 MIDI clock ticks per click, Number of 32nd notes per beat: 8
There are two tempo messages, which I'm not sure are relevant:
#0: Microseconds per quarternote: 400000, Beats per minute: 150.0
#1800: Microseconds per quarternote: 441176, Beats per minute: 136.0001450668214
From trial and error, looking at the Note On messages, and looking at the MIDI file in Garageband, I can 'guess' that the number of ticks per measure is 2100, with a quarternote 525 ticks.
My question is: can I arrive at the 2100 number using the tempo information that was provided above, and if so how? Or have I not parsed enough information from the MIDI file and is there some other control message that I need to look at?
Use the following Java 11 code to extract the ticks per measure. This assumes 4 quarter notes per bar.
public MidiFile(String filename) throws Exception {
var file = new File(filename);
var sequence = MidiSystem.getSequence(file);
System.out.println("Tick length: " + sequence.getTickLength());
System.out.println("Division Type: " + sequence.getDivisionType());
System.out.println("Resolution (PPQ if division = " + javax.sound.midi.Sequence.PPQ + "): " + sequence.getResolution());
System.out.println("Ticks per measure: " + (4 * sequence.getResolution()));
}

CLLE SNDRCVF command not allowed

I am trying to compile this piece of CL code using Rational Series but keep getting error.
This is my CL code:
PGM
DCLF FILE(LAB4DF)
SNDRCVF RCDFMT(RECORD1) /* send, recieve file */
DOWHILE (&IN03 = '0')
SELECT
WHEN (&USERINPUT = '1' *OR &USERINPUT = '01') CALLSUBR OPTION1
OTHERWISE DO
*IN03 = '1'
ENDDO
ENDSELECT
ENDDO
SUBR OPTION1
DSPLIBL
ENDSUBR
ENDPGM
And this is my DSPF code
A R RECORD1
A 1 38'LAB 4'
A 3 3'Please select one of the following-
A options:'
A 6 11'3. Maximum Invalid Signon Attempt-
A s allowed'
A 8 11'5. Run Instructor''s Insurance Pr-
A ogram'
A 5 11'2. Signed on User''s Message Queu-
A e'
A 1 3'Yathavan Parameshwaran'
A 7 11'4. Initial number of active jobs -
A for storage allocation'
A 4 11'1. Previous sign on by signed on -
A user'
A 14 11'F3 = Exit'
A 14 31'F21 = Command Line'
A 2 70TIME
A 1 72DATE
A 9 11'Option: '
A USERINPUT 2 B 9 19
A 91 DSPATR(RI)
A 92 DSPATR(PC)
A MSGTXT1 70 O 11 11
A MSGTXT2 70 O 12 11
Is there a problem with my CL code or DSPF code?
You forgot to say what error you were getting. It's always important to put all the information about error messages into your questions.
There are two errors.
&IN03 is not defined
Your assignment to *IN03 should be to &IN03, but that's not how you do an assignment in CLP
If you want to be able to press F3, you have to code something like CA03(03) in the "Functions" for the record format.
To assign a variable in CL, code
CHGVAR name value
Looking at the documentation here, I suspect you need to add RCDFMT to your DCLF spec like so:
DCLF FILE(LAB4DF) RCDFMT(RECORD1)
SNDRCVF RCDFMT(RECORD1) /* send, recieve file */
If you really do only have 1 record format in your display file, then you can also omit the RCDFMT from both commands like so:
DCLF FILE(LAB4DF)
SNDRCVF /* send, recieve file */

Importing two text files to compare as lists sequentially

Student trying to compare two .txt files of string "answers" from a multiple choice test a,c,d,b, etc. I've found some information on different parts of the problems I'm having and found a possible way to get the comparisons I want, but the guide was meant for in script strings and not pulling a list from a file.
For the import of the two files and comparing them, I'm basing my code on my textbook and this video here: Video example
I've got the code up and running, but for some reason I'm only getting 0.0% match when I want to a 100.0% match, at least for the two text files I'm using with identical answer lists.
import difflib
answer_sheet = "TestAnswerList.txt"
student_sheet = "StudentAnswerList.txt"
ans_list = open(answer_sheet).readlines()
stu_list = open(student_sheet).readlines()
sequence = difflib.SequenceMatcher(isjunk=None, a=ans_list, b=stu_list)
check_list = sequence.ratio()*100
check_list = round(check_list,1)
print(str(check_list) + "% match")
if check_list == 100:
print('This grade is Plus Ultra!')
elif check_list >= 75:
print('Good job, you pass!')
else:
print('Please study harder for your next test.')
# not the crux of my issue, but will accept advice all the same
answer_sheet.close
student_sheet.close
If I add in the close statement at the end for both of the text files, then I receive this error:
Traceback (most recent call last): File
"c:/Users/jaret/Documents/Ashford U/CPT 200/Python Code/Wk 5 Int Assg
- Tester code.py", line 18, in
answer_sheet.close AttributeError: 'str' object has no attribute 'close'
I had to re-look at how my files were being opened and realized that the syntax was for Python 2 not 3. I chose to go w/ basic open and later close to reduce any potential errors on my novice part.
import difflib
f1 = open('TestAnswerList.txt')
tst_ans = f1.readlines()
f2 = open('StudentAnswerList.txt')
stu_ans = f2.readlines()
sequence = difflib.SequenceMatcher(isjunk=None, a=stu_ans, b=tst_ans)
check_list = sequence.ratio()*100
check_list = round(check_list,1)
print(str(check_list) + "% match") # Percentage correct
if check_list == 100:
print('This grade is Plus Ultra!')
elif check_list >= 75:
print('Good job, you pass!')
else:
print('Please study harder for your next test.')
# Visual Answer match-up
print('Test Answers: ', tst_ans)
print('Student Answers:', stu_ans)
f1.close()
f2.close()

Can not read more than 32 blocks in a single READ MULTIPLE BLOCKS command from M24LR

I am trying to read multiple blocks (all of them in a single READ MULTIPLE BLOCKS command) from a M24LR chip through NFC-V.
let writeData = new Uint8Array(5);
writeData[0] = 0x0A; // Flags
writeData[1] = 0x23; // Read multiple block
writeData[2] = 0x00; // Address of starting block (first 8bit)
writeData[3] = 0x00; // Address (second 8bit)
writeData[4] = 0x1F; // Numbers of block (0x20 is not working)
nfc.transceive(writeData.buffer)
.then(response => {
console.log('response: ' + response);
})
.catch(error => {
console.log('error transceive: ' + JSON.stringify(error));
});
If I am asking for 32 blocks it works well, if I ask for 33 blocks, the command fails with an error.
Is it something that I am doing wrong? Does the READ MULTIPLE BLOCKS command have a limit?
See the datasheet (M24LR64-R: Dynamic NFC/RFID tag IC with 64-Kbit EEPROM
with I²C bus and ISO 15693 RF interface, DocID15170 Rev 16, section 26.5; the same also applies to M24LR64E-R, M24LR16E-R, and M24LR04E-R):
The maximum number of blocks is fixed at 32 assuming that they are all located in the same sector. If the number of blocks overlaps sectors, the M24LR64-R returns an error code.
Thus, the READ MULTIPLE BLOCKS command for these chips is limited to 32 blocks.

How do I get the per-spec output of a LV-MaxSonar LV-EZ0 rangefinder with Android Things?

I'm using this sensor with a Raspberry Pi B 3 and Android Things 1.0
I have it connected as per these instructions
The spec for its output suggests I should receive "an ASCII capital “R”, followed by three ASCII character digits representing the range in inches up to a maximum of 255, followed by a carriage return (ASCII 13)"
I have connected to the device and configured it as follows (connection parameters map to the "Serial, 0 to Vcc, 9600 Baud, 81N" in that spec, I think):
PeripheralManager manager = PeripheralManager.getInstance();
mDevice = manager.openUartDevice(name);
mDevice.setBaudrate(9600);
mDevice.setDataSize(8);
mDevice.setParity(UartDevice.PARITY_NONE);
mDevice.setStopBits(1);
mDevice.registerUartDeviceCallback(mUartCallback);
I am reading from its buffer in that callback as follows:
public void readUartBuffer(UartDevice uart) throws IOException {
// "The output is an ASCII capital “R”, followed by three ASCII character digits
// representing the range in inches up to a maximum of 255, followed by a carriage return
// (ASCII 13)
ByteArrayOutputStream bout = new ByteArrayOutputStream();
final int maxCount = 1024;
byte[] buffer = new byte[maxCount];
int total = 0;
int cycles = 0;
int count;
bout.write(23);
while ((count = uart.read(buffer, buffer.length)) > 0) {
bout.write(buffer, 0, count);
total += count;
cycles++;
}
bout.write(0);
byte[] buf = bout.toByteArray();
String bufStr = Arrays.toString(buf);
Log.d(TAG, "Got " + total + " in " + cycles + ":" + buf.length +"=>" + bufStr);
}
private UartDeviceCallback mUartCallback = new UartDeviceCallback() {
#Override
public boolean onUartDeviceDataAvailable(UartDevice uart) {
// Read available data from the UART device
try {
readUartBuffer(uart);
} catch (IOException e) {
Log.w(TAG, "Unable to access UART device", e);
}
// Continue listening for more interrupts
return true;
}
When I connect the sensor and use this code I get readings back of the form:
05-10 03:59:59.198 1572-1572/org.tomhume.blah D/LVEZ0: Got 7 in 1:9=>[23, 43, 0, 6, -77, -84, 15, 0, 0]
05-10 03:59:59.248 1572-1572/org.tomhume.blah D/LVEZ0: Got 7 in 1:9=>[23, 43, 0, 6, 102, 101, 121, 0, 0]
05-10 03:59:59.298 1572-1572/org.tomhume.blah D/LVEZ0: Got 7 in 1:9=>[23, 43, 0, 6, 102, 99, 121, 0, 0]
The initial 23 and the final 0 on each line are values I have added. Instead of an expected R\d\d\d\13 I expect between them, I'm getting 7 signed bytes. The variance in some of these byte values appears when I move my hand towards and away from the sensor - i.e. the values I'm getting back vary in a way I might expect, even though the output is completely wrong in form and size.
Any ideas what I'm doing wrong here? I suspect it's something extremely obvious, but I'm stumped. Examining the binary values themselves it doesn't look like bits are shifted around by e.g. a mistake in protocol configuration.
I can't test it on a hardware now, but seems algorithm for reading serial data from a LV-MaxSonar LV-EZ0 rangefinder should be slightly different: you should find "an ASCII capital “R” in UART sequence buffer (because LV-EZ0 starts sending data after power on and not synchronized with Raspberry Pi board and first received byte may be not “R” and quantity of received bytes can be less or more then 5 bytes of LV-MaxSonar response^ in one buffer can be several (or part)of LV-MaxSonar responses) and THAN try to parse 3 character digits representing the range in inches and ending CR symbol (if there is no all 3 bytes for digits and CR symbol - than start to find capital “R” again because LV-MaxSonar response is broken (it also can be)). For example take a look at GPS contrib driver especially at processBuffer() of NmeaGpsModule.java and processMessageFrame() of NmeaParser.java - the difference is in your have only one "sentence" and its start is not "GPRMC", but only "R" symbol.
And other important thing: seems there no capital “R” (ASCII 82) in your response buffers - may be some issues in LV-MaxSonar LV-EZ0 connection. Your schematics should be exactly like top right picture on page 6 of datasheet: Independent Sensor Operation: Serial Output Sensor Operation. Also try, for example, to connect LV-MaxSonar LV-EZ0 to USB<->UART (with power output) cable (e.g. like that) and test it in terminal with your PC.