String Arrays and BufferedReader - java

I am working on an assignment for class and I'm stuck at the very beginning. I'm not sure how to go about the user input, I'll elaborate after I tell you what the assignment is....
The first input will be the answer key to a quiz of ten T or F answers. It then takes user input for Students first and last name, ID #, and then answers to a "quiz" of T/F, the user enters as many students as they want and then "ZZZZ" to terminate. All of the user input is entered in one entry and that's where I'm having issues.
An example input for the program:
1 T T T T T F T T F F
Bobb, Bill 123456789 T T T T T F T T F F
Lou, Mary 974387643 F T T T T F T T F F
Bobb, Sam 213458679 F T F T f t 6 T F f
Bobb, Joe 315274986 t t t t t f t t f f
ZZZZ
which will produce the output:
Results for quiz 1:
123-45-6789 Bill Bobb 10
974-38-7643 Mary Lou 9
213-45-8679 Sam Bobb 5
315-27-4986 Joe Bobb 10
The average score is 8.5
We have to use BufferedReader and all of the input is entered all at once. The issue I'm having is I do not know how to go about the input. At first I figured I would split the input by newline and create an array where each index is the newline, but what I have now only prints "ZZZZ" and I can't figure out why? I also don't know how to go about comparing the first index (answer key) with all the students answers. Once I split the input by newlines can I then split each index in that array by space? Any help is greatly appreciated! Please keep in mind I'm very new to Java.
What I have so far (I know its not much but I just got stuck right up front)....
public class CST200_Lab4 {
public static void main(String[] args) throws IOException {
String inputValue = " ";
String inputArr[] = new String[13];
String answerKey = null;
String numStudents[];
InputStreamReader ISR = new InputStreamReader(System.in);
BufferedReader BR = new BufferedReader(ISR);
while(!(inputValue.equalsIgnoreCase("ZZZZ"))) {
inputValue = BR.readLine();
inputArr = inputValue.split("\\r+");
answerKey = inputArr[0];
}
System.out.println(answerKey);
}
}

Use this code inside main()
String inputValue = " ";
String inputArr[] = new String[13];
String answerKey = null;
String numStudents[];
InputStreamReader ISR = new InputStreamReader(System.in);
BufferedReader BR = new BufferedReader(ISR);
try {
inputValue = BR.readLine();
String answers[] = inputValue.split(" ");
int count = 0;
System.out.println();
while((inputValue = BR.readLine()) != null) {
if (inputValue.equalsIgnoreCase("ZZZZ"))
break;
inputArr = inputValue.split("\\s+");
System.out.print(inputArr[2] + " ");
System.out.print(inputArr[1] + " ");
System.out.print(inputArr[0].split(",")[0] + " ");
count = 0;
for(int i = 0; i <10; i++){
if(inputArr[i+3].equalsIgnoreCase(answers[i+1]))
count ++;
}
System.out.print(count);
System.out.println();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I have left the average part for you to calculate. Mention not.

I just typed this code here, so there may be typos and you should validate it. But this is one way of doing it.
If you use an ArrayList to store student details, you don't need to know the number of students. Size of an ArrayList is dynamic.
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
import java.util.ArrayList;
public class CST200_Lab4 {
public static void main(String[] args) throws IOException {
String inputValue = "";
ArrayList<String[]> students = new ArrayList<String[]>()
String[] answerdarr;
BufferedReader BR = new BufferedReader(new InputStreamReader(System.in));
//first line is always the answers
String answers = BR.readLine();
answerArr = answers.split(" ");
while(!(inputValue.equalsIgnoreCase("ZZZZ"))) {
inputValue = BR.readLine();
//add extra array element so we can later use it to store score
inputValue = inputValue + " Score";
String[] inputArr = inputValue.split(" ");
int studentTotal = 0;
for(int i = 3, i < inputArr.length; i++) {
if(inputArr[i].equals["T"]) {
studentTotal++;
}
}
//previous value of this is "Score" as we set earlier
inputArr[13] = studentTotal;
students.add(inputArr);
}
//Now do your printing here...
}
}

Related

Reading the String and Int from file, and then looped through?

I'm trying to get it so when it reads through the file, it splits every thing before a comma into an element, and then since there are 10 integer grades, those need to be parsed into an int and then calculated for an average. However, I'm unsure of how to actually accomplish this. I've been looking for a solution for hours and I just can't seem to figure it out. I would really appreciate some help here, as I'm currently running out of brain cells.
Thank you, - from someone new to programming.
The assignment:
https://i.stack.imgur.com/L7E9x.png
The .txt file I'm reading from:
https://i.stack.imgur.com/nxCi4.png
My current code:
public class Main {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
String userInput;
System.out.println("Enter raw grades filename:");
userInput = scanner.nextLine();
BufferedReader br = new BufferedReader(new FileReader(userInput));
String line = "";
String txtSplitBy = ", ";
while ((line = br.readLine()) != null) {
String[] splitLine = line.split(", ");
String name = splitLine[0];
String scores = splitLine[2];
int i = Integer.parseInt(scores);
}
}
}
BufferedReader br = new BufferedReader(new FileReader(userInput));
String line;
String txtSplitBy = ",";
while ((line = br.readLine()) != null) {
int score = 0;
String grade;
String[] splitLine = line.split(txtSplitBy);
String name = splitLine[0];
for ( int i =1; i <= 10; i++) {
score += Integer.parseInt(splitLine[i]);
}
if ( score < 50 ) {
grade = "B";
}else if ( score < 60 ) {
grade = "A";
}else {
grade = "S";
}
System.out.println(name +"," + (score/10) + "," + grade );
}
You need to add your grade logic here.
Here is my version, I kept it simple, after all, it's your homework!
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
String userInput;
System.out.println("Enter raw grades filename:");
userInput = scanner.nextLine();
BufferedReader br = new BufferedReader(new FileReader(userInput));
String line = "";
String txtSplitBy = ","; // Changed from ', ' to ','
while ((line = br.readLine()) != null) {
String[] splitLine = line.split(",", 2); // The threee caps the number of splits
String name = splitLine[0];
ArrayList<Integer> grades = new ArrayList<>();
String[] rawGrades = splitLine[1].split(","); // List of grades as string
for(String rawGrade : rawGrades) {
grades.add(Integer.parseInt(rawGrade));
}
}
}

