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");
}
Related
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.
At the moment my code is only giving me the first matching result. The user inputs their desired room price and at the moment it will only display the first match. In the case the user inputs '60' to the console it should display 3 results. I imagine i'll need another forloop and if statement after it prints to the console but not sure how to execute
public static void secondMain() {
BufferedReader reader;
var lines = new ArrayList<String>();
var rooms = new ArrayList<Room>();
Room selectedRoom = null;
try {
reader = new BufferedReader(new FileReader("rooms.txt"));
String line = reader.readLine();
lines.add(line);
while (line != null) {
line = reader.readLine();
lines.add(line);
}
reader.close();
for (int i = 0; i < lines.size() - 1; i++) {
String[] words = lines.get(i).split(" ");
var room = new Room();
room.roomNum = Integer.parseInt(words[0]);
room.roomType = (words[1]);
room.roomPrice = Double.parseDouble(words[2]);
room.hasBalcony = Boolean.parseBoolean(words[3]);
room.hasLounge = Boolean.parseBoolean(words[4]);
room.eMail = (words[5]);
rooms.add(room);
}
var searchRoomPrice = input.nextDouble();
for (int i = 0; i < rooms.size(); i++) {
if (rooms.get(i).roomPrice == searchRoomPrice) {
selectedRoom = rooms.get(i);
break;
}
}
System.out.println("Room Number: " + selectedRoom.roomNum);
System.out.println("Room Type: " + selectedRoom.roomType);
System.out.println("Room Price: " + selectedRoom.roomPrice);
System.out.println("Balcony: " + selectedRoom.hasBalcony);
System.out.println("Lounge: " + selectedRoom.hasLounge);
System.out.println("Email: " + selectedRoom.eMail);
System.out.println("-------------------");
} catch (Exception e) {
e.printStackTrace();
}
}
Any other information needed feel free to ask
If you only want to print the information move the print commands inside the loop and remove the break i.e.
for(int i = 0; i < rooms.size(); i++){
if(rooms.get(i).roomPrice == searchRoomPrice){
selectedRoom = rooms.get(i);
System.out.println("Room Number: " + selectedRoom.roomNum);
System.out.println("Room Type: " + selectedRoom.roomType);
System.out.println("Room Price: " + selectedRoom.roomPrice);
System.out.println("Balcony: " + selectedRoom.hasBalcony);
System.out.println("Lounge: " + selectedRoom.hasLounge);
System.out.println("Email: " + selectedRoom.eMail);
System.out.println("-------------------");
}
}
You could also save all the objects in a list with the first loop and then in a second loop iterate over the list and print the information i.e.
List<Room> roomList = new ArrayList<Room>();
for(int i = 0; i < rooms.size(); i++){
if(rooms.get(i).roomPrice == searchRoomPrice){
roomList.add(rooms.get(i));
}
}
for(Room room : roomList){
System.out.println("Room Number: " + room.roomNum);
System.out.println("Room Type: " + room.roomType);
System.out.println("Room Price: " + room.roomPrice);
System.out.println("Balcony: " + room.hasBalcony);
System.out.println("Lounge: " + room.hasLounge);
System.out.println("Email: " + room.eMail);
System.out.println("-------------------");
}
I notice 2 things:
You are using a break; here:
if(rooms.get(i).roomPrice == searchRoomPrice){
selectedRoom = rooms.get(i);
break;
}
So you are stopping the loop after the first match.
Here:
for (int i = 0; i < lines.size() - 1; i++)
Is there a reason to use that minus 1?
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();
}
}
After making an invalid entry, the invalid entry loop continues to appear in this program. I am seeking to keep asking the user for input until he/she enters valid data. Then I'd like to use that input to continue on with the program. I'm positive there's a type of loop associated with this. Thanks for your help.
identInput = JOptionPane.showInputDialog(null, "Please enter a student ID: ");
intID = Integer.parseInt(identInput);
savedIntID = Integer.parseInt(identInput);
for(x = 0; x < studentIDs.length; ++x)
{
if(identInput.equals(studentIDs[x]))
{
JOptionPane.showMessageDialog(null, "The first name associated with \nStudent ID "
+ intID + " is: " + firstNames[x] + "\n" + firstNames[x] + "'s current GPA is: "
+ gPAs[x]);
inputTruth = true;
break;
}
}
//The following will show up and continue to if the data is incorrect. Am not
//sure how to reuse if good data are entered.
while(inputTruth == false)
{
JOptionPane.showInputDialog(null, "The Student ID you entered "
+ savedIntID + "\nis not valid. \nPlease enter another Student ID: ");
}
inputTruth = false;
while(inputTruth == false)
{
identInput = JOptionPane.showInputDialog(null, "Please enter a student ID: ");
intID = Integer.parseInt(identInput);
savedIntID = Integer.parseInt(identInput);
for(x = 0; x < studentIDs.length; ++x)
{
if(identInput.equals(studentIDs[x]))
{
JOptionPane.showMessageDialog(null, "The first name associated with \nStudent ID "
+ intID + " is: " + firstNames[x] + "\n" + firstNames[x] + "'s current GPA is: "
+ gPAs[x]);
inputTruth = true;
break;
}
}
//The following will show up and continue to if the data is incorrect. Am not
//sure how to reuse if good data are entered.
if(inputTruth == false)
{
JOptionPane.showInputDialog(null, "The Student ID you entered "
+ savedIntID + "\nis not valid. \nPlease enter another Student ID: ");
}
}
You just Need a while loop
while(!isInputValid){
//Take your input
if(check == input){
isInputValid = true;
}else{
//Please enter valid input try again.
}
}
is this what you want ?
inputTruth = false;
while(inputTruth == false)
{
for(x = 0; x < studentIDs.length; ++x)
{
if(identInput.equals(studentIDs[x]))
{
JOptionPane.showMessageDialog(null, "The first name associated with \nStudent ID "
+ intID + " is: " + firstNames[x] + "\n" + firstNames[x] + "'s current GPA is: "
+ gPAs[x]);
inputTruth = true;
break;
}
}
if (inputTruth == false) {
identInput = JOptionPane.showInputDialog(null, "The Student ID you entered "
+ savedIntID + "\nis not valid. \nPlease enter another Student ID: ");
}
}
Ok guys so I'm stuck trying to write some code in java, I cant get the code to display the pricing option for fullsize. I can't get the program to continue onto the second option I have listed as Case 2.
The project basically gives the user the option to ask if he is renting a car [Y or N]:
if Y is inputed the next question
it ask is "Compact of Full-size?",
if the user selects compact the project displays that the user has selected compact and
if the code displays fullsize the project displays that the user has selected fullsize.
Then it asks the user if they have a coupon if the users answer Y for the coupon the price is 7% off of 30.50.
If the user answers N the price is a normal 30.50. The fullsize normal price is 40.50 and the price with a coupon is 7% off of 40.50. The following is the code i have written currently.
The code:
public class CarRental {
public static void main(String[] args) {
for (int i = 0; i < 4; i++) {
System.out.println("Programmed by .");
double standardCompact = 30.50;
double couponCompact = ((30.50) - (30.50 * 0.07));
double standardFullSize = 40.50;
double couponFullSize = ((40.50) - (40.50 * 0.07));
//Scanner Input
Scanner input = new Scanner(System.in);
System.out.print("Rent a Car? [Y or N]: ");
//Response String
String response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("You entered no. Bye. ");
} else if (response.equals("Y")) {
System.out.print("Compact or Full-Size? [C or F]: ");
//case1
response = input.next().toUpperCase();
if (response.equals("C")) {
System.out.println("You selected Compact. ");
} else if (response.equals("F")) {
System.out.println("You have selected Full-Size. ");
System.out.print("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is" + " " + standardCompact + " " + "per day.");
} else if (response.equals("Y")) {
System.out.println("Price is" + " " + couponCompact + " " + "per day.");
//case 2
response = input.next().toUpperCase();
if (response.equals("F")) {
System.out.println("You have selected Full-Size.");
System.out.println("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is" + " " + standardFullSize + " " + "per day.");
} else if (response.equals("Y")) {
System.out.println("Price is" + " " + couponFullSize + " " + "per day.");
}
}
}
You're missing some }s after your else clauses. Example:
response = input.next().toUpperCase();
if (response.equals("C")) {
System.out.println("You selected Compact. ");
//Put code that should only execute if you select Compact here.
}else if(response.equals("F")){
System.out.println("You have selected Full-Size. ");
//Put code that should only execute if you select Full-size here.
//Should have a } here!
//Put code that should always execute here.
Because you never close the block of code in the else clause, all of the code that follows is still part of the else, and therefore will only be executed if the else is selected, not under every circumstance as you had intended.
You are opening lots of brackets { but not closing them where you need }.
I usually not just handing the code, but I've noticed you done must of the job, but confused where to close the brackets and a little bit at the program flow.
I only changed it a bit, there is a lot that you can cut and reuse code.
public static void main(String[] args){
for(int i = 0; i < 4; i++) {
System.out.println("Programmed by .");
double standardCompact = 30.50;
double couponCompact = ((30.50)-(30.50 * 0.07));
double standardFullSize = 40.50;
double couponFullSize = ((40.50)-(40.50 * 0.07));
//Scanner Input
Scanner input = new Scanner(System.in);
System.out.print("Rent a Car? [Y or N]: ");
//Response String
String response = input.next().toUpperCase();
if (response.equals("N")){
System.out.println("You entered no. Bye. ");
}
else if (response.equals("Y")) {
System.out.print("Compact or Full-Size? [C or F]: ");
response = input.next().toUpperCase();
if (response.equals("C")) {
System.out.println("You selected Compact. ");
//case1
System.out.print("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is" + " " + standardCompact + " " + "per day.");
}
else if (response.equals("Y")) {
System.out.println("Price is" + " " + couponCompact + " " + "per day.");
}
}
else if(response.equals("F")) {
System.out.println("You have selected Full-Size. ");
//case 2
System.out.print("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is" + " " + standardFullSize + " " + "per day.");
}
else if (response.equals("Y")) {
System.out.println("Price is" + " " + couponFullSize + " " + "per day.");
}
}
}
}
}
The problem with this code is all your code is under the if statemente for Full-Size so the case 2 only executes when you select full-size , Yes to coupon and after showing the final message you press F again the code should look like this.
public class CarRental {
public static void main(String[] args){
for(int i=0; i<4; i++){
System.out.println("Programmed by .");
double standardCompact = 30.50;
double couponCompact = ((30.50)-(30.50 * 0.07));
double standardFullSize = 40.50;
double couponFullSize = ((40.50)-(40.50 * 0.07));
//Scanner Input
Scanner input = new Scanner(System.in);
System.out.print("Rent a Car? [Y or N]: ");
//Response String
String response = input.next().toUpperCase();
if (response.equals("N")){
System.out.println("You entered no. Bye. ");
}else if (response.equals("Y")) {
System.out.print("Compact or Full-Size? [C or F]: ");
//case1
response = input.next().toUpperCase();
if (response.equals("C")) {
System.out.println("You selected Compact. ");
System.out.print("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is" + " " + standardCompact + " " + "per day.");
} else if (response.equals("Y")) {
System.out.println("Price is" + " " + couponCompact + " " + "per day.");
}
//case 2
}else if(response.equals("F")){
System.out.println("You have selected Full-Size. ");
System.out.println("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is" + " " + standardFullSize + " " + "per day.");
} else if (response.equals("Y")) {
System.out.println("Price is" + " " + couponFullSize + " " + "per day.");
}
}
}
}
}
As you can see in the code above is really important to correctly close conditional blocks so the code really does what you expect it to do.
Using flow diagrams is a good support for learning how programming languages really work.