I need to compare test answers that I read from a file. The file looks like this:
1st line = Answer key
3rd Line and below = Student ID + Student answers to test
TTFTFTTTFTFTFFTTFTTF
ABC54102 T FTFTFTTTFTTFTTF TF
DEF56278 TTFTFTTTFTFTFFTTFTTF
ABC42366 TTFTFTTTFTFTFFTTF
ABC42586 TTTTFTTT TFTFFFTF
I put the answer key (1st line) in a String called ansKey with .nextLine(). I then print the student ID in a loop and put that student's answers in another String and pass both to a method:
Scanner inFile = new Scanner(file);
while(inFile.hasNextLine())
{
//Student ID
System.out.print("\t" + inFile.next());
//Student Answers
studentAnswers = inFile.nextLine();
System.out.print("\t" + studentAnswers);
//Get examGrade
testGrade = examGrade(ansKey, studentAnswers.trim());
//Display scores
System.out.println(testGrade);
}
In my method I have a for loop to compare:
public static String examGrade(String ansKey, String studentAnswers)
{
for(int i = 0; i < studentAnswers.length(); i++)
{
if(ansKey.charAt(i) == studentAnswers.charAt(i))
score += 2;
else if(studentAnswers.charAt(i) == ' ')
score += 0;
else
score -= 1;
}
}
All of this works perfectly fine. Except my professor doesn't want me to use trim(). If I take it out, I get ArrayIndexOutOfBounds. The reason I use trim() is because studentAnswers has a space in front when I read it with .nextLine(); I can't use .next() as some of the answers have spaces in between them.
I don't believe I can use anything I haven't used in my code already (Classes not seen here, arrays, etc..). I can use StringBuffer and StringTokenizer though. Not sure how those classes would help me however. Any help would be appreciated!
Ok so if you can't use trim() or substring(), you'll have to go with arithmetic
public static String examGrade(String ansKey, String studentAnswers)
{
//Now only go up to the answer key length
for(int i = 0; i < ansKey.length(); i++)
{
//shift the index we are checking the student answers by 1
int j = i + 1;
if(ansKey.charAt(i) == studentAnswers.charAt(j))
score += 2;
else if(studentAnswers.charAt(j) == ' ')
score += 0;
else
score -= 1;
}
}
Related
I am trying to reduce the string array by using a for a loop. This is an example I tried to do
User string input: Calculus
User input:5
output: CalcuCalcCalCaC
I have turned the string to a char array but the issue presents itself when trying to print them out multiple times. It only prints once and has the right starting output.
input string: Oregon
input number: 4
output: Oreg
I notice my for loop says that it is not looping when I hover over it on the IDE that I downloaded from JetBrains.
I tried different combinations of decrementing and incrementing but could not get that "for statement is not looping". Other than that I have tried different ways to do something in the for loop but I don't think anything needs to be done for now if the for loop is not looping then, right?
So my question is, how to reduce a string or char array and print the decrement value over and over again?
Here is my code so far for it.
public String wordDown(String userString, int userNum)
{
String stringModded = userString.substring(0, userNum);
char[] charArray = stringModded.toCharArray();
char repeat = ' ';
for(int i = 0; i<userNum; ++i)
{
repeat = (char) (repeat +charArray[i]);
charArray[i] = repeat;
for(int j = 1; i > charArray.length; ++j)
{
String modWord = String.valueOf(charArray[i + 1]);
return modWord;
}
}
return null;
}
public static void main(String[] args)
{
int userNumber;
String userString;
RandomArrayFunctionalities ranMethod = new RandomArrayFunctionalities();
Scanner in = new Scanner(System.in);
System.out.println("\nEnter a word:");
userString = in.next();
System.out.println("\nEnter a number within the word scope that you just enter:");
userNumber = in.nextInt();
System.out.println(ranMethod.wordDown(userString, userNumber));
}
You do not need to modify the original array. Use a StringBuilder to concatenate the successive parts of the word. Use the String.substring(int,int) method to pull out those parts. The example that follows uses a decrementing index to generate the successively smaller substrings.
public String wordDown(String word, int userNum) {
StringBuilder sb = new StringBuilder();
for (int length = userNum ; length > 0 ; --length) {
sb.append(word.substring(0, length));
}
return sb.toString();
}
I think you are over complicating things, you don't need a char array at all and you only need a single loop, and a single return statement:
public String wordDown(String userString, int userNum) {
String finalString = "";
for (int i = 0; i < userNum; ++i) {
finalString = finalString + userString.substring(0, userNum - i);
}
return finalString;
}
Simply loop up to the inputted number and substring from 0 to inputtedNumber - loopCounter and append the result to the previously held String value.
Example Run:
Enter a word:
Calculus
Enter a number within the word scope that you just enter:
5
CalcuCalcCalCaC
Sidenote:
Technically you would want to use StringBuilder instead of appending String in a loop, but that is probably out of the scope of this question. Here is that version just for reference:
public String wordDown(String userString, int userNum) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < userNum; ++i) {
sb.append(userString.substring(0, userNum - i));
}
return sb.toString();
}
I am trying to solve a competitive programming practice set. I am only a beginner so please bear with me.
Here is the problem
The history teacher at your school needs help in grading a True/False test using his designed
scoring technique. Each correct answer is awarded two points, each wrong answer gets one
point deducted, and no answer gets a zero.
Your task is to help the teacher automate this task.
Input
The first entry in the file contains answers to the test in the form:
TFFTFTFTFFFTTTTFTFTF
The next line is the number test cases, i.e. number of students who took the test.
Every other entry in the file is the student ID, followed by a blank, followed by the student's
responses. For example, the entry:
S2013-1-1003 TFTFTFTT TFTFTFFTTFT
indicates that the student ID is S2013-1-1003 and the answer to question 1 is True, the
answer to question 2 is False, and so on. This student did not answer question 9. The exam, in
this example, has 20 questions.
Output
The output should be the student's ID, followed by the answers, followed by the test score,
followed by the test grade. Assume the following grade scale: 90%-100%, A; 80%-89.99%, B;
70%-79.99%, C; 60%-69.99%, D; and 0%-59.99%, F.
Sample Input
TTTTTFFFFF
3
S2013-1-2345 TTTTTFFFFF
S2013-1-1266 TFTFTFTFTF
S2012-2-0006 T T TF F F
Sample Output
S2013-1-2345 TTTTTFFFFF 20 A
S2013-1-1266 TFTFTFTFTF 8 F
S2012-2-0006 T T TF F F 12 D
*/
My code :
public class Score {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
//input answer to the test
String correctAnswer = sc.nextLine();
//input number of test cases
int numberOfStudents = sc.nextInt();
String studentID[] = new String[numberOfStudents];
String studentAnswer[] = new String[numberOfStudents];
int studentScore[] = new int[numberOfStudents];
char studentGrade[] = new char[numberOfStudents];
//ask user to input data
for(int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter student details");
studentID[i] = sc.nextLine();
studentAnswer[i] = sc.nextLine();
}//end of first for loop
//checks whether the student has the correct score
for(int y = 0; y < correctAnswer.length(); y++) {
if(studentAnswer[y].charAt(y) == correctAnswer.charAt(y)) {
studentScore[y]++;
}//end of if
}//end of for
for(int y = 0; y < numberOfStudents; y ++) {
double percentage = (studentScore[y] / correctAnswer.length()) * 100 ;
//check the letter grade of the student
if(percentage >= 90) {
studentGrade[y] = 'A';
}//end of first if
else if(percentage >= 80 && percentage <= 89) {
studentGrade[y] = 'B';
}//end first else if
else if(percentage >= 70 && percentage <= 79) {
studentGrade[y] = 'C';
}//end of second else if
else if(percentage >= 60 && percentage <= 69) {
studentGrade[y] = 'D';
}//end of third else if
else {
studentGrade[y] = 'F';
}//end of last else
}//end of for
//close the scanner to avoid any memory leaks
//display the score
for(int i = 0; i < numberOfStudents; i++) {
System.out.printf("%d\t%d\t%d\t%d", studentID[i], studentAnswer[i], studentScore[i], studentGrade[i]);
}//end of first for
}//end of main
}//end of class
The program compiles and all however once I input my test data, i received an outofBounders error from my compiler. Then I realized that I had made a mistake in this code
System.out.println("Enter student details");
studentID[i] = sc.nextLine();
studentAnswer[i] = sc.nextLine();
}//end of first for loop
if StudentID and studentAnswer is an integer then I can seperate them by using space and enter my data in one line. However I forgot that when I use space as a seperator, it is not seperated as space is still considered a string. My main question here is how do I ask the user to input his student ID and his answer in one line seperated by a string so that I can store then into my arrays such as studentID array and studentAnswer array.
The format specifier that you use for display the score is wrong! you can can change it as below:
//display the score
for(int i = 0; i < numberOfStudents; i++) {
System.out.printf("%s\t%s\t%d\t%s", studentID[i], studentAnswer[i], studentScore[i], studentGrade[i])
}//end of first for
You are taking input using sc.nextLine(). What does nextLine() do is, it reads all character from input buffer until \n or newline character is found.
So you can ask user to give input something like this way:
StudentID \n studentAnswer
Another way you can modify your input taking array as like as this:
for(int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter student details");
String line = sc.nextLine();
char[] chars = line.toCharArray();
String fs = "";
String sc = "";
boolean flag = false;
for(int j=0;j<chars.length;j++){
if(chars[j]==' ') {
flag = true;
continue;
}
if(flag ==false) fs += chars[j];
else sc += chars[j];
}
studentID[i] = fs;
studentAnswer[i] = sc;
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
import java.util.Scanner;
import java.util.ArrayList;
public class hangman {
public static void ttt(String inputWord) {
int wordLength = inputWord.length();
String blanks = "";
for (int i = 0; i < wordLength; i++) {
blanks = blanks.concat("_ ");
}
// System.out.print(wordLength);
System.out.println(blanks);
int points = 0;
int counter = 0;
ArrayList<String> usedChars = new ArrayList<String>();
while (points < wordLength) {
Scanner reader = new Scanner(System.in);
System.out.println("Guess: ");
String guess = reader.next();
// int checker = 0;
// for(int k = 0; k < usedChars.size(); k++) {
// if(usedChars.get(k) != guess) {
// checker = checker + 1;
// }
// else {}
// }
// if(checker == usedChars.size()) {
for (int i = 0; i < wordLength; i++) {
if (guess == inputWord.substring(i, i + 1)) {
points = points + 1;
usedChars.add(guess);
System.out.println("hit"); // this is me trying to see if
// this part is working
} else {
}
}
System.out.println("Used letters: " + usedChars);
// }
// else {
// System.out.print("Sorry, that letter has already been used");
// }
counter = counter + 1;
if (counter == 5) {
points = wordLength;
}
}
System.out.println("Game over");
}
public static void main(String[] args) {
ttt("to");
}
}
Don't worry about the commented out code, that's just me going over the top trying to prevent duplicate guesses, but it's more important that I get the rest of the code to work first.
Anyway, the only part of my code that seems to be working is the counter part. You can try it yourself, but it seems like all it does it take 5 guesses (5 lives, kind of random) and print game over.
edit: in hindsight i need to revisit that counter part, because it should only increase for incorrect guesses
The first thing I noticed was that my array isn't working correctly. It's not .add()'ing like I ask it to add my guesses. (Source: https://beginnersbook.com/2013/12/java-arraylist-add-method-example/)
Then, the more serious problem of the code not even being able to record correct guesses :/
I'm starting to code in my school's java class and decided to try this on my own for fun, any help would be greatly appreciated! :P
change the following boolean expression
guess == inputWord.substring(i, i + 1)
to
guess.equals(inputWord.substring(i, i + 1))
because guess is a String object. using '==' operator will only compare the reference, not the value.
also you might want to use
String guess = reader.nextLine();
instead of
String guess = reader.next();
I understand how to count the occurrences of specific characters in a string. What I am struggling is printing "The specific character is at location x, y, z". If I place the text within the loop that tests for location, the text is printed multiple times. I do not want that to happen.
There are other constraints as well. I must keep the program basic, and I am limited to using the charAt() and string.lenghth() functions. The program should only exit when the user enters "-1". When the user enters the string, the program should read through the characters, output the location of the specific characters, and then prompt the user to enter a new string. I am also struggling with allowing the user to enter a new string and running the loop again.
Here is the code I have so far
import java.util.Scanner;
public class GimmeAW {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the Line\nEntering -1 exits the program")
String aLine;
aLine = input.nextLine();
char one = aLine.charAt(0);
char two = aLine.charAt(1);
if (one == '-' && two == '1') {
System.out.println("System Exit");
System.exit(1);
}
for (int i = 0; i < aLine.length(); i++) {
if (aLine.charAt(i) == 'w' || aLine.charAt(i) == 't') {
int location = i;
System.out.print(" " + i);
}
}
}
To avoid printing the msg multiple times, just keep the msg outside of the counting loop and print it once for each character ...
char[] ch = {'w', 't'}; // characters to count
int l = aLine.length();
for(int i = 0; i < ch.length; i++) {
System.out.print("The character " + ch[i] + " is at locations ");
// searching
for(int j = 0; j < l; j++) {
if(aLine.charAt(j) == ch[i]) {
System.out.print(j + " ");
}
}
System.out.println();
}
And you can put all the code you want to repeat inside a do-while loop and run it until the user wants to.
String choice = "yes";
do {
// code
// want to repeat ??
choice = in.nextLine();
} while(choice.equals("yes"));
So I think my while loop is not even occurring and I am not quite sure why. It is probably an something obvious however I cannot seem to find the solution. What this code is attempting to do is use the variable "firstLetter" and add to the String "passcode" and continue to add the different characters that are specified within the while loop. however it is saying that my variable may have not been initialized which makes me think that the whole loop is messed up and is not being seen. Im pretty new to coding so any help would be appreciated
import java.util.Scanner;
public class Password
{
public static void main (String [] args)
{
System.out.println("This program will take a phrase by you and"
+ "\ncreate a strong and safe password that "
+ "\nwill be similar. Please enter a phrase.");
Scanner keyboard = new Scanner (System.in);
String message = keyboard.nextLine();
String firstLetter;
int index = 0,
number = 0, //a counting mechanism
spot = 2, // how many characters in each word you put down
pass = 1; //counting up the number of char in the password
if (message.charAt(0) == ' '){
System.out.println("Make sure the first character in your "
+ "phrase is not a space");
System.exit(1);
}//if
System.out.print("\nYour Password is: ");
char white = message.charAt(index);
firstLetter = Character.toString(white);
System.out.println(firstLetter);
index = 1;
String passcode;
while(index < message.length()) {
white = message.charAt(index);
if ((white != ' ') && (number != spot)) {
pass = pass + 1;
index = index + 1;
number = number + 1;
passcode = firstLetter + white;
}//if
else if (white != ' ') {
index = index + 1;
}//else if
else { spot = spot + 1;
number = 0;
index = index + 1;
}//else
}//while
System.out.print(passcode);
}
}
You have declared a variable passcode like:
String passcode;
The only way to initialize it when you go in while loop (meaning while condition satisfies), you go into if if ((white != ' ') && (number != spot)) { What if it doesn't satisfies condition? That means you dont have any values for pass code and then you try to access it like:
System.out.print(passcode);
Hence compiler complains about the same. So you need to do something addition to String declaration like:
String passcode = "";//define it as well with default value and you might need to check defining values within if/else where its not already present
Just had a brief look at the code, I feel this would not compile and complain about passcode variable not being initialized. What if the condition
index < message.length() is not true first time and while loop is never entered!!
I guess that explains why compiler is giving error.
You can initialize passcode to any value, null or empty string may be depending on your use case which I am not sure of.
Hope this helps.