Cannot Read Next Console Line - NoSuchElementException

The idea of this is to take in a console input and use it as the file name for the text file to fill with square root values with various decimal places
however I cannot get it to let me enter anything, it throws a NoSuchElementException and I do not get why? in a previous method, I used this exact code to get the file name as a variable
This is Current Method
private static void FileWritting () throws IOException {
System.out.println("\n6.7.2 Writting Data");
System.out.println("-----------------------");
System.out.println("Enter the File name");
Scanner Scanner2 = new Scanner(System.in);
String filename = Scanner2.nextLine();
FileWriter writehandle = new FileWriter("D:\\Users\\Ali\\Documents\\lab6\\" + filename + ".txt");
BufferedWriter bw = new BufferedWriter(writehandle);
int n = 10;
for(int i=1;i<n;++i)
{
double value = Math.sqrt(i);
String formattedString = String.format("%."+ (i-1) +"f", value);
System.out.println(formattedString);
// bw.write(line);
bw.newLine();
}
bw.close();
writehandle.close();
Scanner2.close();
}
Where This is the previous method
System.out.println("6.7.1 Reading Data");
System.out.println("-----------------------");
System.out.println("Enter the File name");
Scanner Scanner1 = new Scanner(System.in);
String filename = Scanner1.nextLine();
FileReader readhandle = new FileReader("D:\\Users\\Ali\\Documents\\lab6\\"+ filename +".txt");
BufferedReader br = new BufferedReader(readhandle);
String line = br.readLine ();
int count = 0;
while (line != null) {
String []parts = line.split(" ");
for( String w : parts)
{
count++;
}
line = br.readLine();
}
System.out.println("The number of words is: " + count);
br.close();
Scanner1.close();
}
You're calling Scanner#close in your first method. This closes stdin, which makes reading from it impossible. I recommend creating a global variable to hold your scanner and closing it when your program terminates (instead of creating a new one in every method).
More info and a better explanation

How to take space separated input in Java using BufferedReader?

How to take space separated input in Java using BufferedReader?
Please change the code accordingly, i wanted the values of a, b, n as space seperated integers and then I want to hit Enter after every test cases.
Which means first i'll input the number of test cases then i'll press the Enter key. Then i input the vale of a then i'll press Space, b then again Space then i'll input the value of n, then i'll press the Enter key for the input for the next testcase.
I know that this can be done easily through Scanner but i don't wanna use it because it throws TLE(Time Limit Extended) error on online judges.
public static void main(String[] args) throws IOException {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String inputString = br.readLine();
int testCases = Integer.parseInt(inputString);
double a,b,n,j,t=1;
int i;
int ans [] = new int[testCases];
for(i=0;i<testCases;i++)
{
inputString = br.readLine();
a = Double.parseDouble(inputString);
inputString = br.readLine();
b = Double.parseDouble(inputString);
inputString = br.readLine();
n = Double.parseDouble(inputString);
for(j=0;j<n;j++)
{
if(t==1)
{
a*=2;
t=0;
}
else if(t==0)
{
b*=2;
t=1;
}
}
if(a>b)
ans[i]=(int)(a/b);
else
ans[i]=(int)(b/a);
t=1;
}
for(i=0;i<testCases;i++)
System.out.println(ans[i]);
}catch(Exception e)
{
return;
}
}
First read the number of input lines to be read.
Then parse each line and get the String.
Though I have not added the NumberFormatException handling, but it's a good idea to have that.
Change your for loop like this:
for(i=0;i<testCases;i++){
inputString = br.readLine();
String input[] = inputString.split("\\s+");
a = Double.parseDouble(input[0]);
inputString = br.readLine();
b = Double.parseDouble(input[1]);
inputString = br.readLine();
n = Double.parseDouble(input[2]);
for(j=0;j<n;j++){
if(t==1){
a*=2;
t=0;
}else if(t==0){
b*=2;
t=1;
}
}
if(a>b){
ans[i]=(int)(a/b);
}else{
ans[i]=(int)(b/a);
t=1;
}
}

