Java: Storing an array before sorting [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to get this beginning part of my program to work the way I want it to before I move on and it's driving me crazy. In an attempt to receive 5 inputs for book title, author, page count, I'm receiving 6 for book title, 5 for author, and 5 for pg count. My end result is to just have each array with 5 inputs for each stored so I can organize them based on what the user requests. Do you see what I'm doing wrong? Thanks.
String[] titleChoice = new String[5];
String title = "", titleString = "";
String[] authorChoice = new String[5];
String author = "", authorString = "";
String[] pageChoice = new String[5];
String page = "", pageString = "";
String currentTitle;
String formatEntry;
int x = 0;
int numEntered;
int highestTitle = titleChoice.length - 1;
int highestAuthor = authorChoice.length - 1;
int highestPage = pageChoice.length - 1;
final int MAX_ARRAY_SIZE = 5;
boolean notQuit = false;
Arrays.fill(titleChoice, "zzzzzzzzzzz");
Arrays.fill(authorChoice, "zzzzzzzzzzz");
Arrays.fill(pageChoice, "zzzzzzzzzzz");
do
{
currentTitle = JOptionPane.showInputDialog(null, "Enter the title of a book, or zzz to
quit:");
if(!currentTitle.equals("zzz"))
{
titleChoice[x] = currentTitle;
authorChoice[x] = JOptionPane.showInputDialog(null, "Please enter "
+ titleChoice[x] + "'s author's last name: ");
pageChoice[x] = JOptionPane.showInputDialog(null, "Please enter "
+ titleChoice[x] + "'s page count: ");
x = x + 1;
}
else
JOptionPane.showMessageDialog(null, "You have elected to quit the program.
Goodbye.);
}
while(!currentTitle.equals("zzz"));
Receiving an ArrayIndexOutOfBoundsException for titleChoice[x] = currentTitle; as well. Not really sure how to remedy this.

The string in the else statement isn't closed, but besides that unless the user enters "zzz" on the 5th input the loop increments x and tries again with a nonexistent index. As suggested above while(!currentTitle.equals("zzz") && x < 5) should work because is limits the index to a number within the Array bounds (0 - 4).

If you want the program to stop asking for more than 5 titles add a further condition to the while:
while(!currentTitle.equals("zzz") && x < 5);
otherwise it will keep asking until you enter zzz.

I'm guessing your 6th book title is "zzz". They are entering a 6th title to quit but then you aren't running the section of code that generates an author and page so those both still have 5 entries.

Related

How can I store user input in arrays and then print them out? [duplicate]

This question already has answers here:
How do you save user input inside an array?
(3 answers)
Closed 3 years ago.
I am a beginner programmer and I am making a little application for practice.
You enter your budget, then you add an expense(name, amount)
and it subtracts and tells you your current budget.
I want to make it so you can see all of your expenses after each execution.
I have tried to make for loops that store the names of the expenses and then print them.
But I am doing something wrong :/.
Sorry for my bad English, I am from Croatia!
Here is some beginner ugly code.
int length = 0;
String[] listOfNames = new String[length];
boolean active = true;
int budget = 0;
Scanner input = new Scanner(System.in); //user input
System.out.println("Enter current budget in HRK");
int enteredAmount = input.nextInt(); //user input for budget
budget = enteredAmount;
while(active)
{
System.out.println("Current budget is " + budget + " HRK");
System.out.println("Enter expense name and amount");
System.out.println("Name: ");
String name = input.next(); //name of expense
for(int i=0; i<listOfNames.length;i++){ //adds entered expense names to array
listOfNames[i] = name;
length++;
}
System.out.println("Amount: ");
int enteredAmount1 = input.nextInt();
budget -= enteredAmount1; // subtracts the budget from the users input
System.out.println("Expense: " + name + ", Amount: " + enteredAmount1); // prints final result
for(int j=0; j<listOfNames.length; j++) // prints stored strings in array
{
System.out.println(listOfNames[j]);
}
}
}
}
Here are the issues:
You started the length of listOfNames at zero.
int length = 0;
String[] listOfNames = new String[length];
That's why the for loops never run.
Also, it is not possible to change the size of an array in Java.
To store a variable amount of input, I recommend an ArrayList, which can be resized.
ArrayList<String> listOfNames = new ArrayList<String>();
Adding something to listOfNames:
String name = input.next();
listOfNames.add(name);
The downside to an ArrayList is that it is less efficient than an array, but this doesn't really matter for your program.
Here is the documentation and another helpful website for ArrayLists.

