Looping String arrays : cannot find symbol error - java

I'm new to java and I'm banging my head against a wall with a task. I need to get this to work. Can anyone tell me where I went wrong? I need to write an application for Carl’s Carpentry that shows a user a list of available items: table, desk, dresser, or entertainment center. Allow the user to enter a string that corresponds to one of the options, and display the price as $250, $325, $420, or $600, accordingly. Display an error message if the user enters an invalid item. The program MUST contain parallel arrays.
import javax.swing.*;
public class CarpentryChoice
{
public static void main(String[] args)
{
String entry;
String [] item = {"table","desk","dresser","entertainment center"};
int [] price = {250, 325, 420, 600};
String strPiece;
int x, fi = 99;
String prompt = "Please select an item\n" +
"Our furniture is:\n" + "Table\n" +
"Desk\n" +
"Dresser\n" +
"Entertainment center\n" +
"Enter an item letter";
entry = JOptionPane.showInputDialog(null, prompt);
entry = strPiece.ToString();
for(x = 0; x < item.length; ++x)
if(strPiece == item[x])
fi = x;
if(fi == 99)
JOptionPane.showMessageDialog(null,
"Invalid item code entered");
else
{
if (fi > 2)
fi = fi - 3;
JOptionPane.showMessageDialog(null, "Furniture item " +
strPiece + " is priced at $" +
price[fi]);
}
System.exit(0);
}
}
Any help is MUCH appreciated!!
Thanks!

It is toString instead of ToString.
Why are you assigning entry twice? The second assignment will override what the user input via the prompt dialog. You don't need the variable strPiece in this case. You can just use entry:
entry = JOptionPane.showInputDialog(null, prompt);
for(x = 0; x < item.length; ++x)
To compare Strings, use the equals instead of the == operator:
if(entry.equals(item[x]))
And in the part that displays the result dialog, use entry again instead of strPiece (simply remove strPiece from the entire code):
JOptionPane.showMessageDialog(null, "Furniture item " +
entry + " is priced at $" +
price[fi]);

Related

How to check user input is part of the array in Java