Searching a file based on given user-inputted filters and parsing input?

I am attempting to make a program that searches a given file for a
Information is stored in the given format:
Jane 19 50 86 85 84 83 45 76
There is the name, along with the age, followed by test scores. The user inputs a name and an age, then the program searches the file for a line that has this name and age. These test scores should be retrieved and stored, then printed.
The program should then retrieve the information attached to that particular line in the file.
What I had planned on doing was storing the user input in Strings, then searching the file with these, like so:
Scanner input = Scanner(System.in);
String params = "";
System.out.print("name? ");
params += input.next() + " ";
System.out.print("age? ");
params += input.next();
System.out.println(params);
return params;
But this seems as though it would cause complications. If I searched for a boy named Tom who was 19, would this not also match with a boy named Tommy who was 19?
In addition, I'm not really sure how to parse the numbers from the given line to print them. I made a separate Scanner for the input line, and attempted to use Integer.parseInt(), but the Scanner starts from the beginning of the line, so it attempts to change "Jane", for example, to a int, which is of course, not possible, so it creates a NumberFormatException.
Addition of relevant code:
public static String introQuery(Scanner input) {
String params = "";
System.out.print("name? ");
params += input.next() + " ";
System.out.print("age? ");
params += input.next();
System.out.println(params);
return params;
}
public static void fileNameScanner(Scanner file, String params) {
boolean fileContains = false;
System.out.println("fileNameScanner ran");
int score = 0;
Scanner split = new Scanner(params).useDelimiter(" ");
String name = split.next().toUpperCase();
String gender = split.next().toUpperCase();
while (file.hasNextLine() /* && (fileContains = false)*/) {
String inputLine = file.nextLine().toUpperCase();
//commented out the test that would not work for the described case
if (inputLine.contains(params))/*(inputLine.contains(name) && (inputLine.contains(age)))*/{
Scanner numberSplit = new Scanner(inputLine);
score = Integer.parseInt(numberSplit.next());
fileContains = true;
}
}
//this test does not work for some reason
if (fileContains = false) {
System.out.println("name/age combination not found");
}
}
I would do it like this:
public static String[] getParams(Scanner input){
String[] data = new String[2];
System.out.print("Name? ");
data[0] = input.nextLine();
System.out.print("Age? ");
data[1] = input.nextLine();
System.out.println("Search parameters > Name: " + data[0] + "\tAge: " + data[1]);
return data;
}
public static String searchFile(String filePath, String[] param) throws IOException, FileNotFoundException{
BufferedReader br = new BufferedReader(new FileReader(new File(filePath)));
List<String> fileData = new ArrayList<String>();
List<String> NamesAndAge = new ArrayList<String>();
String line;
while((line = br.readLine()) != null){
fileData.add(line);
}
br.close();
for(String s : fileData){
String[] split = s.split(" ");
NamesAndAge.add(split[0] + " " + split[1]);
}
for(String n : NamesAndAge){
if(n.equalsIgnoreCase(param[0] + " " + param[1])){
int index = NamesAndAge.indexOf(n);
return fileData.get(index).substring(n.length()).trim();
}
}
return null;
}
The last method searchFile(String fileName, String[] param) will return the scores from the file eg. 1 4234 345 5646 13. If the method returns null it didn't find a matching name and/or age.

java scanner to detect 3 words on line

I am trying to write a little program that will use scanner to check if there is a next line (in awhile loop) and then maybe another one to check that the words on the line are tab appart and there are 3 strings (the use constructor to create a object) so the three strings would be Product Name Manufacturer Brcode
EG: Tyre17x60 Goodyear 458765464
and so and so
I am bit stuck with this so any help would be grateful
You can try this:
public static void main (String[] args) throws java.lang.Exception
{
String str = "Tyre17x60 Goodyear 458765464";
InputStream is = new ByteArrayInputStream(str.getBytes());
Scanner sc = new Scanner(is);
sc.useDelimiter("\n");
while (sc.hasNext())
{
String[] tmp = sc.next().split("\t");
if (tmp.length == 3)
System.out.println("Text contains 3 parts separated with tabs");
else
System.out.println("Text is not well formated");
// save data
//productName = tmp[0];
//manufacturer = tmp[1];
//brcode = tmp[2];
}
}
Assuming you are reading from a file, you can use the following code:
Scanner s = new Scanner(new File("file.txt"));
while(s.hasNext())
{
String productName = s.next();
String Manufacturer = s.next();
String Brcode = s.next();
}
Scanner scan = new Scanner("file.txt");
while(scan.hasNext()){
scan.nextLine();
System.out.println("Product : " + scan.next());
System.out.println("Name : " + scan.next());
System.out.println("Code : " + scan.nextLong());
}
Try something like this....

Categories

Resources