Multiple Choice and True/False Quiz using loops [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to build a quiz for a user that has to have 5 multiple choice questions and 5 true/false questions. I must do this using loops (while loops). I've come to the point where I set up a separate method asking the user the questions and error checking for the true/false or multiple choice questions. I now have to somehow give the user a point if they answer each question correctly. Then in the end, I must give the user the the total amount of points they won. Then I have to ask if they want to play again in the end, if they say yes I have to go back to the first question and restart the game and if they say no the program has to close. Here is where I got to on my main method. I started putting a while loop for the first answer (correct answer being 3) and making a point variable but I'm not sure where to go from there and how to connect everything. I hope what I did so far is correct. Thanks!
UserInteraction input = new UserInteraction();
Questions ask = new Questions();
int answer1 = 0, answer2 = 0, answer3 = 0, answer4 = 0, answer5 = 0;
int a1 = ask.Question1(answer1);
int point;
while (a1==3)
{point = 1;
}
int a2 = ask.Question2(answer2);
int a3 = ask.Question3(answer3);
int a4 = ask.Question4(answer4);
int a5 = ask.Question5(answer5);
boolean answer6=false, answer7=false, answer8=false, answer9=false, answer10=false;
String a6 = ask.Question6(answer6);
String a7 = ask.Question7(answer7);
String a8 = ask.Question8(answer8);
String a9 = ask.Question9(answer9);
String a10 = ask.Question10(answer10);
For the Questions methods, I'll put two blank examples on here.
{public int Question1 (int answer1)
{String message = "";
int smallestValue = 1;
int largestValue = 4;
System.out.println("Q1) What is...?");
System.out.println("1: ....");
System.out.println("2: ......");
System.out.println("3: ......");
System.out.println("4: ......");
System.out.print("Enter the number");
Scanner input = new Scanner(System.in);
UserInteraction input2 = new UserInteraction();
answer1 = input2.getIntValueFromUserBetween(message, smallestValue, largestValue);
return answer1;
}
public String Question6(boolean answer10)
{String message = "";
System.out.println("(Q10) ....(true/false)");
System.out.print("Enter your answer here: ");
Scanner input = new Scanner(System.in);
UserInteraction input2 = new UserInteraction();
answer10 = input2.confirm(message);
return "" + answer10;
}
}
Sorry if I misunderstand your question, but I don't understand why you're using a loop here.
while (a1==3)
Your program is either going to get stuck here or never use it. What I mean is that if the user answers the question correctly (i.e 3), they will be stuck in the while loop until you set a1 != 3.
What I think is a better solution is using selection. For example:
if (a1 == 3) {
point += 1; // point = point + 1
// Or whatever functionality you need here
}
Edit: If you really must use a loop, then having a Boolean flag would be the way to go. For example:
Boolean flag = false;
if (a1 == 3) {
flag = true;
while (flag) {
point += 1; //point = point + 1
// Make sure that you set flag equals to false at the end of the loop though, otherwise it will infinitely loop
// Include any other functionality needed
flag = false;
}
}
Is this similar to what your looking for?
int correct;
public void quiz() { // this is so you can restart quiz easily
String[] answers = String[5];
//add answers to array, set them to variables/constant first then index
String[] questions = String[5];
// add questions to array
for(int i = 0; i <= questions.length; i++) { // stops after all questions have been asked, make sure its "<="
System.out.println(questions[i]); // prints question 1 first loop then 2 and so on
// read input from user
if(input == answers[i]) { // you may have to convert input to correct type
correct += 1;
}
}
}
System.out.println("You got " + correct + " correct answers");
System.out.println("Would you like to play again?");
if(input == yes) {
quiz(); //starts quiz again // starts quiz method again
P.S. sorry if I've misunderstood the question
To ask different questions you can just change the String variables then call quiz() to ask those questions. nice and simple :)

System.out.println does not work [duplicate]

This question already has answers here:
How to test for blank line with Java Scanner?
(5 answers)
Closed 7 years ago.
I am beginner in learning java programming. Basically, I can't make the last bit of my code to work. Before I show you my code, I think it is a good idea to show how the result should be. The result of the program should be:
Please Enter either S(supply) or R(replenish) followed by ID and quantity.
R p122. 10
New Stock-level for p122(Chain) is 58
S. p124. 20
New Stock-level for p125(Pedal) is 18
S. p905. 20
No part found with ID p905
.....// enter empty string to terminate
//Show final stock levels of all Parts
Although, I did be able to perform the main calculation and everything, I cannot print out the final stock levels of all Parts. I really don't understand why.
Here is my code:
import java.util.Scanner;
public class TestPart {
public static void main(String[] args) {
// Array of 5 Part objects
// Part[] part = new Part[5];
Part[] part = new Part[5];
part[0] = new Part("p122", "Chain", 48, 12.5);
part[1] = new Part("p123", "Chain Guard", 73, 22.0);
part[2] = new Part("p124", "Crank", 400, 11.5);
part[3] = new Part("p125", "Pedal", 3, 6.5);
part[4] = new Part("p126", "Handlebar", 123, 9.50);
///////// Test Class 2 ////////
Scanner scanner = new Scanner(System.in);
System.out.println("Please Enter either S (supply) or R (replenish) followed by ID and quantity.");
while (scanner.hasNext()) {
String sOrR = scanner.next();
String inputId = scanner.next();
int amount = scanner.nextInt();
for (int i = 0; i < 5; i++) {
String id = part[i].getID();
// Find ID in array
if (id.equals(inputId)) {
// S or R
if (sOrR.equals("R")) {
part[i].replenish(amount);
} else {
part[i].supply(amount);
}
System.out.println("New Stock-level for " + part[i].getID() + "(" + part[i].getName() + ") is "
+ part[i].getStockLevel());
}
}
if ((inputId.equals(part[0].getID()) == false) && (inputId.equals(part[1].getID()) == false)
&& (inputId.equals(part[2].getID()) == false) && (inputId.equals(part[3].getID()) == false)
&& (inputId.equals(part[4].getID()) == false)) {
System.out.println("No part found with ID " + inputId);
}
}
scanner.close();
System.out.println("Final stock level for all the parts: ");
for (int i = 0; i < 5; i++) {
System.out.println("Final Stock-level for " + part[i].getID() + "(" + part[i].getName() + ") is "
+ part[i].getStockLevel());
}
}
}
My program executes perfectly the calculating part. However it doesn't display final stocklevels.
Please Enter either S(supply) or R(replenish) followed by ID and quantity.
R p122. 10
New Stock-level for p122(Chain) is 58
S. p124. 20
New Stock-level for p125(Pedal) is 18
S. p905. 20
No part found with ID p905
Your abort condition (namely scanner.hasNext()) won't exit the while loop whenever the user enters an empty string. I don't know if you already noticed but whenever the user only hits the return key, nothing happens because Scanner.next does not trigger on return only. Though be aware that it stores your input. That means once you enter a "valid" input (such as abc), the Scanner will give you everything the user just entered before that valid input. Just a small example to demonstrate what I mean:
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()) {
System.out.println("\"" + scanner.next() + "\"");
}
scanner.close();
System.out.println("finished");
So, if you want to abort your program after the user entered an empty line, this is not possible with java.util.Scanner.hasNext. I recommend you add another character to your "S or R" option that allows the user to exit the program like this:
if(sOrR.equals("E")) break;
You should place this directly behind String sOrR = scanner.next();.