I wanna ask if this is possible. So I have this program will enter a for loop to get the user input on number of subjects. Then after he will enter the subjects listed in the array as his guide. My goal is that I want to check his subjects if it is really inside the array that I made. I made a program but I don't know where to put the part that the program will check the contents.
My goal:
Enter the corresponding code for the subjects you have chosen: user will input 8
Enter the number of subjects you wish to enroll: be able to type the whole subject name like (MATH6100) Calculus 1
then the program will check if the subjects entered are part of the elements inside the array
UPDATE:
I have made another but the problem is that I don't know where to put the code fragment wherein it will check the contents of the user input for list of subjects he wish to enroll.
Here is the code:
private static void check(String[] arr, String toCheckValue){
boolean test=Arrays.asList(arr).contains(toCheckValue);
System.out.println("Is/Are " + toCheckValue + " present in the array: " + test);
}
public static void main(String[] args){
String arr[]={"(MATH6100) Calculus 1", "(ITE6101) Computer Fundamentals", "(ITE6102) Computer Programming 1", "(GE6100) Understanding the Self", "(GE6106) Purposive Comunication 1", "(ETHNS6101) Euthenics 1", "(PHYED6101) Physical Fitness", "(NSTP6101) National Service Training Program 1"};
Scanner input1=new Scanner(System.in);
System.out.print("\nEnter the number of subjects you wish to enroll: ");
int number_subjects1=input1.nextInt();
String []subjects1=new String[number_subjects1];
//else statement when user exceeds the number of possible number of subjects
if(number_subjects1<=8){
for(int counter=0; counter<number_subjects1; counter++){
System.out.println("Enter the corresponding code for the subjects you have chosen (EX. MATH6100): " + (counter+1));
subjects1[counter]=input1.next();
}
String toCheckValue=subjects1[0];
System.out.println("Array: " +Arrays.toString(arr));
check(arr, toCheckValue);
System.out.println("\nPlease check if these are your preferred subjects:");
for(int counter=0; counter<number_subjects1; counter++){
System.out.println(subjects1[counter]);
}System.out.println("********************************** \n" + "\tNothing Follows");
System.out.print("\nIf you have enter some errors please press Y and refresh the form (Y/N): ");
Scanner character=new Scanner(System.in);
String answer_1subjectserrors=character.nextLine();
System.out.println(answer_1subjectserrors + "Based on your answer, you need to refresh thae page and try again.");
}
}
}
I believe the issue is that you are checking your class course codes against an array which contains both the class code AND the class description.
You ask the user to enter the class code but then you use that code to check for its existence in an array containing both the code & description. The contains in List (collections) is not the same as the contains in String.
I have slightly modified your code so you may get the desired result.
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class SOQuestion {
private static void check(String[] arr, String toCheckValue){
List courses = Arrays.asList(arr);
boolean test=courses.contains(toCheckValue);;
System.out.println("Is/Are " + toCheckValue + " present in the array: " + test);
}
public static void main(String[] args) {
String class_codes_and_descriptions[] = { "(MATH6100) Calculus 1", "(ITE6101) Computer Fundamentals", "(ITE6102) Computer Programming 1",
"(GE6100) Understanding the Self", "(GE6106) Purposive Comunication 1", "(ETHNS6101) Euthenics 1",
"(PHYED6101) Physical Fitness", "(NSTP6101) National Service Training Program 1" };
String class_codes[] = { "MATH6100", "ITE6101", "ITE6102","GE6100", "GE6106", "ETHNS6101","PHYED6101", "NSTP6101" };
Scanner input1 = new Scanner(System.in);
System.out.print("\nEnter the number of subjects you wish to enroll: ");
int number_subjects1 = input1.nextInt();
String[] subjects1 = new String[number_subjects1];
// else statement when user exceeds the number of possible number of subjects
if (number_subjects1 <= 8) {
for (int counter = 0; counter < number_subjects1; counter++) {
System.out.println("Enter the corresponding code for the subjects you have chosen (EX. MATH6100): "
+ (counter + 1));
subjects1[counter] = input1.next();
}
String toCheckValue = subjects1[0];
System.out.println("Array: " + Arrays.toString(class_codes_and_descriptions));
check(class_codes, toCheckValue);
System.out.println("\nPlease check if these are your preferred subjects:");
for (int counter = 0; counter < number_subjects1; counter++) {
System.out.println(subjects1[counter]);
}
System.out.println("********************************** \n" + "\tNothing Follows");
System.out.print("\nIf you have enter some errors please press Y and refresh the form (Y/N): ");
Scanner character = new Scanner(System.in);
String answer_1subjectserrors = character.nextLine();
System.out.println(
answer_1subjectserrors + "Based on your answer, you need to refresh the page and try again.");
}
}
}
When you are debugging always try to break down the statements into steps so you know where the error is. For example instead of boolean test=Arrays.asList(arr).contains(toCheckValue);
break it down to two steps like this :
List courses = Arrays.asList(arr);
boolean test=courses.contains(toCheckValue);
That way you will have an easier time checking for issues.
Second request is to always look at the API. Skim over the API to look at the method that you are using to understand it better.
For example if you are using contains method of List then look up the API here:
https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/List.html#contains(java.lang.Object)
Of course since this is Oracle's Java the explanation is imprecise & not straightforward but it is usually helpful.
I would recommend using a different data structure than plain arrays. Since you are already using List why not use another collections data structure like HashMap?
The original poster may want to look at a slightly refactored and cleaned up version of the code & try to figure out how to check for all courses since that is his next question. I believe that should become obvious with a more refactored code:
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class SOQuestion {
public static String class_codes_and_descriptions[] = { "(MATH6100) Calculus 1", "(ITE6101) Computer Fundamentals", "(ITE6102) Computer Programming 1",
"(GE6100) Understanding the Self", "(GE6106) Purposive Comunication 1", "(ETHNS6101) Euthenics 1",
"(PHYED6101) Physical Fitness", "(NSTP6101) National Service Training Program 1" };
public static String class_codes[] = { "MATH6100", "ITE6101", "ITE6102","GE6100", "GE6106", "ETHNS6101","PHYED6101", "NSTP6101" };
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int desired_number_of_subjects = input_desired_number_of_subjects(input);
String[] desired_subjects = enter_subjects(desired_number_of_subjects, input);
String toCheckValue = desired_subjects[0];
System.out.println("Array: " + Arrays.toString(class_codes_and_descriptions));
check(class_codes, toCheckValue);
pls_confirm_desired_subjects(desired_number_of_subjects, desired_subjects);
System.out.println("********************************** \n" + "\tNothing Follows");
System.out.print("\nIf you have enter some errors please press Y and refresh the form (Y/N): ");
Scanner character = new Scanner(System.in);
String answer_1subjectserrors = character.nextLine();
System.out.println(
answer_1subjectserrors + "Based on your answer, you need to refresh the page and try again.");
}
private static int input_desired_number_of_subjects(Scanner input) {
System.out.print("\nEnter the number of subjects you wish to enroll: ");
int take_number_of_subjects = input.nextInt();
// TODO: else statement when user exceeds the number of possible number of subjects
return take_number_of_subjects;
}
private static String[] enter_subjects(int desired_subjects_count , Scanner input_desired_subjects) {
String[] subjects_totake = new String[desired_subjects_count];
if (desired_subjects_count <= 8) {
for (int counter = 0; counter < desired_subjects_count; counter++) {
System.out.println("Enter the corresponding code for the subjects you have chosen (EX. MATH6100): "
+ (counter + 1));
subjects_totake[counter] = input_desired_subjects.next();
}
}
return subjects_totake;
}
private static void check(String[] arr, String toCheckValue){
List courses = Arrays.asList(arr);
boolean test=courses.contains(toCheckValue);
System.out.println("Is/Are " + toCheckValue + " present in the array: " + test);
}
private static void pls_confirm_desired_subjects(int take_number_of_subjects, String[] take_subjects) {
System.out.println("\nPlease check if these are your preferred subjects:");
for (int counter = 0; counter < take_number_of_subjects; counter++) {
System.out.println(take_subjects[counter]);
}
}
}
I will shortly edit the above but a hint is : you can use a for loop to go over the entered desired_subjects array and do a check on each one of the subjects, perhaps?
The following checks for all the courses (though this is not how I would check the courses)
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class SOQuestion {
public static String class_codes_and_descriptions[] = { "(MATH6100) Calculus 1", "(ITE6101) Computer Fundamentals", "(ITE6102) Computer Programming 1",
"(GE6100) Understanding the Self", "(GE6106) Purposive Comunication 1", "(ETHNS6101) Euthenics 1",
"(PHYED6101) Physical Fitness", "(NSTP6101) National Service Training Program 1" };
public static String class_codes[] = { "MATH6100", "ITE6101", "ITE6102","GE6100", "GE6106", "ETHNS6101","PHYED6101", "NSTP6101" };
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int desired_number_of_subjects = input_desired_number_of_subjects(input);
String[] desired_subjects = enter_subjects(desired_number_of_subjects, input);
check_all_desired_subjects(desired_subjects);
pls_confirm_desired_subjects(desired_number_of_subjects, desired_subjects);
System.out.println("********************************** \n" + "\tNothing Follows");
System.out.print("\nIf you have enter some errors please press Y and refresh the form (Y/N): ");
Scanner character = new Scanner(System.in);
String answer_1subjectserrors = character.nextLine();
System.out.println(
answer_1subjectserrors + "Based on your answer, you need to refresh the page and try again.");
}
private static int input_desired_number_of_subjects(Scanner input) {
System.out.print("\nEnter the number of subjects you wish to enroll: ");
int take_number_of_subjects = input.nextInt();
// TODO: else statement when user exceeds the number of possible number of subjects
return take_number_of_subjects;
}
private static String[] enter_subjects(int desired_subjects_count , Scanner input_desired_subjects) {
String[] subjects_totake = new String[desired_subjects_count];
if (desired_subjects_count <= 8) {
for (int counter = 0; counter < desired_subjects_count; counter++) {
System.out.println("Enter the corresponding code for the subjects you have chosen (EX. MATH6100): "
+ (counter + 1));
subjects_totake[counter] = input_desired_subjects.next();
}
}
return subjects_totake;
}
private static void check_all_desired_subjects(String[] desired_subjects) {
System.out.println("Array: " + Arrays.toString(class_codes_and_descriptions));
for (String subject_code_to_check:desired_subjects ) {
check(class_codes, subject_code_to_check);
}
}
private static void check(String[] arr, String toCheckValue){
List courses = Arrays.asList(arr);
boolean test=courses.contains(toCheckValue);
System.out.println("Is/Are " + toCheckValue + " present in the array: " + test);
}
private static void pls_confirm_desired_subjects(int take_number_of_subjects, String[] take_subjects) {
System.out.println("\nPlease check if these are your preferred subjects:");
for (int counter = 0; counter < take_number_of_subjects; counter++) {
System.out.println(take_subjects[counter]);
}
}
}

