I am very new to coding, have only completed a few hours of YouTube videos to learn thus far. I am trying to complete a practice code and am facing some trouble.
I have attached a part of the code below. When I am entering value in (10,12,14, and 16) the code is still responding with "Wrong Response". In addition to this the following line is not properly functioning. It is not giving me the option to select a crust type. Please let me know if anyone has any suggestions.
Crust problem:
System.out.println("What type of crust would you like? ");
System.out.print("(H)and-tossed, (T)hin-crust, or (D)eep-dish: ");
crust = keyboard.nextLine();
Int Value problem:
if ( size.equals(" 10 ")) {
pizzaPrice = SM_Price;
} else if ( size.equals(" 12 ")) {
pizzaPrice = MED_Price;
} else if ( size.equals(" 14 ")) {
pizzaPrice = LG_Price;
} else if (size.equals(" 16 ")) {
pizzaPrice = XL_Price;
}
else { System.out.println("Wrong repsonse. ");
Thank you.
So, keep in mind that the constants 16, "16", " 16 " are all different things and non-equal to each other.
The other thing is that you need to show us what your types are. As Java is statically typed, that type information can actually help determine the behavior that you get.
if size is an int, then using size against string will not work. i.e size.equals(" 10 ") will not be the same as size.equals(10).
Also will not be the same as size.equals("10") which is different from " 10 "
You haven't defined size anywhere, so it's impossible to say.
I suspect your problem however is either that size is a different type that what you're comparing against using equals, or it's because you have spaces before and after your string numbers: " 12 ".
Please refer to User Input not working with keyboard.nextLine() and String (Java) for your nextLine() problem.
As to your other question one needs to know of what type you declared size to be.
If you declared it as String using String size = "10"; for example, then you are quite close:
Just change " 10 " in line 1 to "10" (without whitespace, as "10".equals(" 10 ") == false) and go for the small pizza.
Related
When running this in a command prompt,
System.out.println(Num + " is prime!");
System.out.println("Press N to put in another number or S to stop");
Where Num is an int
This is what comes out:
Is there any way to counter it or should I just deal with it?
System.out.println(String.valueOf(Num) + " is prime!");
Edit: Adding more information to replete the mystery here.
java.lang.String.valueOf will correctly parse your Number where as simply adding a Number with a String will vary between compilers.
See more here Concat an integer to a String - use String literal or primitive from performance and memory point of view?
Doing some practice exam questions, and it says to:
assume the statement String pattern = getPattern();. Explain if any flow in the method getPattern(). How would you fix it?
Here's the code:
public static String getPattern() {
Scanner inPattern = new Scanner(System.in);
String pattern = " ";
boolean valid = false;
int i = 0;
while(!valid){
System.out.println("please enter a valid pattern with X or x");
pattern = inPattern.next();
if ( ! (pattern.charAt(i) == 'X' || pattern.charAt(i) == 'x'
|| pattern.charAt(i) == 'r'))
System.out.println("You have entered an invalid pattern");
else if ((i + 1) == pattern.length()) valid = true;
};
inPattern.close();
return pattern;
}
I'm not really sure how I would fix this... obviously this is a smaller part of a bigger code because this doesn't include a main method, personally making it a bit more difficult to see what's wrong.
I'm really not sure exactly what to change here. I've been up for 7+ hours watching youtube videos and attempting to understand this stuff or to do this question but I really cannot figure it out. would anyone be able to provide a good example?
Okey, so first things first. The code you recieved is all you need to run it, its not part of a "bigger program". It tells you to assume its being called like this:
String pattern = getPattern();
So when calling the method "getPattern" from a main method what happens? You get prompted to input a "valid" character, if the character is valid the method returns the character.
The question itself is weirdly designed. But looking at the code, I guess what they're fishing for is that you're being told to input the character 'x' or 'X'. But in the code another valid character is 'r'. So either they want you to change the text given to the user, or remove 'r' as a valid char would be my guess.
I'm a very beginner at Java, and I'm creating a program that accepts user input in Java, and I'm trying to create a string that accepts strings or integers as responses. However, when I type in the acceptable integer, it won't recognize the answer. Here is the code:
System.out.println("How much time you you want to spend on this? Less than 30 mins, less than an hour, or more? Type \"30\", \"h\", or \"m\".");
String ls = console.next();
while (!ls.equalsIgnoreCase("h") && !ls.equalsIgnoreCase("m") && ls.equalsIgnoreCase("30")) {
System.out.println("Type shit properly.");
ls = console.next();
}
if (ls.equalsIgnoreCase("30")) {
System.out.println("Do you want to do something fun? Y/N.");
String dare = console.next();
while (!dare.equalsIgnoreCase("y") && !dare.equalsIgnoreCase("n")) {
System.out.println("Seriously?");
dare = console.next();
}
}
Every time I type 30 into the console, it gives me my error report "Type shit properly" instead of proceeding to the "if ls equals 30" section. It works fine for the m and h options, just not the number. I thought strings accepted numbers as well; was I wrong? How do I get this to accept both Strings AND integers as input?
Change
&&ls.equalsIgnoreCase("30")
to
&&!ls.equalsIgnoreCase("30")
or if you want to allow any number, you could use String.matches(String)
&&!ls.matches("\\d+")
use !ls.matches("30") instead of ls.equalsIgnoreCase("30")
I'm very new to programming, especially Java. I need to create a program that counts how many orders each entry at a restaurant gets ordered. The restaurant carries 3 entries, hamburgers, salad, and special.
I need to set up my program so that the user inputs, say, "hamburger 3", it would keep track of the number and add it up at the end. If the user inputs "quit", the program would quit.
System.out.println("Enter the type (special, salad, or hamburger) of entrée followed by the number, or quit to exit the program.");
I'm thinking about using a while loop, setting it so if the user input != to "quit", then it would run.
What's difficult for me is I don't know how to make my program take into account the two different parts of the user input, "hamburger 3" and sum up the number part at the end.
At the end, I want it to say something like "You sold X hamburgers, Y salads, and Z specials today."
Help would be appreciated.
You'll probably want three int variables to use as a running tally of the number of orders been made:
public class Restaurant {
private int specials = 0;
private int salads = 0;
private int hamburger = 0;
You could then use a do-while loop to request information from the user...
String input = null;
do {
//...
} while ("quite".equalsIgnoreCase(input));
Now, you need some way to ask the user for input. You can use a java.util.Scanner easily enough for this. See the Scanning tutorial
Scanner scanner = new Scanner(System.in);
//...
do {
System.out.println("Enter the type (special, salad, or hamburger) of entrée followed by the number, or quit to exit the program.");
input = scanner.nextLine();
Now you have the input from the user, you need to make some decisions. You need to know if they entered valid input (an entree and an amount) as well as if they entered an available option...
// Break the input apart at the spaces...
String[] parts = input.split(" ");
// We only care if there are two parts...
if (parts.length == 2) {
// Process the parts...
} else if (parts.length == 0 || !"quite".equalsIgnoreCase(parts[0])) {
System.out.println("Your selection is invalid");
}
Okay, so we can now determine if the user input meets or first requirement or not ([text][space][text]), now we need to determine if the values are actually valid...
First, lets check the quantity...
if (parts.length == 2) {
// We user another Scanner, as this can determine if the String
// is an `int` value (or at least starts with one)
Scanner test = new Scanner(parts[1]);
if (test.hasInt()) {
int quantity = test.nextInt();
// continue processing...
} else {
System.out.println(parts[1] + " is not a valid quantity");
}
Now we want to check if the actually entered a valid entree...
if (test.hasInt()) {
int quantity = test.nextInt();
// We could use a case statement here, but for simplicity...
if ("special".equalsIgnoreCase(parts[0])) {
specials += quantity;
} else if ("salad".equalsIgnoreCase(parts[0])) {
salads += quantity;
} else if ("hamburger".equalsIgnoreCase(parts[0])) {
hamburger += quantity;
} else {
System.out.println(parts[0] + " is not a valid entree");
}
Take a look at The if-then and if-then-else Statements and The while and do-while Statements for more details.
You may also find Learning the Java Language of some help. Also, keep a copy of the JavaDocs at hand, it will make it eaiser to find references to the classes within the API
These two methods should be what you're looking for.
For splitting: String.split(String regex)
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)
For parsing String into an Interger: Integer.parseInt(String s)
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
You can split your strings using input.split(" "). This method gives you two strings - two parts of the main string. The character you splitted with (" ") won't be found in the string anymore.
To then get an integer out of your string, you can use the static method Integer.parseInt(inputPartWithCount).
I hope this helps!
I'm doing a basic java tutorial that is basically a mad libs program. The idea came up in the tutorial to try making sure a user is at least 13, but the example hard coded the age into the program. I wanted to try getting the age from the user, but at this point, my code gives me an error because a "string cannot be converted to an integer." Looking at my code, I don't see why it's giving me this error. Here is what I used:
int age = console.readLine("Enter your age: ");
if (age < 13) {
//enter exit code
console.printf("Sorry but you must be at least 13 to use this program.\n");
System.exit(0);
}
I have looked for other answers, but I didn't see any that I could discern from the specific problems they were trying to fix.
You should use
try{
int age = Integer.parseInt(console.readLine("Enter your age: "));
// do stuff
} catch (NumberFormatException e) {
// User did not enter a number
}
Java doesn't cast between the two automatically. The above method however will throw an exception when you don't enter a number which you will have to handle
You can use
Scanner input = new Scanner(System.in);
int Age = input.nextInt();
input.nextLine();
Okay, I'm not sure if it's cool to answer your own question. I managed to get this to work, so in case someone else encounters the same problem. Here is the code that I used:
String ageAsString = console.readLine("Enter your age: ");
int age = Integer.parseInt(ageAsString);
if (age < 13) {
//enter exit code
console.printf("Sorry but you must be at least 13 to use this program.\n");
System.exit(0);
}