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

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));
}
}
}

Related

I can't add a string to itself

I'm new to java and trying to add a string to itself (plus other strings also) and it runs but doesn't do anything at all, as in it just outputs "test", which is what it is before
everything else seems to work
package chucknorris;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input string:");
String input = scanner.nextLine();
int length = input.length();
String output = "test";
for (int current = 0;current <= length;current++) {
String letter = input.substring(current, current);
output = output + letter + " ";
if (current == length) {
System.out.println(output);
}
}
}
}
Try this Solution, but you should use StringBuilder if you want to edit a String for a multiple times
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input string:");
String input = scanner.nextLine();
int length = input.length();
String output = "test";
for (int current = 0;current <= length;current++) {
if (current >= length) {
break;
}
String letter = input.substring(current, current + 1);
output = output + letter;
}
System.out.println(output);
}
}
use concat for the string concatenation.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input string:");
String input = scanner.nextLine();
int length = input.length();
String output = "test";
output = output.concat(output).concat(input).concat("");
System.out.println(output);
}

Storing strings in list with loop, then printing the list

My goal is to ask the user to enter a bunch of strings in a loop, and when they enter "stop", the loop breaks and prints all those strings with a comma at the end of each word. For example, if the user enters "first", "second", "third", and "fourth", then the program would print the following:
first, second, third, fourth
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
int i;
String s;
String[] listOfStrings = new String[1000];
String last = "";
System.out.println("Please enter some Strings: ");
for (i = 1; i>0; i++) {
listOfStrings[i] = kb.next();
last = listOfStrings[i] + ",";
if (listOfStrings[i].equalsIgnoreCase("stop")) {
break;
}
}
System.out.print(last);
There is a problem because it always just winds up printing the last word and nothing else. Any help would be greatly appreciated.
I would use an ArrayList:
Scanner sc = new Scanner(System.in);
List<String> list = new ArrayList<String>();
while (sc.hasNext()) {
String s = sc.next();
if (s.equalsIgnoreCase("stop")) {
break;
} else {
list.add(s);
}
}
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i) + ",");
}
If you want everything in one line, you can do this:
Scanner sc = new Scanner(System.in);
String line = "";
while (sc.hasNext()) {
String s = sc.next();
if (s.equalsIgnoreCase("stop")) {
break;
} else {
line += s + ", ";
}
}
System.out.println(line.substring(0, line.length()-2));

String Arrays and BufferedReader

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...
}
}

Print Words In String Backwards

So I'm having a bit of trouble with my Computer Science class. I need to write some code that will take a string and print it backwards in reverse word order. He told me to find an empty space, then print from there and then keep searching....and repeat this until the end of the string. I typed my code out and all it does it print the first word 3 times. I know this will probably seem obvious to you guys.
public class Backwords
/*
* Gets words from main and prints in reverse order
*/
public static String BackwardsString(String str)
{
String str1 = (" " + str);
String answer = (" ");
int lastpos = str1.length();
for(int currpos = str.length(); currpos >= 0; currpos--) //shazam
{
if (str1.charAt(currpos) == ' ')
{
for (int p = currpos+1; p <lastpos; p++) //majicks
answer = answer + str1.charAt(p);
lastpos = currpos;
System.out.println(answer);
}
}
return answer;
}
public static void main(String [] args)
{
System.out.println("Enter a string : ");
Scanner firststr = new Scanner(System.in); //gets string input
String str = firststr.next();
System.out.println(BackwardsString(str));
}
}
Set answer back to answer = "" before the second nested for loop
for(int currpos = str.length(); currpos >= 0; currpos--) //shazam
{
if (str1.charAt(currpos) == ' ')
{
answer = "";
for (int p = currpos+1; p <lastpos; p++) //majicks
answer = answer + str1.charAt(p);
lastpos = currpos;
System.out.println(answer);
}
}
You should use StringBuilder instead of String here since there can be lot of String concatenation which may create more object in the heap.
Using StringBuilder you can do this easy way too.
Eg:
public static String BackwardsString(String str) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(str);
return stringBuilder.reverse().toString();
}
public static void main(String[] args) {
System.out.println("Enter a string : ");
Scanner firststr = new Scanner(System.in);
String str = firststr.next();
System.out.println(BackwardsString(str));
}
try this
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string ");
String str = sc.nextLine();
String[] strArray = str.split(" ");
StringBuilder reverseString = new StringBuilder("");
for (int i = strArray.length - 1; i >= 0; i--) {
reverseString.append(strArray[i]+" ");
}
System.out.println("Reverse of string is : "+reverseString.toString());
You'd probably have an easier time splitting the string:
String[] words = str1.split(" ");
Then you'd work on each word[i] reversing it, you could break it down to a char array, or use a stringbuilder as others have suggested, up to you on what you think is appropriate for your class.

How to display specific data from a file

My program is supposed to ask the user for firstname, lastname, and phone number till the users stops. Then when to display it asks for the first name and does a search in the text file to find all info with the same first name and display lastname and phones of the matches.
import java.util.*;
import java.io.*;
import java.util.Scanner;
public class WritePhoneList
{
public static void main(String[] args)throws IOException
{
BufferedWriter output = new BufferedWriter(new FileWriter(new File(
"PhoneFile.txt"), true));
String name, lname, age;
int pos,choice;
try
{
do
{
Scanner input = new Scanner(System.in);
System.out.print("Enter First name, last name, and phone number ");
name = input.nextLine();
output.write(name);
output.newLine();
System.out.print("Would you like to add another? yes(1)/no(2)");
choice = input.nextInt();
}while(choice == 1);
output.close();
}
catch(Exception e)
{
System.out.println("Message: " + e);
}
}
}
Here is the display code, when i search for a name, it finds a match but displays the last name and phone number of the same name 3 times, I want it to display all of the possible matches with the first name.
import java.util.*;
import java.io.*;
import java.util.Scanner;
public class DisplaySelectedNumbers
{
public static void main(String[] args)throws IOException
{
String name;
String strLine;
try
{
FileInputStream fstream = new FileInputStream("PhoneFile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
Scanner input = new Scanner(System.in);
System.out.print("Enter a first name");
name = input.nextLine();
strLine= br.readLine();
String[] line = strLine.split(" ");
String part1 = line[0];
String part2 = line[1];
String part3 = line[2];
//Read File Line By Line
while ((strLine= br.readLine()) != null)
{
if(name.equals(part1))
{
// Print the content on the console
System.out.print("\n" + part2 + " " + part3);
}
}
}catch (Exception e)
{//Catch exception if any
System.out.println("Error: " + e.getMessage());
}
}
}
you need to split your line and set your parts inside the while loop:
FileInputStream fstream = new FileInputStream("PhoneFile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
Scanner input = new Scanner(System.in);
System.out.print("Enter a first name");
name = input.nextLine();
String[] line;
String part1, part2, part3;
//Read File Line By Line
while ((strLine= br.readLine()) != null)
{
line = strLine.split(" ");
part1 = line[0];
part2 = line[1];
part3 = line[2];
if(name.equals(part1))
{
System.out.print("\n" + part2 + " " + part3);
}
}

Categories

Resources