Java: How can I tell if one of my array String values is null?

After many failed attempts to alphabetically sort an array, I have realized my failure is most likely due to one of my String array values being null. I tried both Arrays.sort() & compareTo(), much like this user:
How to sort a String array alphabetically (without using compareTo or Arrays.sort)
...with the same results, most likely pointing to one of my values being null. How can I tell if one of my values is/are null? Is there a test? How did it get to be null? And most importantly, is this even the correct question to be asking? Thanks.
String[] titleChoice = new String[5];
String title = "", titleString = "";
String[] authorChoice = new String[5];
String author = "", authorString = "";
int[] pageChoice = new int[5];
String page = "", pageInt = "";
String currentTitle;
String currentPage = "";
String formatEntry;
int x = 0;
int numEntered;
int highestTitle = titleChoice.length - 1;
int highestAuthor = authorChoice.length - 1;
int highestPage = pageChoice.length - 1;
final int MAX_ARRAY_SIZE = 5;
boolean notQuit = true;
Arrays.fill(titleChoice, "zzzzzzzzzzz");
Arrays.fill(authorChoice, "zzzzzzzzzzz");
Arrays.fill(pageChoice, 99999999);
Scanner input = new Scanner(System.in);
do
{
System.out.print("Enter the title of a book, or zzz to quit:");
titleChoice[x] = input.next();
if(!titleChoice.equals("zzz"))
{
LibraryBook inputBook = new LibraryBook();
inputBook.setBook(titleChoice[x]);
LibraryBook inputAuthor = new LibraryBook();
System.out.print("Please enter " + titleChoice[x] + "'s author's last name: ");
authorChoice[x] = input.next();
inputAuthor.setAuthor(authorChoice[x]);
LibraryBook inputPages = new LibraryBook();
System.out.println("Please enter " + titleChoice[x] + "'s page count: ");
pageChoice[x] = input.nextInt();
inputPages.setPages(pageChoice[x]);
x = x + 1;
}
else
System.out.println("You have elected to quit the program. Goodbye.");
}
while(((!titleChoice.equals("zzz")) && x < 5) && ((!authorChoice.equals("zzz")) && x < 5)
&& ((!pageChoice.equals("zzz")) && x < 5));
//I just put this in here to see if it would compile
Arrays.sort(titleChoice[x]); }}
How can I tell if one of my values is/are null?
One way is to learn to read the stack trace that you are getting. (We could maybe help you with that, if you showed it to us.)
Another way is to test the value to see if it is null.
Is there a test?
Here is how you test a simple variable.
if (a == null) {
System.out.println("a is null");
}
If you have an array whose elements could be null, write a loop to test them. (There are more elegant ways ... but if you are learning, keep it simple.)
How did it get to be null?
The two ways are:
You assigned null to it.
It was null to start with, and you haven't assigned a non-null value to it. For example, new String[5]; creates a new String array whose values are initially all null.
And most importantly, is this even the correct question to be asking?
We can't tell you what the "correct" question is, because it depends on your mental state ... and we cannot read your mind.

