I just started learning java a week ago. I am taking a class at my school. I am trying to create a quiz and I can't figure out how to print out the score. The quiz has three possibilities 3/3, 2/3, 1/3. The problem I am having is with the if statements near the end of the program.
import java.io.*;
import static java.lang.System.*;
import java.util.Scanner;
class t1_lesson03_template{
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.println("1. What do you type at the begining of a comment?");
String answer1 = "//";
String userinput1 = scan.nextLine();
if (userinput1.equals(answer1)) {
System.out.println(" Correct!");
}
if (!userinput1.equals(answer1)) {
System.out.println(" Wrong!");
}
String answer2 = ("(int)");
System.out.println("2. What do you type before a double to convert to an int?");
String userinput2 = scan.nextLine();
if (userinput2.equals(answer2)) {
System.out.println(" Correct!");
}
if (!userinput2.equals(answer2)) {
System.out.println(" Wrong!");
}
String answer3 = ("int number = 5;");
System.out.println("3. Create an int called \"number\", and make it equal 5.");
String userinput3 = scan.nextLine();
if (userinput3.equals(answer3)) {
System.out.println(" Correct!");
}
if (!userinput3.equals(answer3)) {
System.out.println(" Wrong!");
}
if (userinput1.equals(answer1) && userinput2.equals(answer2) && userinput3.equals(answer3)) {
System.out.println("3/3 Awesome!");
}
else if (userinput1.equals(answer1) || userinput2.equals(answer2) || userinput3.equals(answer3)) {
System.out.println("2/3 Good job.");
}
else {
System.out.println("1/3 Try again.");
}
}
}
This,
else if (userinput1.equals(answer1) || userinput2.equals(answer2)
|| userinput3.equals(answer3)) {
should be something like
else if ((userinput1.equals(answer1) && userinput2.equals(answer2)) ||
(userinput1.equals(answer1) && userinput3.equals(answer3)) ||
(userinput2.equals(answer2) && userinput3.equals(answer3))) {
but I would prefer a count. And an array to display your different messages. Something like
int count = 0;
if (userinput1.equals(answer1)) {
count++;
}
if (userinput2.equals(answer2)) {
count++;
}
if (userinput3.equals(answer3)) {
count++;
}
String[] result = { "0/3 None", "1/3 Try Again.", "2/3 Good Job.", "3/3 Awesome!" };
System.out.println(result[count]);
Just add braces before each condition in if class and else if such as
if ((userinput1.equals(answer1)) && (userinput2.equals(answer2)) && (userinput3.equals(answer3))) {
System.out.println("3/3 Awesome!");
}
else if ((userinput1.equals(answer1)) || (userinput2.equals(answer2)) || (userinput3.equals(answer3))) {
System.out.println("2/3 Good job.");
}
Related
I have this short snippet of code where I have to check a string to see if it contains integers and possibly a decimal. The string is an amount of money (12.34) so as well it can not go past the fourth index.
My question is I'm being told to use charAt() (and in my code I used matches() and contains() which is wrong) to check for integers and decimals so that this routine will return a boolean that is true if the string works with those parameters, however I'm confused at how to go about converting this to use charAt() instead of matches() and contains().
As well, I'm sorry if I formatted this wrong, or worded something wrong, or the code looks awful, I'm in my first semester of Java and it's my very first programming class I've ever taken so I'm a bit rough.
import java.util.Scanner;
public class Auction
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String price;
String quantity;
System.out.print("How much money are you willing to bet on this item?: $");
price = keyboard.next();
if(price.matches("[0-9]*") && price.length() <= 5)
{
Float f = Float.parseFloat(price);
System.out.printf("$%5.2f", f);
System.out.println();
}
else if(price.matches("[0-9]*") && price.length() <= 5 && price.contains("."))
{
Float f = Float.parseFloat(price);
System.out.printf("$%5.2f", f);
System.out.println();
}
else
{
System.out.println("Invalid input");
}
System.out.print("What quantity do you want to bid on?: ");
quantity = keyboard.next();
if(quantity.contains("."))
{
System.out.println("Invalid input");
}
}
}
I am typing this from a phone. So excuse the mistakes please. have u been asked by your professor to use charAt instead of regex and matches?
if (inpString!= null && !inpString.isEmpty () && inpString.length() <= 5){
int periodCount = 0;
for (int i=0; i < inpString.length (); i++){
char c = inpString.charAt (i);
if (c == '.'){
periodCount++;
}else if (c >= '0' && c <= '9'){
}else {
System.out.println("invalid output");
break;
}
if(periodCount > 1){
System.out.println("too may periods. Invalid output");
break;
}
}
}else {
System.out.println ("invalid input");
}
Can you comment if u need to check that there are no thousandth digit i.e 1.234? If yes make sure
inpString.substring
(inpString.lastIndexOf
(".")).length < 3
with all the null and indexOutOfBounds checks
How about this way?
import java.util.Scanner;
public class Auction {
private static final String numberRegex = "^\\d*(\\.\\d+)?$";
private static final String integerNumber = "^\\d*$";
private static final int MAX_LENGTH = 5;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String price;
String quantity;
System.out.print("How much money are you willing to bet on this item?: $");
price = keyboard.next();
if (price.length() <= MAX_LENGTH && price.matches(numberRegex)) {
Float f = Float.parseFloat(price);
System.out.printf("$%5.2f\n", f);
} else {
System.out.println("Invalid input");
return;
}
System.out.print("What quantity do you want to bid on?: ");
quantity = keyboard.next();
if (!quantity.matches(integerNumber)) {
System.out.println("Invalid input");
}
}
}
I made some command line games and at the end of the game I want to ask if the player wants to play again. You can see in the code how I made but it's not working and I don't know why.
Can anybody help me?
import java.util.Scanner;
//WIP
public class GuessingGame2 {
static Scanner userInput = new Scanner(System.in);
static int randNumber;
static int guessNumber;
static boolean gameStatus;
static void checkNum(int x) {
guessNumber++;
if(x == randNumber) {
gameStatus = true;
} else if(x < randNumber) {
System.out.println("Too small!");
} else {
System.out.println("Too big!");
}
}
static void checkAnsw() {
if(userInput.hasNextLine()) {
if(userInput.nextLine() == "Y" || userInput.nextLine() == "y") {
guessGame();
} else if(userInput.nextLine() == "N" || userInput.nextLine() == "n") {
} else {
System.out.print("Y or N ");
checkAnsw();
}
} else {
System.out.print("Y or N ");
userInput.next();
checkAnsw();
}
}
static void guessGame() {
randNumber = (int) (Math.random() * 1000);
guessNumber = 0;
gameStatus = false;
System.out.println("Try to guess a number from 1 to 1000!");
while(gameStatus == false) {
System.out.print("Your guess: ");
if(userInput.hasNextInt()) {
checkNum(userInput.nextInt());
} else {
System.out.println("You need to choose a number!");
userInput.next();
}
}
System.out.println("You guessed the number in " + guessNumber + " tries.");
System.out.print("Do you want to play again? Y or N ");
checkAnsw();
}
public static void main(String[] args) {
guessGame();
}
}
Change your checkAnsw method to this:
static void checkAnsw() {
if(userInput.hasNextLine()) {
if(userInput.nextLine().equalsIgnoreCase("y")) {
guessGame();
} else if(userInput.nextLine().equalsIgnoreCase("n")) {
} else {
System.out.print("Y or N ");
checkAnsw();
}
} else {
System.out.print("Y or N ");
userInput.next();
checkAnsw();
}
}
You cannot compare Strings with the = as they are objects. Use the .equals method to compare Strings.
Your code works fine, I have copied and pasted it in Eclipse and this is the output:
Try to guess a number from 1 to 1000!
Your guess: eeeee
You need to choose a number!
Your guess: 1
Too small!
Your guess: 2
Too small!
Your guess: 2
I don't understand which is your problem, try to explain better
Here's what i've been working on. I'm trying loop this while method, using booleans. (My teacher is incompetent, so i've been learning out of textbook.)
else { System.out.println("Do you want to restart? Y/N");
string answer = scn.next();
return;
if (scn.hasNext() && !no)) {
System.out.println("end");
} else{
continue;
}
/*if (repeat) {
continue;
} else {
System.out.println("End");
break;
}*/
}
This is nested in a while loop like so ....
import java.util.Scanner; import java.lang.String;
public class booleanvariables {
public static void main (String[] args){
Scanner scn = new Scanner(System.in);
int score1, score2;
String answer, e;
boolean bothHigh, atLeastOneHigh, atLeastOneModerate, noLow, tooLow, repeat;
while (true) {
System.out.print("Enter the first test score:\t");
score1 = scn.nextInt();
System.out.print("Enter the second test score:\t");
score2 = scn.nextInt();
answer = null;
e = "n";
bothHigh = (score1 >= 90 && score2 >= 90);
atLeastOneHigh = (score1 >= 90 || score2 >= 90);
atLeastOneModerate = (score1 >= 70 || score2 >= 70);
noLow = !(score1 < 50 || score2 < 50);
tooLow = (score1 <= 50 || score2 <= 50);
repeat = (answer == "yes" || answer == "y"); //|| answer == Y || answer == Yes);
if (tooLow)
System.out.println("Inputs are too low");
if (bothHigh)
System.out.println("Qualified to be a manager");
if (atLeastOneHigh)
System.out.println("Qualified to be a supervisor");
if (atLeastOneModerate && noLow)
System.out.println("Qualified to be a clerk");
/** NESTED WRONG I'M AWARE
*/
else { System.out.println("Do you want to restart? Y/N");
string answer = scn.next();
return;
if (scn.hasNext() && !no)) {
System.out.println("end");
} else{
continue;
}
/*if (repeat) {
continue;
} else {
System.out.println("End");
break;
}*/
}
}
}
}
This is much simpler than you think.
Just do it like this:
boolean stop = false;
while(!stop) {
//do whatever you want here
System.out.println("Do you want to quit?(yes or no");
String input = scan.nextLine();
if(input.equals("no")) {
stop = true;
}
}
That way, if you enter "no", it'll set the boolean to true, which then will make the condition for the while loop, !stop, equal to false.
answer == "yes"
You are checking if two objects are the same. You should use the equals method answer.equals("yes") || answer.equals("y")
Tested and Working to My Liking
I've reworked some branching. ( I use BlueJ as a compiler and it thinks this is an error without the input = scn.nextLine();
do {
//same booleans i've been using
if (!stop) {
System.out.print("Do you want to quit? (yes or no):\t");
//String input;
input = scn.nextLine();
}
//String input;
input = scn.next();
if(input.equals("yes")) {
stop = true;
System.out.println("Goodbye");
return;
}
} while (!stop);
I really don't know why blue J doesn't like it when initialize input from within the if statement
So I just have a quick little issue
int pickmeup = 0;
while (true)
{
pickmeup = scanner.nextInt();
if (pickmeup == 1)
{System.out.println ("you entered 1");}
if(pickmeup == 2)
{System.out.println ("you entered 2");}
{
break;
}
System.out.println ("Invalid code");
Now when I run this code it all works fine however in regards to the strings but it seems as though the loop doesn't work all that well when I enter '3', as it doesn't return the string 'Invalid code'.
If I were to get rid of the strings after both if statements, then it works perfectly fine. What exactly am I doing wrong? Are there other ways to automatically have strings output?
I believe you want to use a logical or || and an else like,
int pickmeup;
while (true) {
pickmeup = scanner.nextInt();
if (pickmeup == 1 || pickmeup == 2) {
System.out.printf("you entered %d%n", pickmeup);
} else {
System.out.println("Invalid code");
}
}
Alternatively, you could use an else if chain like,
int pickmeup;
while (true) {
pickmeup = scanner.nextInt();
if (pickmeup == 1) {
System.out.println("you entered 1");
} else if (pickmeup == 2) {
System.out.println("you entered 2");
} else {
System.out.println("Invalid code");
}
}
You could start with firstly correcting your code, you can do that in eclipse Source-Format or by pressing CTRL+SHIFT+F
For your example, I corrected as much as I understood, currently it breaks only if else is reached. Break can be modified.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int pickmeup = 0;
while (true){
pickmeup = scanner.nextInt();
if (pickmeup == 1){
System.out.println("one");
}
else if (pickmeup == 2){
System.out.println("two");
}
else{
System.out.println("Invalid code");
break;
}
}
First of all I am not asking anyone to do anything just need a little help to fix this bug with boolean. I put false but the program stops. I got two parts to the program.
First part where i did the calculations:
class FibonacciNumbers {
FibonacciNumbers() {} //default constructor
public int fOf(int n) {
if (n == 0) //the base case
{
return 0;
} else if (n == 1) {
return 1;
} else {
return fOf(n - 1) + fOf(n - 2);
}
}
}
Second where the main method is:
import java.util.*;
public class FibonacciNumbersTesters {
public static void main(String[] args) {
FibonacciNumbers fNumbers = new FibonacciNumbers(); //creates new object
Scanner in = new Scanner(System.in);
String again;
String test;
boolean IsRepeat = true;
boolean isQuit;
try {
isQuit = false;
while (!isQuit) {
System.out.print("Enter the number you want to convert to Fibanocci('q' to quit): ");
int n = in.nextInt();
System.out.print("The Fibanocci number for " + n + " is: ");
n = fNumbers.fOf(n);
System.out.println(n);
System.out.print("Do you want to run again? (Y or N): ");
again = in.next();
if (again.equalsIgnoreCase("N")) {
System.out.println("Thank you! Please terminate the program by entering 'Q' or 'q' OR you can cotinue by entering anything else: ");
String toQuit = in.next();
if ((toQuit.charAt(0) == 'q') || (toQuit.charAt(0) == 'Q')) {
System.out.println("Good-bye!");
isQuit = true;
}
} else {
IsRepeat = true;
}
}
} catch (InputMismatchException ex) {
test = in.nextLine();
if ((test.charAt(0) == 'q') || (test.charAt(0) == 'Q')) {
System.out.println("Good-bye!");
isQuit = true;
} else {
System.out.println("Invalid input!");
System.out.println("Try again! ");
isQuit = false;
}
}
}
}
This part where i put isQuit = false; at the end it just stops. I want it to continue.
Try putting your try catch statement inside of your while loop.