Hi,I'm having a problem with this. Here is the situation. There are 4 choices
[1]black
[2]red
[3]blue
For example, if the user choose any of this numbers code will print:
you choose black
here is my code so far
System.out.print("Course: \n[1] BSIT \n[2] ADGAT \n[3] BSCS \n[4] BSBA \n[5] NITE \n enter course:");
course=Integer.parseInt(input.readLine());
The problem is, when I call system.out.print(""+course); it prints the number and not the word itself?
You cannot print the course without any kind of datastructure. If you want to relate the number to some kind of data you need to do it yourself. For example store the names in an array:
String[] names = {"BSIT","ADGAT","BSCS","NITE"};
Then reference your array with corresponding lookup:
//...
int course = Integer.parseInt(input.readLine());
System.out.println("You chose: " + names[course-1]);
Remember that indexing starts from zero when working with arrays so we decrease by one.
What you do there:
1. You print out a sentence.
2. You let the user input a sentence, which you expect to contain a number and convert it as such.
The program itself has no clue that the first sentence you gave to the user is actually a selection of different things he should choose from.
What you need to to is to convert the number back to the thing it actually represented.
The easiest way would be a
String word;
switch(course) {
case 1: word = "BSIT"
break;
case 2: word = "ADGAT";
break;
case 3: word = "BSCS";
break;
case 4: word = "BSBA";
break;
case 5: word = "NITE";
break;
default:
throw new IllegalArgumentException("The choice '" + course + "' is not a valid one. Only 1-5 would be legal);
}
System.out.println("The course you've chosen is: " + word);
That's the most straight forward way to do it here, but actually not my favorite, because it duplicates the places where the mapping is done. I would prefer to actually tell the program what those things are, like:
private enum Courses {
BSIT(1), ADGAT(2), BSCS(3), BSBA(4), NITE(5);
private int userChoice;
private Courses(int theUserChoice) {
userChoice = theUserChoice;
}
public int getUserChoice() {
return userChoice;
}
public static fromUserChoice(int aChoice) {
for (Courses course: Courses.values() {
if (course.userChoice == aChoice) {
return course;
}
throw new IllegalArgumentException("The choice '" + course + "' is not a valid one. Only 1-5 would be legal);
}
}
}
private static String printCourseList() {
System.out.print("Courses: ");
for (Courses course: Courses.values()) {
System.out.print("[" + course.getUserChoice() + "] " + course.name() + " ");
}
System.out.println();
}
public static main(String[] args) {
printCourseList();
Courses course = Courses.fromUserChoice(Integer.valueOf(System.console().readLine()));
System.out.println("You're selected course is: " + course.name());
}
I prefer it that way because now the program actually knows that there is a special thing called 'Courses'. It knows that it is bound to a number and that some numbers might actually reflect a choice of a courses. It is done in a central place (the definition of the courses).
Hopefully this is not too much information and you'll see this as helpful.
use this
switch(course)
{
case 1:
System.out.println("black");
break;
case 2:
System.out.println("red");
break;
case 3:
System.out.println("blue");
break;
default:
System.out.println("invalide number"); // this will execute if course var does not equale to 1 , 2 or 3
break;
}
Related
Please help i have been stuck for a good part of an afternoon already and cant really find/understand answers from other resources. I need to receive a password input from the user and need to test whether or not the password contains:
Two Upper case letters
Three Lower case letters
One number
here is my code:
import javax.swing.JOptionPane;
public class PracticePassword {
public static void main(String[] args) {
String originalPw;
// TODO Auto-generated method stub
String newPw;
int pwLength;
int i;
char c;
newPw = JOptionPane.showInputDialog(null, "Please enter a password" +
" that contains the following:" + "\n"
+ "**TWO upper case letters" + "\n" + "**THREE lower case letters" + "\n"
+ "**ONE number");
originalPw = newPw;
pwLength = newPw.length();
for (i = 0; i <= pwLength; i++) {
boolean hasUpperCase = !originalPw.equals(originalPw.toUpperCase());
boolean hasLowerCase = !originalPw.equals(originalPw.toUpperCase());
if(!hasUpperCase){
System.out.println("You have three upper case letters, good job.");
}
else {
System.out.println("You must have three upper case letters");
}
}
}
}
If it looks like i have no clue what i am doing towards the end its because i dont. Please help. thank you:)
thanks for your replies everyone. i shouldve been more specific. I guess what i shoudlve asked if there are any methods out there or structures i can implement in my code to make sure the user input meets those specifications. I see now that my code is very incomplete. i am going over notes now to improve my code.
This looks like a homework question so I won't solve it directly. However here are some steps you could take:
Create a method to validate the input (public static boolean isValid(String str))
Convert the String to a character Array. (There's a method for that!)
Iterate over the letters and keep track of how many upper and lower case letters there are and how many digits there are. (Using Character.isDigit(), Character.isUpperCase() and Character.isLowerCase())
If all the requirements are met, return true. Return false otherwise.
I am trying to create a program where one can input words, which are added to an array, until the same word is entered twice. Then the program breaks.
Something like this:
public static void main(String[] args) {
ArrayList<String> words = new ArrayList<String>();
Scanner reader = new Scanner(System.in);
while (true) {
System.out.println("Type a word: ");
String word = reader.nextLine();
words.add(word);
if (words.contains(word)) {
System.out.println("You typed the word: " + word + " twice.");
break;
}
Every time I enter a single word, the program says "You have typed the word twice." I need to find a way to distinguish the items in the array from one another. Is it possible to use a for block?
Thank you.
You're adding word to words before doing the contains check.
if (words.contains(word)) {
System.out.println("You typed the word: " + word + " twice.");
break;
} else {
words.add(word);
}
will resolve this.
You should also consider making words a Set, which has faster lookups and doesn't allow duplicates.
A slightly improved version would be to use a Set: its add method returns false when the element is already present (and it's more efficient than a list to "find" an element - although in your case, because there is only a small number of words, it won't make any noticeable difference).
Set<String> words = new HashSet<> ();
while (true) {
System.out.println("Type a word: ");
String word = reader.nextLine();
if (!words.add(word)) {
System.out.println("You typed the word: " + word + " twice.");
break;
}
}
I am working on a practice exercise in my online pursuit to learn Java and am stumped!
The gist of my program is I have the user select an option via the input of a single char, then the program proceeds to cases based off of the value. If the default case executes, that means the input was invalid and I want to then return to the user input prompt.
I initial thought was to use a 'goto', however from what I understand, I would probably be stoned to death by anyone besides me reading the code. And then there's the fact that goto doesn't exist in Java... So while Googling, I found 'labeled breaks'. It looked just like what I needed. However, the spot which I have inserted the label is unrecognized, even though it's in the same class as the cases. How should I go about doing this?
String newLine = System.getProperty("line.separator");
restart:
System.out.println("Please select the type of shape you wish to calcuate information for: "
+ newLine + "A: Square" + newLine + "B: Rectangle" + newLine + "C: Circle");
char typeShape = input.next().charAt(0);
String shape = Character.toString(typeShape);
switch (shape.toLowerCase()) {
case "a":
//do something
break;
case "b":
//do something
break;
case "c":
//do something
break;
default:
System.out.println("Invalid selection. Please re-enter shape.");
break restart;
}
I believe you want to label a block. Something like
restart: {
System.out.println("Please select the type of shape you wish to calculate "
+ "information for: " + newLine + "A: Square" + newLine + "B: Rectangle"
+ newLine + "C: Circle");
char typeShape = input.next().charAt(0);
String shape = Character.toString(typeShape);
switch (shape.toLowerCase()) {
case "a":
//do something
break;
case "b":
//do something
break;
case "c":
//do something
break;
default:
System.out.println("Invalid selection. Please re-enter shape.");
break restart;
}
}
I guess a simple approach will be to use the do-while loop. If the condition is not satisfied (invalid input/character), continue the loop, otherwise set the flag to false and come out.
boolean inputFlag;
do {
System.out.println("Please select the type of shape you wish to calcuate information for: "
+ newLine + "A: Square" + newLine + "B: Rectangle" + newLine + "C: Circle");
char typeShape = input.next().charAt(0);
String shape = Character.toString(typeShape);
switch (shape.toLowerCase()) {
case "a":
inputFlag = false;
//do something
break;
case "b":
inputFlag = false;
//do something
break;
case "c":
inputFlag = false;
//do something
break;
default:
System.out.println("Invalid selection. Please re-enter shape.");
inputFlag = true;
}
} while (inputFlag);
Java allows you to label a loop construct (e.g. for, while) and then jump out of the inside one of the loops to an outer level.
The language does not allow you to label arbitrary lines and "goto" them.
UPDATE: Apparently I was wrong. Java supports labeling arbitrary blocks (but not individual statements). See https://stackoverflow.com/a/1940322/14731
Labeled blocks are frowned upon for similar reasons goto is frowned upon: it's not a natural flow.
With that said, you might be wondering how you would manage the behavior you want, which is pretty simple: use a loop
//pseudo-code
while(something) {
repeatCode
}
In your case, you would do something like:
boolean choosing = true;
while(choosing) {
switch(...) {
case "a":
choosing = false;
break;
case "b":
choosing = false;
break;
}
}
You may find this a bit verbose. Instead, you could set choosing to false as soon as you enter the loop, then set it back to true if the user didn't enter a correct name.
Or better yet, use a do-while loop:
boolean choosing = false;
do {
switch(...) {
case "a":
break;
default:
choosing = true;
break;
}
} while(choosing);
My title isn't exactly the best but I'm not sure how to name what I am trying to do. Either way, I have a case-switch...
switch (input) {
case "A":
Item item = new Item();
System.out.print("Enter a barcode: ");
barCode = scan.nextLine();
item.setBarCode(barCode);
if (store.addItem(barCode)) {
System.out.println(store.stockedItems.get(barCode).getProductName()
+ " has been added to the store's inventory");
}
else {
item.setQuantity(1);
System.out.print("Enter the item's name: ");
productName = scan.nextLine();
productName = productName.toLowerCase();
item.setProductName(productName);
store.stockedItems.put(barCode, item);
System.out.println(store.stockedItems.get(barCode).getProductName()
+ " has been added to the store's inventory");
}
break;
}
This is just one case. What this does is when the user picks A to add an object to my data structure, it finds out if the barcode mentioned is already in use.
If it is, it just increments the quantity of the object in my data structure.
If the barcode is not in use and after checking its validity. It will prompt the user for the name of the object and then proceed to add it to my data structure.
Now the problem is after I input the barcode string and call the setter function in its respective object class:
public void setBarCode(String code) {
if (!code.matches("[0-9]+") || code.length() != 12) {
System.out.println("The barcode entered is not in valid format. Entry ignored.");
} else {
barcode = code;
}
}
This function just makes sure it is numeric and 12 characters long. If it's not, I want to ignore the entry and start over from the menu. The problem I have is that the program moves on to asking for the items name even if the barcode is invalid and not set.
How do I skip all that and just print the menu out again?
Two strategies can work for this:
move the check for barcode validity outside the setBarCode method and do that test first (or modify setBarCode to return a boolean indicating whether the bar code was valid).
modify addItem to return something more informative than a boolean so that you can distinguish three cases: bad bar code; succeeded; failed because it needs more info.
The setter setBarCode() should either (a) succeed, or (b) indicate failure (probably using an IllegalArgumentException since we're in Java) rather than fail silently. If you were to use an IllegalArgumentException, this code would work nicely:
boolean acceptable;
try {
item.setBarCode(barCode);
acceptable = true;
}
catch(IllegalArgumentException e) {
acceptable = false;
}
if(acceptable) {
if(store.addItem(barCode)){
System.out.println(store.stockedItems.get(barCode).getProductName() + " has been added to the store's inventory");
}
else {
item.setQuantity(1);
System.out.print("Enter the item's name: ");
productName = scan.nextLine();
productName = productName.toLowerCase();
item.setProductName(productName);
store.stockedItems.put(barCode, item);
System.out.println(store.stockedItems.get(barCode).getProductName() + " has been added to the store's inventory");
}
}
break;
However, I'd recommend you not rely on the failure of a setter for correctness. Stylistically, it "smells funny." Rather, I'd put the test in another (probably static) method, test before you call the setter and react accordingly, and then put an assert in the setter. So, more like this:
// Somewhere up in your code -- Sorry, fixed up your regex
private static final Pattern BARCODE=Pattern.compile("^\\d{12}$");
public static boolean isValidBarcode(String candidate) {
return BARCODE.matcher(candidate).matches();
}
// Now your "real" code
case "A":
Item item = new Item();
System.out.print("Enter a barcode: ");
barCode = scan.nextLine();
if(isValidBarCode(barCode)) {
item.setBarCode(barCode);
if(store.addItem(barCode)) {
System.out.println(store.stockedItems.get(barCode).getProductName() + " has been added to the store's inventory");
}
else {
item.setQuantity(1);
System.out.print("Enter the item's name: ");
productName = scan.nextLine();
productName = productName.toLowerCase();
item.setProductName(productName);
store.stockedItems.put(barCode, item);
System.out.println(store.stockedItems.get(barCode).getProductName() + " has been added to the store's inventory");
}
}
else {
System.out.println("That's not a valid bar code.");
}
break;
// And, finally, your setBarCode() method
public void setBarCode(String code) {
assert isValidBarCode(code);
barcode = code;
}
I want to make a simple calculator but, I don't know how to enter many operations just like a real calculator.
switch (choice)
{
case 1:
System.out.println("Please enter 2 numbers only: " );
x = input.nextInt();
y = input.nextInt();
sum = calc.add(x,y);
System.out.printf("The sum is %d\n\n",sum);
out.write(x + "+" + y + "=" + sum);
break;
case 2:
...
case 3:
...
}
There is no question but I have some suggestions.
I would
make the case statements based on the operation '+', instead of 1.
make the messages match the operations. e.g. write(x + "*" + y when multiplying. Also don't call them all "sum"
make sure I read the nextLine() at the end.
write a new line after each line.
add a default: when the user enters an unknown operation.
Use the ScriptEngine. E.G. here.
=
That has a GUI (obviously) but you could simply allow the user to type in whatever formula JS can handle. Here is another example at my site that allows formula entry by text field.