I'm trying to make a code that takes a users input and prints their schedule, but I'm running into a problem with my do-while loop.
My program will not rerun. I'm getting an error that says:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2 at com.company.Main.main(Main.java:25)
Here is my code:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String rerun;
do {
System.out.println("What is your name?");
String name = input.nextLine();
System.out.println("How many courses do you have?");
int numCourse = input.nextInt();
input.nextLine();
String[][] timetable = new String[numCourse][2];
for (int j = 0; j < numCourse; j++) {
System.out.println("What is the name of your course #" + (j + 1) + "?");
String course = input.nextLine();
timetable[j][0] = course;
System.out.println("What is your teachers name for " + course + "?");
String teacher = input.nextLine();
timetable[j][1] = teacher;
}
System.out.println("Hello " + name + ", here is your timetable:");
for (int i = 0; i <= numCourse; i++) {
System.out.format("\n%-30s%-30s", "Course #" + (i+1) + ": " + timetable[i][0],"Teacher: " + timetable[i][1]);
}
System.out.println("Would anyone else like to print their schedule? (yes/no)");
rerun = input.next();
}while(rerun.equalsIgnoreCase("yes"));
System.out.println("Goodbye!");
}
}
Problem is in second for loop where you display your from array. put next() inplace of nextLine() because sometimes it skip the position.
Change
for (int i = 0; i <= numCourse; i++) {
System.out.format("\n%-30s%-30s", "Course #" + (i+1) + ": " + timetable[i][0],"Teacher: " + timetable[i][1]);
}
To
for (int i = 0; i < numCourse; i++) {
System.out.format("\n%-30s%-30s", "Course #" + (i+1) + ": " + timetable[i][0],"Teacher: " + timetable[i][1]);
}
Suppose your numCorse is 2. In your code, loop start from 0 and terminate after 2 so, Your loop working right while i is 0 and 1 but if i is going to 3 you get exception ArrayIndexOutOfBound.
Related
I don't see the issue or how to input the message. The full error that I keep getting is below. I can't see any problems with the code and I can't find a way to a message into the code.
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of ran
ge: 30
at java.base/java.lang.StringLatin1.charAt (String.java:47)
at java.base/java.lang.String.charAt (String.java:693
at Main.main (Main.java:15)
import java.util.Scanner;
public class Main
{
public static void main( String[] args )
{
Scanner kb = new Scanner(System.in);
System.out.println("What is your message? ");
String message ="" + "\n";
System.out.println("\nYour message is " + " characters long.");
System.out.println("The first character is at position 0 and is '" + "'.");
int lastpos = 30;
System.out.println("The last character is at position " + lastpos + " and is '" + message.charAt(lastpos) + "'.");
System.out.println("\nHere are all the characters, one at a time:\n");
for ( int i=0; i<message.length(); i++ )
{
System.out.println("\t" + i + " - '" + message.charAt(i) + "'");
}
int a_count = 0;
for ( int i=0; i<message.length(); i++ )
{
char letter = message.charAt(i);
if ( letter == 'a' || letter == 'A' );
{
a_count++;
}
}
System.out.println("\nYour message contains the letter 'a' " + a_count + " times. Isn't that interesting?");
}
}
You never actually capture a message from the scanner - something like this:
message = kb.nextLine();
In addition, if you're trying to get the last index/position of the message, you'd want to do something like this:
int lastpos = message.length();
OR
int lastpos = message.length()-1;
The difference between the two being that the first gives you the size of the string, and the second gives you the last index of the string (for example, "abcdefg", lastpos 1 would be 7, and lastpos 2 would be 6).
Finally, keep in mind, you can do something like
message.charAt(0);
to get the first index character of the string.
I have made 3 changes from the code that you have written. They are the following:
Read the message using kb.nextLine(); instead of "" + "\n";
The first character of the message is message.charAt(0) instead of "'."
To count the number of characters, you have given semicolon after the if condition. Remove that. The semicolon after if is not needed.
Check the snippet below for better understanding.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("What is your message? ");
String message = kb.nextLine();
System.out.println("\nYour message is " + " characters long.");
System.out.println("The first character is at position 0 and is '" + message.charAt(0));
int lastpos = 30;
System.out.println("The last character is at position " + lastpos + " and is '" + message.charAt(lastpos) + "'.");
System.out.println("\nHere are all the characters, one at a time:\n");
for (int i = 0; i < message.length(); i++) {
System.out.println("\t" + i + " - '" + message.charAt(i) + "'");
}
int a_count = 0;
for (int i = 0; i < message.length(); i++) {
char letter = message.charAt(i);
if (letter == 'a' || letter == 'A') {
a_count++;
}
}
System.out.println("\nYour message contains the letter 'a' " + a_count + " times. Isn't that interesting?");
}
}
Essentially i've isolated the issue, the int numpersons begins as 0. I take a user input to make it a particular number which is the array size, when the second method begins it takes the 0 again and then the array has an out of bounds exception. I want to pass it from one method to the next, or make them more successive, idk how to do this
thanks in advance
import java.util.Scanner;
public class BankApp {
Scanner input = new Scanner(System.in);
int numpersons = 0;
private SavingsAccount[] clients = new SavingsAccount[numpersons];
public BankApp() {
while (numpersons < 1) {
System.out.println("How many people are there?");
numpersons = input.nextInt();
if (numpersons < 1 || 2147483647 < numpersons) {
System.out.println("invalid number, please enter again");
}
}
input.nextLine();
}
public void addClients() {
int i = 0;
while (i < numpersons) {
System.out.println("enter account id " + (i + 1));
String AccountID = input.nextLine();
System.out.println("enter account name " + (i + 1));
String AccountName = input.nextLine();
System.out.println("enter account balance " + (i + 1));
Double AccountBalance = input.nextDouble();
clients[i] = new SavingsAccount(AccountID, AccountName, AccountBalance);
input.nextLine();
i++;
}
}
public void displayClients() {
int i = 0;
while (i < numpersons) {
System.out.println("======================================");
System.out.println("Account ID " + (i + 1) + ": " + clients[i].getID());
System.out.println("Account Name " + (i + 1) + ": " + clients[i].getName());
System.out.println("Account Balance " + (i + 1) + ": " + clients[i].getBalance());
System.out.println("======================================");
i++;
}
}
public static void main(String args[]) {
BankApp ba = new BankApp();
ba.addClients();
ba.displayClients();
}
}
I've been working on a small bit of code that helps me calculate performance of a movie's Box-Office weekend. I want it to require the
Name of the movie
How much it'll cost to use
How much it's predicted to make that weekend
Then I want it to output all the above information, with the addition of each movie's performance. Well, I'm having issues with it saving multiple String[] values as well as int[] values. I can remove the String lines, and all the int[]'s (both the price and the prediction) work fine, or I can remove the int[]'s and the String[] works fine. Can anyone help me find my errors?
import java.util.*;
public class FMLArrays {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String[] movieName = new String[15];
int[] moviePrice = new int[15];
int[] moviePrediction = new int[15];
int[] moviePreformance = new int[15];
for (int i = 0; i < movieName.length; i++) {
System.out.print("Enter the name of movie " + (i+1) + ": ");
movieName[i] = console.nextLine();
System.out.print("Enter the price of movie " + (i+1) + ": ");
moviePrice[i] = console.nextInt();
System.out.print("Enetr the prediction of movie " + (i+1) + ": ");
moviePrediction[i] = console.nextInt();
moviePreformance[i] = Math.round(((moviePrediction[i] * 1000000) / moviePrice[i]) * 100) / 100;
System.out.println();
}
for (int i = 0; i < movieName.length; i++) {
System.out.println();
System.out.println("Name: " + movieName[i]);
System.out.println("Price: $" + moviePrice[i]);
System.out.println("Prediction: $" + moviePrediction[i] + " million");
System.out.println("Preformance: $" + moviePreformance[i]);
}
}
}
When you used nextInt() and entered a number you also enterd a new line character, so the next time you called nextLine() this new line character was your next input waiting.
You could fix this by always using nextLine, or by adding a call for nextLine.
import java.util.*;
public class FMLArrays {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String[] movieName = new String[2];
int[] moviePrice = new int[2];
int[] moviePrediction = new int[2];
int[] moviePreformance = new int[2];
for (int i = 0; i < movieName.length; i++) {
System.out.print("Enter the name of movie " + (i+1) + ": ");
movieName[i] = console.nextLine();
System.out.print("Enter the price of movie " + (i+1) + ": ");
moviePrice[i] = Integer.parseInt(console.nextLine());
System.out.print("Enetr the prediction of movie " + (i+1) + ": ");
moviePrediction[i] = Integer.parseInt(console.nextLine());
moviePreformance[i] = Math.round(((moviePrediction[i] * 1000000) / moviePrice[i]) * 100) / 100;
System.out.println();
}
for (int i = 0; i < movieName.length; i++) {
System.out.println();
System.out.println("Name: " + movieName[i]);
System.out.println("Price: $" + moviePrice[i]);
System.out.println("Prediction: $" + moviePrediction[i] + " million");
System.out.println("Preformance: $" + moviePreformance[i]);
}
}
}
This should fix the issue:
moviePrice[i] = console.nextInt();
console.nextLine();
moviePrediction[i] = console.nextInt();
console.nextLine();
console.nextInt() only reads the number, not the rest of the line, like carriage return.
case 2:
System.out.println("Please enter Book ID: ");
String userinput2 = sc.next();
for (int i = 0; i < myBooks.size(); i++) {
if (myBooks.get(i).getBookID().contains(userinput2)) {
System.out.println("BookID: " + myBooks.get(i).getBookID() + "\nTitle: "
+ myBooks.get(i).getTitle() + "\nAuthor: " + myBooks.get(i).getAuthor());
System.out.println("Please enter new details of book");
System.out.println("Title: ");
String userinput7 = sc.next();
myBooks.get(i).setTitle(userinput7);
System.out.println("Author: ");
String u1 = sc.next();
myBooks.get(i).setAuthor(u1);
myBooks.get(i).setOnLoan(false);
myBooks.get(i).setNumLoans(0);
System.out.println("---------------------------------------------------");
System.out.println("The book has been successfully updated");
System.out.println("Book ID: " + myBooks.get(i).getBookID() + " " + "\nTitle: "
+ myBooks.get(i).getTitle() + " " + "\nAuthor: " + myBooks.get(i).getAuthor());
System.out.println("---------------------------------------------------");
}
else { System.out.println("Please enter a correct bookID");
}
}
I'm having a problem with my validation check. If the user enters a bookID that doesn't exist, instead of printing out "please enter a correct bookID" once, it prints it out 4 times, which amounts to the number of objects i have in the array list. Is there a way to sort this?
Your else statement is in the middle of the for statement
for (int i = 0; i < myBooks.size(); i++) {
if (myBooks.get(i).getBookID().contains(userinput2)) {
[[do stuff]]
}
else { System.out.println("Please enter a correct bookID");
}
}
It looks like it should be in the middle of the if statement
if (myBooks.get(i).getBookID().contains(userinput2)) {
for (int i=...) {
[[do stuff]]
}
}
else { System.out.println("Please enter a correct bookID");
}
Here is the main problem:
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at ExamAnalysis.main(ExamAnalysis.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:271)
The program compiles and runs. It's just that I am either getting the java.util.NoSuchElementException along with my five jother errors with (answer.charAt(i) == char) near the bottom. Here is my program:
import java.io.*;
import java.util.Scanner;
class ExamAnalysis
{
public static void main(String [] args) throws FileNotFoundException
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type the correct answers to the exam questions, one right after the other: ");
String answers = keyboard.nextLine();
System.out.println("Where is the file with all the student responses? ");
String responses = keyboard.nextLine();
Scanner read = new Scanner(new File(responses));
while (read.hasNextLine())
{
for (int i = 0; i <= 10; i++)
{
responses = read.nextLine();
int p = 1;
p += i;
System.out.println("Student " + p + " responses: " + responses.substring(0,10));
}
System.out.println("Thank you for the data on 9 students. Here's the analysis: ");
resultsByStudents(responses, answers);
analysis(responses);
}
}
public static void resultsByStudents(String responses, String answers)
{
System.out.println ("Student # Correct Incorrect Blank");
System.out.println ("~~~~~~~~~ ~~~~~~~ ~~~~~~~~~ ~~~~~");
int student = 0;
int correct = 0;
int incorrect = 0;
int blank = 0;
for (int i = 0; i <= 9; i++)
{
for (int j = 0; j <= responses.length(); j++)
{
if ((responses.charAt(j)) == answers.charAt(j))
correct++;
else if ((responses.charAt(j)) != answers.charAt(j))
incorrect++;
else
blank++;
}
System.out.println(student + " " + correct + " " + incorrect + " " + blank);
student++;
}
}
public static void analysis(String responses)
{
System.out.println("QUESTION ANALYSIS (* marks the correct response)");
System.out.println("~~~~~~~~~~~~~~~~~");
//stores the percentage of each choice chosen
double A = 0;
double B = 0;
double C = 0;
double D = 0;
double E = 0;
double X = 0;
// tallys every variable chosen per question
for (int i = 0; i <= 10; i++) // go through all the questions
{
for (int j = 0; j <= responses.charAt(i); j++) //go through all the student responses
{
// variable that are being tallied
int chooseA = 0;
int chooseB = 0;
int chooseC = 0;
int chooseD = 0;
int chooseE = 0;
int chooseBlank = 0;
//variables take percentage of choices that have been chosen from each student
A = chooseA/9;
B = chooseB/9;
C = chooseC/9;
D = chooseD/9;
E = chooseE/9;
X = chooseBlank/9;
// variables that will print the asterisk with certain character of correct answer
String a = "A";
String b = "B";
String c = "C";
String d = "D";
String e = "E";
String blank = "blank";
if (responses.charAt(j) == A)
chooseA++;
else if (responses.charAt(j) == B)
chooseB++;
else if (responses.charAt(j) == C)
chooseC++;
else if (responses.charAt(j) == D)
chooseD++;
else if (responses.charAt(j) == E)
chooseE++;
else
chooseBlank++;
System.out.println("Question #" + i);
if (answers.charAt(i) == 'A') a = "A*"; // answers cannot be resolved(I already made it a global variable in my main method.)
else if (answers.charAt(i) == 'B') b = "B*";// answers cannot be resolved
else if (answers.charAt(i) == 'C') c = "C*";// answers cannot be resolved
else if (answers.charAt(i) == 'D') d = "D*";// answers cannot be resolved
else if (answers.charAt(i) == 'E') e = "E*";// answers cannot be resolved
System.out.println(a + " " + b + " " + c + " " + d + " " + e + " " + blank);
System.out.println (chooseA + " " + chooseB + " " + chooseC + " " + chooseD + " " + chooseE + " " + chooseBlank );
System.out.println (A + " " + B + " " + C + " " + D + " " + E + " " + X);
}
}
}
}
while (read.hasNextLine())
{
for (int i = 0; i <= 10; i++)
{
responses = read.nextLine();
int p = 1;
p += i;
System.out.println("Student " + p + " responses: " + responses.substring(0,10));
}
System.out.println("Thank you for the data on 9 students. Here's the analysis: ");
resultsByStudents(responses, answers);
analysis(responses);
}
}
Your logic here is confusing you. read.nextLine(); "Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line."
So you are saying, does it have a line? If so, read the next 10...well...11 lines, which isn't what you want. You don't know if there are 11 lines past this point. Don't know what that text file looks like, but you will want to restructure this part to either say, "While it has a next line", or "Read 11 lines"
Remove the for loop may resolve the issue. You are checking only once by using while(hasNextLine() ) but calling read.nextLine() 10 times in for loop.
for (int i = 0; i <= 10; i++)
{
responses = read.nextLine();
.......
}
int i = 0;
int numberOfStudents = 9;
while (i < numberOfStudents && read.hasNextLine()){
responses = read.nextLine();
i++;
System.out.println("Student " + i + " responses: " + responses.substring(0,10));
}
System.out.println("Thank you for the data on "+ numberOfStudents +" students. Here's the analysis: ");
resultsByStudents(responses, answers);
analysis(responses);
i < numberOfStudents : makes the required number of inserts
read.hasNextLine() : checks if there is input from console. If not the program waits for input.
for (int i = 0; i <= 10; i++)
count from 0 -> 10 = 11 students