Can someone point out what is wrong with my program?
I have done most of it but I can't seem to find what's wrong with it.
It doesn't ask the user for the "enter your grade" prompt for each course.
This is for an array assignment for school. Here is my code.
I am having difficulties figuring out what is wrong with the for loop I made specifically the for loop.
This program is supposed to ask the user for their courses and then the user enters their grades for that course.
If possible, please provide me hints on what I am doing wrong.
import java.io.*;
public class StudentMarks {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException{
// TODO code application logic here
//Declare BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//declare variables
int x=0, y=0;
double grade=0.0;
String course;
//ask user how many courses they completed
System.out.println("How many courses have you completed?");
//obtain answer
int completed=Integer.parseInt(br.readLine());
//declare array for course
String courses[]=new String[completed];
//ask user to enter the course names use a FOR loop for this
for(int i=0;i<courses.length;i++)
{
i++;
System.out.println("Please enter course name " + i);
course = br.readLine();
for(int j=i--;j<i;j++)
{
j++;
System.out.println("What is the grade you got for " + course+ " " + j);
//get their answer
grade = Double.parseDouble(br.readLine());
}
}//end for loop
//display to the user the high achievement award qualifiers:
System.out.println("High-Ahcievement Award Qualifiers: \n");
if(grade>93)
{
//output
}
else if(grade<70)
{
System.out.println("Needs Improvement:");
//output
}
}
}
Instead of i++ use
System.out.println("Please enter course name " + (i+1));
you do not need any nested loop
for(int j=i--;j<i;j++)
{
j++;
System.out.println("What is the grade you got for " + course+ " " + j);
//get their answer
grade = Double.parseDouble(br.readLine());
}
instead use
System.out.println("What is the grade you got for " + course);
//get their answer
grade = Double.parseDouble(br.readLine());
HERE is the Full code if you still having trouble understanding it let me know .
import java.io.*;
public class sort {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException{
// TODO code application logic here
//Declare BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//declare variables
int x=0, y=0;
double grade=0.0;
String course;
//ask user how many courses they completed
System.out.println("How many courses have you completed?");
//obtain answer
int completed=Integer.parseInt(br.readLine());
//declare array for course
String courses[]=new String[completed];
//ask user to enter the course names use a FOR loop for this
for(int i=0;i<courses.length;i++)
{
System.out.println("Please enter course name " + (i+1));
course = br.readLine();
System.out.println("What is the grade you got for " + course);
//get their answer
grade = Double.parseDouble(br.readLine());
//end for loop
//display to the user the high achievement award qualifiers:
System.out.println("High-Ahcievement Award Qualifiers: \n");
if(grade>93)
{
//output
}
else if(grade<70)
{
System.out.println("Needs Improvement:");
//output
}
}
}
}
I think you didnt intend to have the i++ / j++ in your for loops (first statement).
The third “parameter” of the loop head actually tells the program what to do, when it reaches the end of the loop. Therefore you increment twice each time.
Your inner loop (with int j = i--) has a condition that is always false, and so it's body is never executed.
The line of code:
j = i--
isn't as simple as it seems and can be broken down into two lines:
j = i;
i = i - 1;
Note that j is set to the value of i, and only after that does i get decremented. So if j is set to i, and then i becomes i - 1, i will be one less than j. So the condition of the for loop i.e. j < i, will always be false, and so the body of the loop will never be executed.
Example:
i = 5;
j = i--;
this boils down to
i = 5;
j = i; //j is 5
i = i - 1; //i is 4
j < i; //5 < 4 is false, inner for loop not executed
Hope this helps!
Related
I have a program that is supposed to simulate a game of poker in java. I have a method class called Poker and a check class called CheckPoker which calls the methods in the method class. I haven't even been able to check if the algorithmic part works because while asking if the user would like to switch out any cards. The loop should quit after 5 cards have been entered or if the user enters "1" but in running the program, the for loop doesn't quit until 5 card values have been entered and then throws a "java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 56" error. I have tried a for loop, a while loop, a do-while loop, but none have seemed to work thus far.
import java.util.*;
public class Poker {
private String[] deck = {
"D1","D2","D3","D4","D5","D6","D7","D8","D9","D10","DJ","DQ","DK","DA",
"C1","C2","C3","C4","C5","C6","C7","C8","C9","C10","CJ", "CQ","CK","CA",
"H1","H2","H3","H4","H5","H6","H7","H8","H9","H10","HJ", "HQ","HK","HA",
"S1","S2","S3","S4","S5","S6","S7","S8","S9","S10","SJ", "SQ","SK","SA"};
private List<String> hand = new ArrayList<>();
public Poker(){
Collections.shuffle(Arrays.asList(deck));
}
public void playGame(){
System.out.print("The first five cards are: ");
for(int i = 0; i<5; i++){
System.out.print(deck[i] +", ");
}
System.out.println(" ");
int k = 0;
String j;
List<String> discard = new ArrayList<>();
Scanner in = new Scanner(System.in);
System.out.println("Enter up to 5 cards you want to get rid of (1 to quit): ");
while (k<5) { //this is the loop I'm having trouble with
j = in.next();
if(!j.equals("1")){
j = in.next();
discard.add(j);
k++;
}else{
break;
}
}
List deckList = Arrays.asList(deck);
String[] discard1 = discard.toArray(new String[0]);
for(int l = 0; l<k; l++){
int m = deckList.indexOf(discard1[l]);
String n = deck[m];
deck[m] = deck[l+5];
deck[l+5] = n;
}
System.out.print("Your new hand is: ");
for(int i = 0; i<5; i++){
System.out.print(deck[i] +", ");
hand.add(deck[i]);
}
System.out.println(" ");
}
Try the code below. It seems you were grabbing two cards per iteration and not capturing them all in the ArrayList.
Scanner in = new Scanner(System.in);
System.out.println("Enter up to 5 cards you want to get rid of (1 to quit): ");
while (k<5) { //this is the loop I'm having trouble with
j = in.nextLine();
if(j.equals("1") {
break;
}
discard.add(j);
k++;
}
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;
}
I am currently teaching my self some basic Java through a text book and gave myself a "homework problem" but I'm having difficulty when writing to a .txt file of a method. It doesn't want to take more than 2 people. Here's a quick run down of what the method is meant to do:
1.) Collects the number of people the user would like to enter into the data file
2.) Collects the first and last name of each person in a two-dimensional array
3.) Collects a number of payments set by the user for each (separate) person that the user entered into an array.
4.) Then it calculates the average payment for each of the people entered into another array(so each person should have their own average)
5.) Lastly, it writes the data to a .txt file named "BusinessData.txt."
It seems to be working perfectly up until it tries to write more than 2 people into the .txt file. It's driving me nuts and I really would like to know how to fix this before moving on to the next couple of topics.
Here's the error message that I am getting when I try to add more than 2 people:
Exception in thread "main" java.lang.Array IndexOutofBoundsException:
3
at Business1.dataCollect(Business1.java:210)
at Business1.main(Business1.java:62)
I'd greatly appreciate any tips.
Here's the actual code:
import java.util.*;
import java.io.*;
public class Business1
{
public static void main(String[] args) throws IOException
{
// Declare local variables
int menuChoice;
// Declare local objects
Scanner input = new Scanner(System.in);
// Display the program title
System.out.println("\n\n\n\n\t\t\t\t***************************************\n"
+ "\t\t\t\t* Average Customer Payment Calculator *\n"
+ "\t\t\t\t***************************************\n\n\n");
// Start of a do-while loop: Continues the program as long as the user doesn't choose to exit
do
{
// Start of a do-while loop: Input Validation (menuChoice must be between 1 - 4)
do
{
// Prompt user for menuChoice
System.out.print("\tPlease enter an integer in accordance to the given choices:\n\n"
+ "\t(1) Collect and Erase Old Data\n"
+ "\t(2) Read Saved Data\n"
+ "\t(3) Append Old Data\n"
+ "\t(4) Exit Program\n\n"
+"\tEnter Choice: ");
menuChoice = input.nextInt();
System.out.println("\n\n");
// If menuChoice is equal to 1: Erase old Data and Collect and Write new data
if(menuChoice == 1)
{
try
{
dataCollect();
}
catch(IOException e)
{
System.out.println("Error");
}
}
// else if menuChoice is equal to 2: Read Saved Data
else if(menuChoice == 2)
{
}
// else if menuChoice is equal to 3: Append Old Data
else if(menuChoice == 3)
{
}
// else if menuChoice is equal to 4: Exit Program
else if(menuChoice == 4)
{
System.out.println("\n\n\n\t\tGoodbye!\n\n\n");
}
// else display error message: Error. Please enter a number 1 - 4
else
{
System.out.println("\n\nERROR. Please enter a number 1 - 4\n\n");
}
// End of do-while loop: Input Validation (menuChoice must be between 1 - 4)
} while(menuChoice < 1 || menuChoice > 4);
// End of a do-while loop: Continues the program as long as the user doesn't choose to exit
} while(menuChoice != 4);
}
// Create a method named dataCollect
public static void dataCollect() throws IOException
{
// Declare local variables
int numPeople, numPayments /* array size for payments */;
double totalPayments = 0, averagePayment;
double [] paymentsArray /* different payments */, averagePaymentsArray;
String [][] namesArray /* First name, last name in array */;
// Declare objects
Scanner keyboard = new Scanner(System.in);
// Prompt user for the number of people they would like to add to the records and store in variable numPeople
System.out.print("\tHow many people would you like to add to your records?\n\n\tEnter an integer: ");
numPeople = keyboard.nextInt();
System.out.println("\n\n");
// Initialize arrays
namesArray = new String[numPeople][2];
// Create a counter for the for-loop
int count = 0;
// For-loop will prompt user for first and last name of each person
for(int i = 1; i <= numPeople; i++)
{
// Consume the remaining newline character
keyboard.nextLine();
// Prompt user for first name
System.out.print("\tPlease enter the FIRST name of person #" + i +": ");
namesArray[count][0] = keyboard.nextLine();
System.out.println("\n\n");
//Prompt user for last name
System.out.print("\tPlease enter the LAST name of person #" + i + ": ");
namesArray[count][1] = keyboard.nextLine();
System.out.println("\n\n\n");
count++;
}
// Reset counter for the next for-loop
count = 0;
int count2 = 1; // Used to keep track of which payment number the user is inputing
int count3 = 0;
int count4 = -1;
// ****************************************************************
// * Open file for input ******************************************
// ****************************************************************
PrintWriter outputFile = new PrintWriter("BusinessData.txt");
outputFile.println("\t\t\tBusiness Data\n\n");
outputFile.println("First Name\tLast Name\tP 1\t\tP 2\t\t P 3\t\tAverage Payments\n\n"
+ "------------------------------------------------------------------------------------------------------------------------------------------------------\n");
// For-loop will ask for number of payments each person made while also collecting the value of each of those payments in a nested for-loop.
for(int i = 0; i < numPeople; i++)
{
// Prompt user for first name
System.out.print("\tPlease enter the number of payments made by " + namesArray[count][0] +" " + namesArray[count][1] + "(Put in 3 for now) : ");
numPayments = keyboard.nextInt();
System.out.println("\n\n");
// Initialize array then reset it for the next person to come
paymentsArray = new double[numPayments];
for(int j = 0; j < numPayments; j++)
{
// ****************************************************************
// * Open file for input ******************************************
// ****************************************************************
System.out.print("\n\n\tPlease enter payment value of payment #" + count2 + " that " + namesArray[count][0] +" " + namesArray[count][1] + " made: $");
paymentsArray[j] = keyboard.nextDouble();
System.out.println("\n\n");
// Increment counter
count2++;
}
// ************************************************************************
// * Calculating Average Payment ******************************************
// ************************************************************************
// For loop for calculating average
for(int k = 0; k < numPayments; k++)
{
totalPayments += paymentsArray[k];
}
// Calculate the Average Payment
averagePayment = totalPayments/paymentsArray.length;
/**************************************************
********** BUG LIES IN THE WRITING **************
***************************************************/
// nested for-loop will write data now otherwise it'll just be wiped out and overwritten by the next input
for(int l = 1; l < numPeople; l++)
{
// Increment counter4
count4++;
// Output first name
outputFile.print(namesArray[count4][count3]);
// Increment counter3
count3++;
// Output last name
outputFile.print("\t\t" + namesArray[count4][count3] + "\t\t");
// Reset counter3
count3 = 0;
for (int m = 0; m < numPayments; m++)
{
outputFile.print(paymentsArray[m] + "\t\t");
}
outputFile.println(averagePayment + "\n\n");
}
// Reset total Payments for the next iteration
totalPayments = 0.0;
// Increment the counter
count++;
}
outputFile.close();
// End of dataCollect method
}
Running your code gives me Exception for 3+ users.
ArrayIndexOutOfBoundsException thrown at
outputFile.print(namesArray[count4][count3]);
Running in debug mode shows that namesArray[count4][count3] is pointing to a value which is not available .
count4 is incremented to out of bounds value because of the below loop.
I don't undertstand why you need this loop
for(int l = 1; l < numPeople; l++)
{
enter code here}
If you remove this it works fine.
im trying to write a program that will accept input of "put name mark", "get name mark" and "quit"
upon the user entering "put name mark" the program will prompt them to enter a student name and mark and then stores it at the next available array index.
the "get name" command will accept a name input from the user and they iterate through the array and display any mark matching the name entered.
the "quit" command will end the program and return the mean mark and the highest mark in the display.
the problem im having is that it dosent seem to be entering the loop when i type the required words in. it just jumps to where it asks the question again and wont even accept input
im still a beginner and ive been working on this program for 4 weeks so any help would be greatly appreciated.
package week14;
import java.util.Scanner;
public class week {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//sets number of string inputs
{
String[] names = new String[50];
double[] scores = new double[50];
// Enter student name and score
System.out.print("please enter either: quit, put name mark, get name");
input.next();
if(input.next() == "put name mark" )
{
System.out.print("Enter Student Name");
names[50] = input.next();
System.out.print("Enter Score");
scores[50] = input.nextInt();
}
System.out.println("please enter either: quit, quit, put name mark, get name");
input.next();
if(input.next() == "get name")
{
System.out.print("please enter the name you would like to display the score for");
String get = input.next();
}
// Sort
for (int i = 50 - 1; i >= 1; i--) {
// Find the maximum in the scores[0..i]
double currentMax = scores[0];
int currentMaxIndex = 0;
for (int j = 1; j <= i; j++) {
if (currentMax < scores[j]) {
currentMax = scores[j];
currentMaxIndex = j;
}
}
// Swap scores[i] with scores[currentMaxIndex];
// Swap names[i] with names[currentMaxIndex] ;
if (currentMaxIndex != i) {
scores[currentMaxIndex] = scores[i];
scores[i] = currentMax;
String temp = names[currentMaxIndex];
names[currentMaxIndex] = names[i];
names[i] = temp;
}
if (input.equals("quit")){
System.out.print(names[i] + scores[i]);
System.out.println();
System.out.print(currentMax);
break;
}
}
}
}
}
That's what i got for now maybe there are some errors if there is any problem say what's it and I'll fix it.
import java.util.Scanner;
public class Week
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in); //Scanner used to get input from the user
String[] names = new String[50]; //The array for names remember arrays index began with 0 not 1
int[] scores = new int[50]; //Again arrays began with 0 not 1 and the last is n-1
int last = 0; //Used to store the last added ID
String command; //The command from the user
boolean running = true; //Whenever the program is running or not
while(running)
{
System.out.println("please enter either: quit, put name mark, get name"); //Print the command list
command = input.nextLine(); //The next input line (This will make the Thread pause untill it get and input)
if(command.equals("put mark")) //If the command is "put mark"
{
if(last == 49) //Check because we can create and Exception by adding too much element to and array
System.out.println("Max number of people reached"); //So we can't add more people
else
{
System.out.println("Enter Student Name"); //Print the questin
names[last] = input.nextLine(); //The name
System.out.println("Enter Score"); //Ask for the score
scores[last] = input.nextInt(); //Get the score ,because score is a double we should use double so it can take numbers like 0.1
last++; //Increment last with 1
}
}else if(command.equals("get name"))
{
System.out.println("please enter the name you would like to display the score for");
String name = input.nextLine(); //Get the name
for(int i = 0; i < last; i++) //Loop untill we hit the last added name's ID
if(names[i].equals(name)) //Check if the names[i] is the name that we're searching for
System.out.println(name + " 's score is " + scores[i]); //If it's then we print it out
}else if(command.equals("quit"))
{
running = false; //The loop will never run again
//Implement sorting for youself I would use Map<K, V> but you didn't learned it so..
//In this case you have to make 1 loop to sort both of the arrays by sorting the second array
//and when you move anything must it in both arrays I can't help you to make this sorry
for(int i = 0; i < last; i++) //We print the sorted arrays of the people and their scores
System.out.println(names[i] + " 's score is " + scores[i]); //Let's print it
}
}
}
}
Having difficulty taking in data (string and number) for participants. The idea is to create a program which will take in data into arrays (name and time separately) and eventually analyse the data by name and time
Here's my code attempt...
import java.util.Scanner;
public class RaceTimes
{
public static void main (String[] args)
{
int num;
Scanner input= new Scanner (System.in);
System.out.println("Welcome to Athletic Statistical Analysis Application");
System.out.println("******************************************************************* \n");
System.out.println("Please input number of participants ");
num=input.nextInt();
// If the user enters an invalid number... display error message... ask again for valid input number
while(num<2|| num >10)
{
System.out.println("Error invalid input! Try again! \nPlease input a valid number of participants...");
num=input.nextInt();
}
double resultArray [] = new double [num]; // create result array with new operator
String nameArray [] = new String [num];// create name array with new operator
// Using the num int will ensure that the array holds the number of elements inputed by user
for (int i = 0 ; i < nameArray.length ; i++)
System.out.println ("Please enter a race participant Name for runner " + (i+1) );
//nameArray [1] = input.nextString();
}
}
You're nearly there!
for (int i = 0 ; i < nameArray.length ; i++) {
System.out.println ("Please enter a race participant Name for runner " + (i+1) );
nameArray[i] = input.next();
System.out.println ("Please enter a race result for runner " + (i+1) );
resultArray[i] = input.nextDouble();
}
That should do it.
You might want to add something here to cope with values that are out of range, or things that can't be interpreted as floating point numbers. You'd need a try/catch block to catch InputMismatchException in order to deal appropriately with someone entering something that can't be interpreted as a number. (The .nextDouble() method will throw this exception if it can't parse the input.)