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 5 years ago.
Improve this question
I am not sure how to exactly ask my question, but I wanted to print the statement "your first/second/third try" every time the user guesses ( I think what I commented in my code will seem clearer than what I am trying to convey now) but I'm confused on how to do so. also, sorry if my code is messy, I'm a newbie at this lol.
import java.util.Scanner;
import java.util.Random;
import java.lang.System;
public class GuessingGame {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
Random randGen = new Random();
int userGuess = 0;
int userTries = 0;
int userCompRandom = randGen.nextInt(11)+1;
String userName = "";
boolean isWrong = true;
string guessNumberTag = "";
System.out.println("Welcome to the number guessing game. What's
your name?");
userName = scnr.nextLine();
System.out.println("I’m thinking of an integer between 1 and 10.
You have 3 guesses.");
while (isWrong = true){
userTries +=1;
userGuess = scnr.nextInt();
if (userGuess > userCompRandom){
System.out.println(userGuess);
System.out.println("Too high, guess lower!");
}
else if (userGuess < userCompRandom){
System.out.println(userGuess); **//First/second/third
try: userGuess//**
System.out.println("Too low, guess higher!");
}
else if (userGuess == userCompRandom){
System.out.println(userGuess);//First/second/third try: userGuess//
System.out.println("Congratulations " + userName + "! It took you " + userTries + "!");
break;
}
if (userTries>4){
System.out.println("Game over " +userName + ",you lose!:p");
break;
}
}
}
}
String[] guessStatement = {"Your first try.", "Your second try.", "Your third try."};
System.out.println(guessStatement[userTries]);
Array index starts at 0, so adjust userTries.
You could create a method to do this. Note your check is >4 so I added fourth.
private static String getPrompt(int tries, int guess) {
String[] tryWords = { "first", "second", "third", "fourth"} ;
return String.format("Your %s try: %d", tryWords[tries-1], guess );
}
and call it:
System.out.println(getPrompt(userTries, userGuess )); //**First/second/third try: userGuess//**
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 13 hours ago.
Improve this question
I am trying to create a 5 questions quiz, after question 4 it automatically prints question 5 and not ask first, and then proceeds on printing the results. here is my code
import java.util.Scanner;
public class quiz {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String name, section;
int score, numQuestions = 5;
System.out.println("Welcome to the Basic Electronics Quiz!");
boolean repeat;
do {
// Get name and section
System.out.print("Enter your name: ");
name = scanner.nextLine().trim();
System.out.print("Enter your section: ");
section = scanner.nextLine().trim();
// Initialize score
score = 0;
// Question 1
System.out.println("\nQuestion 1: What is Ohm's Law?");
System.out.println("A. Voltage = Current x Resistance");
System.out.println("B. Current = Voltage x Resistance");
System.out.println("C. Resistance = Voltage / Current");
System.out.print("Answer: ");
String answer1 = scanner.nextLine().trim().toLowerCase();
if (answer1.equals("a")) {
System.out.println("Correct!");
score++;
}else {
System.out.println("Wrong. The correct answer is " + "A" + ".");
}
System.out.println();
// Question 2
System.out.println("\nQuestion 2: What is the unit of resistance?");
System.out.println("A. Ampere");
System.out.println("B. Volt");
System.out.println("C. Ohm");
System.out.print("Answer: ");
String answer2 = scanner.nextLine().trim().toLowerCase();
if (answer2.equals("c")) {
System.out.println("Correct!");
score++;
}else {
System.out.println("Wrong. The correct answer is " + "C" + ".");
}
System.out.println();
// Question 3
System.out.println("\nQuestion 3: An LED is a type of resistor. (True/False)");
System.out.print("Answer: ");
String answer3 = scanner.nextLine().trim().toLowerCase();
if (answer3.equals("true")) {
System.out.println("Correct!");
score++;
}else {
System.out.println("Wrong. The correct answer is " + "True" + ".");
}
System.out.println();
// Question 4
System.out.println("Question 4: What is the total resistance of two 10-ohm resistors in parallel?");
System.out.print("Your answer: ");
try {
double answer4 = scanner.nextDouble();
double expectedAnswer4 = 5.0;
if (Math.abs(answer4 - expectedAnswer4) < 0.0001) {
System.out.println("Correct!");
score++;
} else {
System.out.println("Wrong. The correct answer is " + expectedAnswer4 + ".");
}
System.out.println();
} catch (Exception e) {
// If there's an error parsing the input, don't add to score
}
// Question 5
System.out.println("\nQuestion 5: What is the term for a circuit that can generate an output signal with a fixed frequency?");
System.out.print("Your answer: ");
String answer5 = scanner.nextLine().trim().toLowerCase();
if (answer5.contains("Occilator") && answer5.contains("occilator")) {
score++;
}
else {
//System.out.println("Wrong. The correct answer is " + "Oscillator" + ".");
}
System.out.println();
// Display results
System.out.printf("\n%s, section %s, your score is %d/%d.\n", name, section, score, numQuestions);
// Ask to repeat
System.out.print("\nDo you want to take the quiz again? (yes/no): ");
String repeatStr = scanner.nextLine().trim().toLowerCase();
repeat = repeatStr.equals("yes") || repeatStr.equals("y");
} while (repeat);
System.out.println("\nThank you for taking the quiz!");
}
}
I tried copying only the question 5 to another file and it works but when i paste it again in the main file it will only proceeds on printing the results instead of asking for question 5
The problem is in using scanner.nextDouble();. You can read here more about why the problem occurs on this line.
You can solve your problem if you use Double.parseDouble(scanner.nextLine()); instead of scanner.nextDouble();.
Also, as Gilbert Le Blanc
has stated in the comments, you need to update the condition in your 5th question from answer5.contains("Occilator") && answer5.contains("occilator") to answer5.contains("Occilator") || answer5.contains("occilator"), otherwise you will never be able to answer the 5th question correctly. Here you also meant to write oscillator and not ocillator.
Here is an example output after implementing the solution:
Welcome to the Basic Electronics Quiz!
Enter your name: Aleksa
Enter your section: 1
Question 1: What is Ohm's Law?
A. Voltage = Current x Resistance
B. Current = Voltage x Resistance
C. Resistance = Voltage / Current
Answer: a
Correct!
Question 2: What is the unit of resistance?
A. Ampere
B. Volt
C. Ohm
Answer: c
Correct!
Question 3: An LED is a type of resistor. (True/False)
Answer: true
Correct!
Question 4: What is the total resistance of two 10-ohm resistors in parallel?
Your answer: 5
Correct!
Question 5: What is the term for a circuit that can generate an output signal with a fixed frequency?
Your answer: occilator
Aleksa, section 1, your score is 5/5.
Do you want to take the quiz again? (yes/no):
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
First question here, I've searched around quite a bit for applying the .length method to user input. Unfortunately none of the questions that have been answered touch on the specifics of my situation.
I'm working a school project that has two parts. The first part is rolling 2 dice until the sum of the 2 dice are either 7 or 11, then printing a message saying what each die rolled, and their total.
The second part of the assignment is where I am having trouble. We are supposed to get the user to input 2 strings and have Java order the 2 strings alphabetically, and use .length to display the length of the two strings, then add them up. I've gotten as far as getting user input, but when I try to calculate the length of the strings, it just gives me the length of the return string at the end of the method. So when the user inputs "Hello" and "Goodbye" I end up getting 10 and 26, because it's counting the length of "Thank you!" and "Thank you! Now watch this!" I've tried putting the .length within the 'inputString' and 'inputAnotherString' method, which didn't work.
import java.io.*;
import java.math.*;
public class Main {
public static void main(String[] args) throws IOException {
boolean keepRolling = true;
while (keepRolling) {
int dieOne = rollDice();
int dieTwo = rollDice();
int diceTotal = (dieOne + dieTwo);
if (diceTotal == 7 || diceTotal == 11) {
System.out.println("You rolled a " + dieOne + " and a " + dieTwo + ": total = " + diceTotal + ". You win!");
break;
} else {
System.out.println("You rolled a " + dieOne + " and a " + dieTwo + ": total = " + diceTotal + ". Roll again!");
}
}
String firstString;
firstString = inputString();
System.out.println(firstString);
String secondString;
secondString = inputAnotherString();
System.out.println(secondString);
int lengthOne = firstString.length();
System.out.println(lengthOne);
int lengthTwo = secondString.length();
System.out.println(lengthTwo);
int totalLength = lengthOne + lengthTwo;
System.out.println(totalLength);
}
public static int rollDice() {
return 1+ (int)(Math.random()*((6-1)+1));
}
public static String inputString() {
String stringOne;
BufferedReader in;
in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a string!");
try {
stringOne = in.readLine();
} catch(IOException e) {
}
return "Thank you!";
}
public static String inputAnotherString() {
String stringTwo;
BufferedReader in;
in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter another string!");
try {
stringTwo = in.readLine();
} catch(IOException e) {
}
return "Thank you! Now watch this!";
}
}
Any help would be greatly appreciated!
You assign the variables to the functions you are calling, meaning that they get assigned to the return value of those functions. Because of this, firstString gets the return value of inputString() (in this case "Thank you!"). You have to return the inputted string in your functions like so:
public static String inputString() {
String stringOne;
BufferedReader in;
in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a string!");
try {
stringOne = in.readLine();
} catch(IOException e) {
}
return stringOne;
}
Though you might want to see how you handle exceptions in this case.
your method public static String inputString() returns "Thank you!" instead of what the user has input. In that case, by setting a variable calling firstString = inputString(); it sets firstString to be "Thank you!". Thus calling firstString.length(); returns you the length of "Thank you!" instead of the input that users give.
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 5 years ago.
Improve this question
The goal of this assignment is to generate a multiplication problem in class Multiplier to display in GameTester so that the user may input an answer. If incorrect 3 times, it will display the correct answer and then prompt whether or not they would like to play again. My overall issue is after they solve or fail to solve the problem and I prompt the next question they are unable to answer. I am looking for a more efficient way to display another question so that it is more fluid and continuous in the program.
import java.util.Scanner;
public class GameTester{
public static String question;
public static void main(String[] args){
Multiplier m = new Multiplier();
Scanner s = new Scanner(System.in);
question = m.generateProblem();
System.out.println(question);
int userAnswer = s.nextInt();
if(userAnswer == m.checkAnswer()){
System.out.println("Correct!! Want to play again?");
s.nextLine();
String user = s.nextLine();
playAgain(user);
}
else {
System.out.println("Sorry, the answer is incorrect. Try again!");
s.nextLine();
for(int i = 0; i <=1; i++){
System.out.println(question);
if(i != 1 && s.nextInt() != m.checkAnswer()){
System.out.println("Sorry, the answer is incorrect. Try again!");
}
else if(i == 1 && s.nextInt() != m.checkAnswer()){
System.out.println("The correct answer was " + m.checkAnswer());
System.out.println("Want to play again?");
s.nextLine();
String user = s.nextLine();
playAgain(user);
}
else{
System.out.println("Correct!! Want to play again?");
s.nextLine();
String user = s.nextLine();
playAgain(user);
}
}
}
}
public static void playAgain(String userInput){
if(userInput.equals("yes")){
Multiplier m2 = new Multiplier();
question = m2.generateProblem();
System.out.println(question);
}
else{
System.exit(0);
}
}
}
import java.util.Random;
public class Multiplier{
public static int product;
public Multiplier(){
}
public static String generateProblem(){
Random r = new Random();
int term1 = r.nextInt(11);
int term2 = r.nextInt(11);
product = term1 * term2;
String s = "How much is " + term1 + " times " + term2 + "?";
return s;
}
public static int checkAnswer(){
return product;
}
}
It's all a simple matter of utilizing a boolean flag and while loops at specific locations. By doing this you can actually eliminate the playAgain() method but on the same token, we create other methods to streamline the flow and eliminate duplicate code.
Since you've brought up the subject of flow, it's always a good idea to keep your Class's main() method clean and by clean I mean by only placing relevant code or calls pertaining to to the true flow of your application instead of filling it with what I call method clutter. Allow the main() method to deal with Command Line Arguments and call another method to actually start your application, branching can then go from there. Try to only place method calls that outline the true main flow of your application. Even though your project is a simple console application it's still a good habit to get into if for anything, the sake of readability. Then again...this is just my opinion and really holds no merit to any of the valid answers provided towards your post.
You might want to streamline your code like this:
package gametester;
import java.util.InputMismatchException;
import java.util.Scanner;
public class GameTester {
public static String question;
public static int questionCount = 0;
private static Scanner s = new Scanner(System.in);
public static void main(String[] args) {
playQuiz();
}
private static void playQuiz() {
boolean playAgain = true;
System.out.println("First Question:");
while (playAgain) {
question = Multiplier.generateProblem();
System.out.println(question);
int userAnswer = getAnswer();
playAgain = processAnswer(userAnswer);
}
}
private static int getAnswer() {
int answer = 0;
while (true) {
answer = 0;
// Trap any non-numerical answers from User
try {
answer = s.nextInt();
s.nextLine();
} catch (InputMismatchException ex) {
// Needed to clear the scanner buffer otherwise
// this catch clause will play over and over again
// indefinately.
s.nextLine();
// Display an Input fault to User.
System.err.println("Incorrect Numerical Response Provided "
+ "(Numbers only please)! Try Again.\n");
// Get another answer from User.
continue;
}
break; // Good input, get outta this loop
}
return answer;
}
private static boolean processAnswer(int userAnswer) {
boolean pAgain = false;
if (userAnswer == Multiplier.checkAnswer()) {
System.out.print("Correct!! ");
pAgain = promptPlayAgain();
} else {
System.out.println("Sorry, the answer is incorrect. Try again!");
for (int i = 0; i <= 1; i++) {
System.out.print(question);
System.out.println(" (Attempt #: " + (i+2) + ")");
int ans = getAnswer();
if (i != 1 && ans != Multiplier.checkAnswer()) {
System.out.println("Sorry, the answer is incorrect. Try again!");
} else if (i == 1 && ans != Multiplier.checkAnswer()) {
System.out.println("The correct answer was " + Multiplier.checkAnswer());
pAgain = promptPlayAgain();
} else {
System.out.print("Correct!! ");
pAgain = promptPlayAgain();
break;
}
}
}
return pAgain;
}
private static boolean promptPlayAgain() {
boolean pAgain = false;
while (true) {
System.out.println("Want to play again (y or n)?");
String user = s.nextLine();
if (user.toLowerCase().charAt(0) == 'n') {
pAgain = false;
break;
} else if (user.toLowerCase().charAt(0) == 'y') {
pAgain = true;
System.out.println("\nNext Question :");
break;
} else {
System.err.println("Incorrect Response ('y' or 'n' exprected)! Try Again.\n");
}
}
return pAgain;
}
}
And your Multiplier Class:
package gametester;
import static gametester.GameTester.questionCount;
import java.util.Random;
public class Multiplier{
public static int product;
public Multiplier(){ }
public static String generateProblem(){
questionCount++;
Random r = new Random();
int term1 = r.nextInt(11);
int term2 = r.nextInt(11);
product = term1 * term2;
String s = String.valueOf(questionCount) + ") How much is " + term1 + " times " + term2 + "?";
return s;
}
public static int checkAnswer(){
return product;
}
}
Now, put a configurable time limit on each question :)
You could split the asking of the question into a method askQuestion. This would instantiate a Multiplier, output the question, and take the user's response. Your method askQuestion could either return the Multiplier, or check the answer and return a boolean indicating whether they got it right.
Your main method would then mainly contain the control loop necessary to run the program. One useful tool for repeatedly asking something is a do-while loop, which runs a block of code at least once, and then repeatedly until a condition is satisfied. For example:
boolean Correct = false;
int Attempts = 0;
do {
Correct = askQuestion();
Attempts++;
} while (!Correct && Attempts < 3);
You can use the while loop as:
public static void main(String[] args) {
Multiplier m = new Multiplier();
Scanner s = new Scanner(System.in);
question = m.generateProblem();
System.out.println(question);
String user;
int count = 0;
int userAnswer;
while (true) {
userAnswer = s.nextInt();
if (userAnswer == m.checkAnswer()) {
System.out.println("Correct!! Want to play again?");
s.nextLine();
user = s.nextLine();
playAgain(user);
count = 0;
} else {
if(count == 2){
System.out.println("The correct answer was " + m.checkAnswer());
System.out.println("Want to play again?");
s.nextLine();
user = s.nextLine();
playAgain(user);
count = 0;
} else {
System.out.println("Sorry, the answer is incorrect. Try again!");
count++;
}
}
}
}
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 5 years ago.
Improve this question
Here is my code. I got an error as ".class expected".
What should I do to rectify it.
import java.util.*;
class Atm2
{
public static void main (String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the amount to be withdrawed");
int withdraw = in.nextInt();
System.out.println("Enter the amount in the account");
double acnt_balc = in.nextDouble();
if ((withdraw % 5 == 0) && (acnt_balc >= withdraw + 0.50))
double cur = acnt_balc - (withdraw + 0.50);
System.out.println(cur);
else
System.out.println(acnt_balc);
}
}
Try curly braces in the context of your if-else.
It should look like this:
if (isMoving) {
currentSpeed--;
} else {
System.err.println("The bicycle has already stopped!");
}
So you can see, that there is a if-block and a else-block. You have to say which code belongs to if and which belongs to else. You can do that with the braces.
Scanner requires you to import java.util.*;
I tried it works and also format properly , see below , it runs
import java.util.*;
class Atm2
{
public static void main (String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the amount to be withdrawed");
int withdraw = in.nextInt();
System.out.println("Enter the amount in the account");
double acnt_balc = in.nextDouble();
if ((withdraw % 5 == 0) && (acnt_balc >=(withdraw + 0.50)))
{
double cur=(acnt_balc-(withdraw + 0.50));
System.out.println(cur);
}
else
{
System.out.println(acnt_balc);
}
}
}
Also make sure your Filename is the same as class name , in this case Atm2.java
The Scanner Class in present in the 'java.util' package , since you forgot to import it and used Scanner sc=new Scanner(); the compliler is complaining, and remember to compile use javac filename.java , to run use java filename
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm making a vocabulary practice program using arrays (I know, not Lists, but I need array practice). However, everything goes well until the program evaluates if the typed answer (when the program quizzes the user) is the actual definition. I always get the answer wrong, and I don't know why. Here's the whole program:
import java.util.Scanner;
public class organ {
public Scanner input = new Scanner(System.in);
public String language;
public int temp;
public static void main(String[] args){
organ organObject = new organ();
organObject.greeting();
organObject.ending();
}
public void greeting(){
System.out.println("Hello! Do you want to practice vocabulary in English or Spanish?");
//Need to fix this grammar.
System.out.println("!Hola! ?Quieres practicar el vocabulario en ingles o espanol?");
language = input.nextLine();
checkLanguage(language);
}
public void checkLanguage(String answer){
if (language.equals("English") || language.equals("ingles")){
englishTree();
}
else{
spanishTree();
}
}
public void englishTree(){
System.out.println("How many words do you want to practice using?");
int temp = input.nextInt();
String[] wordStorage = new String[temp];
String[] meaningStorage = new String[temp];
String answer;
for(int counter = 0; counter < wordStorage.length; counter++){
System.out.println("What is word number " + (1 + counter) + "?");
wordStorage[counter] = input.next();
System.out.println("What is def number " + (1 + counter) + "?");
meaningStorage[counter] = input.next();
}
if (wordStorage.length > 10) {
System.out.println("Stop. Now.");
}
System.out.println("Alright, let's get to the good stuff.");
for(int counter = 0; counter < wordStorage.length; counter++){
System.out.println("What is the meaning of " + wordStorage[counter] + "?");
answer = input.next();
if (answer == meaningStorage[counter]){
System.out.println("Correct!");
}
if (answer != meaningStorage[counter]){
System.out.println("Wrong. The answer is " + meaningStorage[counter] + ".");
}
}
}
public void spanishTree(){
System.out.println("Espere.");
}
public void ending(){
System.out.println("This is the ending of the program for now. Bye!");
}
}
The problem is under "Alright, let's get to the good stuff."
You're using == to compare Strings. Use .equals()
str1.equals(str2) instead of str1 == str2.