The code isn't working for some reason [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm making a thingy that takes 3 inputs like "1500, 1 and 1" or "1500, January and 1" and returns "January 1st, 1500" or "1/1/1500", i had some problems on the day part but someone already told me how to fix it, and now I'm having problems with the month part, i made this kinda fast and i haven't figured out why it isn't working, it SHOULD see if the input is a valid month, if it is then it outputs the month(this part is just for testing), and if it isn't then it should say "please use a valid month or a number between 1 and 12", but when i write anything that isn't a month it just stops, and doesn't output anything, even if i put a month after it just doesn't do anything, i tried to see if there was any errors but i didn't found any, this is the code that i used:
Scanner scan = new Scanner(System.in);
String mx;
System.out.println("Insert Month");
String[] mm = {"january","february","march","april","may","june","july","august","september","october","november","december"};
int mz = 0;
while (0 < 1){
mx = scan.nextLine();
mx = mx.toLowerCase();
for(int i = 0; i < 11; i++){
if (mx.equals(mm[i])){
mz = i + 1;
break;
}
else {
if(i == 11){
System.out.println("please use a valid month or a number between 1 and 12");
}
else{
}
}
}
//}
if(mz > 0){
break;
}
else {}
}
System.out.println(mx);
The reason your program just "stops" is that you only print the statement "please enter a valid month..." if i == 11 and you have your for loop break if i >= 11. Thus, this condition will never be met. The while loop keeps running, even though this statement isnt printed. You could have entered a non-month string on the first try, and then a month string on the second and your while loop would have been broken.
Here is how I have improved your code to work for taking in the month. Pay attention to subtle changes of highlighted. These are important for writing better, more readable code:
Scanner scan = new Scanner(System.in);
//initialize to empty string
String mx = "";
System.out.println("Insert Month");
//use good naming conventions for easier code readability
String[] validMonths = {"january","february","march","april","may","june","july","august","september","october","november","december"};
//using a boolean to break makes much more sense than the way you have written it with an infinite loop and a manual break statement
boolean noMonth = true;
while (noMonth){
mx = scan.nextLine();
for(int i = 0; i < 12; i++){
//rather than convert to lowercase, use this handy String method
//also compares for valid number entries
if (mx.equalsIgnoreCase(validMonths[i]) || mx.equals(Integer.toString(i+1))){
noMonth = false;
break;
}
}
if(noMonth){
System.out.println("please use a valid month or a number between 1 and 12");
}
}
System.out.println(mx);
Create a new while loop to take in the day and a new one to take in the year after these, checking for valid input. Also, every if does not require an else in Java.
You're not using meaningful variable names, making your code a little bit hard to read and maintain. So, I had to create you the following code from scratch:
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String month = getMonthName(getInt("Enter Month: ", keyboard) - 1);
int day = getInt("Enter Day: ", keyboard);
int year = getInt("Enter Year: ", keyboard);
System.out.printf("%s %d, %d\n", month, day, year);
}
public static String getMonthName(final int monthNo)
{
String[] months = {"january","february","march","april","may","june","july","august","september","october","november","december"};
return months[monthNo];
}
public static int getInt(final String msg, Scanner keyboard)
{
System.out.print(msg);
return keyboard.nextInt();
}
The code above does NOT perform and input validation, as you may have noticed already. If you want to validate month input for example, your if condition may look something like this:
if (month < 0 || month < 12)
{
System.out.println("Invalid month number entered");
System.exit(0);
}

Categories