How to do I link keyboard with a object in an arraylist?

I'm very new to Java and I am a noob at it. I am creating a basic game where you can cast a spell on a player, location or item. What I am trying to do at this moment is for the player to cast a spell on something using keyboard input which I have done to a certain degree. when I enter the number for the spell I want to cast it says "You have picked spell 1" but what I want it to say is "You have picked spell Fireball" (Spell 1 is the Fireball Spell". Here is my code for the function:
for (Spell s: playerSpells) {
System.out.println(playerSpells.indexOf(s)+1 + ". " + s); //prints out the player's personal spellbook, each numbered and you can pick which spell you want to cast
for (int i = 0; i < 5; i++) { }
}
String keyboardInput = (String) Utilities.getInput();
int myInt = Integer.parseInt(keyboardInput);
System.out.println("You have picked spell" +" " + keyboardInput +p.getSpells());
for (int i = 0; i < 5; i++) {
```

Java FXML TextArea.setText() Stops Working

I am trying to update a TextArea in my Java FXML program and am encountering a weird problem. I am able to update the instructions 2 times but on the third instance of the same update call the text field will not update. I am using the same method call for all updates and have gotten what should be displayed to print in the console, so I know the problem is with the TextArea update. Here is the code causing the problem:
private void freedomCheck(){ // method for starting out a composition, choosing "mode"
decisionIndex = 0;
this.addChord("I"); //initialize first chord to "I"
prompt[0] = "Please enter your degree of freedom: 1, 2, 3, or 4."; //display prompt
prompt[1] = "1: Composes and plays for you";
prompt[2] = "2: Fill in just notes with chords given to you";
prompt[3] = "3: Fill in chords and notes, with software giving you options for both";
prompt[4] = "4: Fill in chords and notes with full independence";
prompt(); // get user input (can be changed to button press, etc.
}
private void prompt(){
String displayString = "";
for(int i=0;i<5;i++){
displayString += prompt[i] + "\n";
}
setInstructions(displayString);
System.out.println(displayString);
}
public void setInstructions(String newString){
instruction_text.setText(newString);
}
The prompt[] array is used to quickly separate lines of text. This section of the code works and prints correctly on the display, but later when I try to update it with the same prompt() call:
public void promptNotes(){
decisionIndex = 4;
int index;
if (composition.noteLength() == 0)
index = composition.getSize() - 1;
else index = composition.noteLength();
prompt[0] = "The current chord is " + composition.getChord(index).getName() + "; please pick a note:";//prompt
Chord temp = composition.getChord(composition.getSize()-1);
ArrayList<Note> candidates = temp.getOfferedNotes();
int notesLen = candidates.size(); //length of notes list for current chord
for(int i = 1; i < 5; i++){
tempNotes[i] = candidates.get(notesLen - i);
prompt[i] = (i+1) + ": " + tempNotes[i].getName();
}
prompt();
}
The correct output is printed to the console, but the textArea does not update.

How do i fix this simple program? guessing game

Hello please please please can someone help me. I am writing a program where the user can enter a maximum number for a guessing game and using a random generator he/she would have to guess the number from 1-to the max number. i have done most of it but i am stuck on how to loop back the program to enter another input if user say enters a letter or anything else apart from an integer. From the "do" part is where i get confused!
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JOptionPane;
public class guessinggame { // class name
public static void main(String[] args) { // main method
String smax = JOptionPane.showInputDialog("Enter your maximum number for the Guessing Game:");
int max = Integer.parseInt(smax);
do {
if (max > 10000) {
JOptionPane.showMessageDialog(null, "Oh no! keep your choice below 10000 please.");
smax = JOptionPane.showInputDialog("Enter your maximum number for the Guessing Game:");
max = Integer.parseInt(smax);
}
} while (max > 10000);
int answer, guess = 0, lowcount = 0, highcount = 0, game;
String sguess;
Random generator = new Random();
answer = generator.nextInt(max) + 1;
ArrayList<String> buttonChoices = new ArrayList<String>(); // list of string arrays called buttonChoices
buttonChoices.add("1-" + max + " Guessing Game");
Object[] buttons = buttonChoices.toArray(); // turning the string arrays into objects called buttons
game = JOptionPane.showOptionDialog(null, "Play or Quit?", "Guessing Game",
JOptionPane.PLAIN_MESSAGE, JOptionPane.QUESTION_MESSAGE,
null, buttons, buttonChoices.get(0));
do {
sguess = JOptionPane.showInputDialog("I am thinking of a number between 1 and " + max + ". Have a guess:");
try {
guess = Integer.parseInt(sguess);
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null, "That was not a number! ");
}
if (guess < answer) {
JOptionPane.showMessageDialog(null, "That is too LOW!");
lowcount++;
} else {
JOptionPane.showMessageDialog(null, "That is too HIGH!");
highcount++;
}
break;
} while (guess != answer);
JOptionPane.showMessageDialog(null, "Well Done!" + "\n---------------" + "\nThe answer was " + answer + "\nLow Guesses: " + lowcount
+ "\nHigh Guesses: " + highcount + "\n\nOverall you guessed: " + (lowcount + highcount) + " Times");
System.exit(0);
}
}
First thing's first, the break in the last do-while. If you break without condition inside a loop; it's not a loop; it's a single-execution block.
Other than that, you should, in areas where you're validating input, follow this structure. (pseudo code so you can implement).
Do-While input does not equal answer
Get input from user with dialogue
Begin Try
Parse user input
If input > answer
Notify user
Else-If input < answer
Notify user
End Try
Begin Catch Parse error
Alert user of invalid input
End Catch
End While

What's wrong with my code and/or logic?

I having some trouble with an APCS assignment. The program is supposed to read strings with a length of two from a text file - test1.txt - and print out percentages of: a) girl-girl, boy-boy, boy-girl or girl-boy combinations, and b) the total number of individual groups.
I've been trying for an hour to figure this out! Although I'm suspicious of the String declaration in line 25, I don't have a way to confirm that. Furthermore, I'm worried that I messed up my if-else-if-else loop without prompting a compiler error.
The source code is attached for your reference. If you need any additional information, please don't hesitate to ask.
Since I'm a new user with a reputation < 10, please see the attached image:
For elaboration on what isn't working. I took a screenshot and wrote relevant comments on it!
/**
* Family takes user input of sets of boys, girls, and boys + girls. Results are then
* tabulated and displayed in a percentage form to the user. The total number of
* individuals are also displayed.
*
* #E. Chu
* #Alpha
*/
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class Family {
public static void main (String[] args) throws IOException {
int boyCount = 0;
int girlCount = 0;
double boyGroupCount = 0.0;
double girlGroupCount = 0.0;
int mixedGroupCount = 0;
int totalPersonCount = 0;
double totalGroupCount;
String currentToken = " ";
Scanner inFile = new Scanner (new File ("test1.txt"));
while (inFile.hasNextLine()) {
currentToken = inFile.nextLine( );
if (currentToken == "BG") {
boyCount++;
girlCount++;
mixedGroupCount++; }
else if (currentToken == "GB") {
boyCount++;
girlCount++;
mixedGroupCount++; }
else if (currentToken == "BB") {
boyCount += 2;
boyGroupCount++; }
else {
girlCount += 2;
girlGroupCount++; }
}
inFile.close();
totalPersonCount = boyCount + girlCount;
totalGroupCount = boyGroupCount + girlGroupCount + mixedGroupCount;
System.out.println("Sample Size: " + totalPersonCount);
System.out.println("Two Boys (%): " + boyGroupCount / totalGroupCount + "%");
System.out.println("One Boy, One Girl (%): " + mixedGroupCount + "%");
System.out.println("Two Girls (%): " + girlGroupCount / totalGroupCount + "%");
} // End of main method.
} // End of class Family.
currentToken == "BB" should be currentToken.equals("BB")
Don't use == use the method equals instead
Hint: you don't want to compare strings using ==, look into the equals method.

Categories

Resources