So im creating jeapordy in java, and i dont care that i spelt it wrong(if i did) but i only have one question coded so far with only one answer, and it asks the question but only prints out you are wrong even if the answer is right.
it is asking the first history question and the answer is george, but it is printing out that the answer is wrong. the first history question is also worth 100. i have not began to code the math part yet.
thanks if you can help fin my problem! its probably really simple as i am a beginner.
import java.util.Random;
import java.util.Scanner;
public class game {
public static void main (String[] args){
//Utilites
Scanner s = new Scanner(System.in);
Random r = new Random();
//Variables
String[] mathQuestions;
mathQuestions = new String[3];
mathQuestions[0] = ("What is the sum of 2 + 2");
mathQuestions[1] = ("What is 100 * 0");
mathQuestions[2] = ("What is 5 + 5");
String[] historyQuestions;
historyQuestions = new String[3];
historyQuestions[0] = ("What is General Washingtons first name?");
historyQuestions[1] = ("Who won WWII, Japan, or USA?");
historyQuestions[2] = ("How many states are in the USA?");
//Intro
System.out.println("Welome to Jeapordy!");
System.out.println("There are two categories!\nMath and History");
System.out.println("Math History");
System.out.println("100 100");
System.out.println("200 200");
System.out.println("300 300");
System.out.println("Which category would you like?");
String categoryChoice = s.nextLine();
System.out.println("For how much money?");
int moneyChoice = s.nextInt();
if (categoryChoice.equalsIgnoreCase("history")){
if (moneyChoice == 100){
System.out.println(historyQuestions[0]);
String userAnswer = s.nextLine();
s.nextLine();
if (userAnswer.equalsIgnoreCase("george")){
System.out.println("Congratulations! You were right");
}
else{
System.out.println("Ah! Wrong answer!");
}
}
}
}
}
When you call nextInt(), a newline character is left unread, so a subsequent call to nextLine() will return an empty string (since it reads up to the end of the line). Call newLine() once prior to read/discard this trailing newline:
if (moneyChoice == 100) {
System.out.println(historyQuestions[0]);
s.nextLine(); // <--
String userAnswer = s.nextLine();
System.out.println(userAnswer);
...
As an aside, don't forget to close your Scanner when you're finished with it: s.close().
int moneyChoice = s.nextInt(); reads only the integer. It leaves a newline pending reading. Then String userAnswer = s.nextLine() ; reads an empty line that is obviously different from "george". Solution: read the newline immediately after the int, and do so in the whole program. You could prefer to create your own method nextIntAndLine().
int moneyChoice= s.nextInt() ;
s.nextLine();
Related
I am new to java programming.I want to calculate the sum and want to exit the program if user enters "N" and again loop if user enters "Y".But,it is not getting me out of loop even I enter "N".
public class Program {
public static void main(String[] args) {
boolean a=true;
while (a) {
System.out.println("enter a number");
Scanner c=new Scanner(System.in);
int d=c.nextInt();
System.out.println("enter a number2");
Scanner ce=new Scanner(System.in);
int df=ce.nextInt();
int kk=d+df;
System.out.println("total sum is"+kk);
System.out.println("do you want to continue(y/n)?");
Scanner zz=new Scanner(System.in);
boolean kkw=zz.hasNext();
if(kkw) {
a=true;
}
else {
a=false;
System.exit(0);
}
}
}
I didnt know where I made the mistake? Is there any other way?
First of all, your a variable is true if scanner.hasNext() is true, leading to a being true with every input, including "N" which means, your while loop will keep on going until there are no more inputs.
Second of all, you could optimize your code the next way:
I suggest getting rid of a and kkw to make your code cleaner and shorter.
Use only one Scanner and define it outside of the loop. You don't need more than one Scanner for the same input. Also, initializing a Scanner with every loop is resource-consuming.
Use meaningful variable names. Programming should not only be efficient, but also easy to read. In this tiny code it's a minor issue but imagine having an entire program and, instead of adding features and bug-fixing, you had to search for the meaning of every variable.
Here's an optimized and working version of your code:
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Enter a number");
int input1 = scanner.nextInt();
scanner.nextLine(); // nextInt() doesn't move to the next line
System.out.println("Enter a second number:");
int input2 = scanner.nextInt();
scanner.nextLine();
System.out.println("Total sum is " + (input1 + input2)); /* Important to
surround the sum with brackets in order to tell the compiler that
input1 + input2 is a calculation and not an appending of
"Total sum is "*/
System.out.println("Do you want to continue? (Y/N)");
if (scanner.hasNext() && scanner.nextLine().equalsIgnoreCase("n"))
break;
}
scanner.close();
try (Scanner in = new Scanner(System.in)) {
boolean done = false;
while (!done) {
System.out.println("enter first number");
int d = in.nextInt();
System.out.println("enter second number");
int df = in.nextInt();
int kk = d + df;
System.out.println(String.format("total sum is %d", kk));
System.out.println("do you want to continue(y/n)?");
String cont = in.next();
done = cont.equalsIgnoreCase("n");
}
} catch(Exception e) {
e.printStackTrace();
}
I have code that is supposed to guess the user's number and it will narrow its search based on user input. The only issue is that within the while loop, the conditionals are not working with .equals. Instead, it skips to the else even when I type "less than". This is my code below, I am new to java so I might have made a mistake.
package reversedHiLo;
//Import utility
import java.util.*;
public class ReversedHiLo
{
public static void main(String[] args)
{
//create scanner class
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to reverse number guessing game, pick a number between 1 and 100 and type it below:");
int answer = sc.nextInt();
//Create the first guess
int guess = 1 + (int)(100*Math.random());
//Create an array that stores the range of the player's number
int[] range = new int[] {1,100};
//While loop that guesses the number
while(guess != answer)
{
System.out.println("Is your number greater than or less than " + guess + "?" + Arrays.toString(range));
String response = sc.next();
sc.nextLine();
//Conditionals to set the range of the guess
if(response.equals("less than"))
{
range[1] = guess;
}
else
{
range[0] = guess;
}
//Guess a new number based on the range
guess = range[0] + (int)((range[1] - range[0]) * Math.random());
}
//Final print
System.out.println("Your number was " + answer + ".\nThe computer's guess was: " + guess);
//Close scanner
sc.close();
}
}
There are two places where there is a problem:
The first one sc.nextInt() method - which only reads the int
value by keeps current reading buffer on the same line. So to
ignore/skip everything what is after int on the input line (which is
probably \n or \r\n if you only enter the number) you have to
use sc.nextLine().
The second one is sc.next() method - which
only reads first token(or simply word) from your line. That is
probably why you only get "less" value assigned to response
and that will never be .equals to "less than". So you will
have to replace sc.next() one with sc.nextLine() and remove
unnecessary sc.nextLine() from the next line.
Hope this should be clear now and you have a better understanding of what happens when you call these function. If not then I strongly advise you to have a look into Scanner class, read JavaDocs on write multiple tests around it to get a better understanding of what is going on.
If my explanation is still not clear have a look at the code I have modified for you below:
public static void main(String[] args)
{
//create scanner class
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to reverse number guessing game, pick a number between 1 and 100 and type it below:");
int answer = sc.nextInt();
sc.nextLine(); // This one is necessary to ignore everything on the same line as your number was typed in
//Create the first guess
int guess = 1 + (int)(100*Math.random());
//Create an array that stores the range of the player's number
int[] range = new int[] {1,100};
//While loop that guesses the number
while(guess != answer)
{
System.out.println("Is your number greater than or less than " + guess + "?" + Arrays.toString(range));
String response = sc.nextLine(); // This reads the whole input line
//Conditionals to set the range of the guess
if(response.equals("less than"))
{
range[1] = guess;
}
else
{
range[0] = guess;
}
//Guess a new number based on the range
guess = range[0] + (int)((range[1] - range[0]) * Math.random());
}
//Final print
System.out.println("Your number was " + answer + ".\nThe computer's guess was: " + guess);
//Close scanner
sc.close();
}
So I am creating simple program for my Java class and one of the last requirements is to have the program loop. I've done this before, but it was horribly inefficient and convoluted.
Basically, I used a switch case named start with values 0 and 1. If the user typed 0 a do-while loop would begin and if they typed 1, the program would terminate. The only problem with this is the user would have to type 0 for the program to even begin, and if they typed 1, I had to have a fail-safe changing the value of start to 3 or else an infinite loop would begin. Can someone help me find a better way of doing this? (Also, before anyone says anything about the way it is written, one of the requirements was that it HAD to be done within one executable class.)
(Also, Also: Could someone tell me the rules of indentation? I'm really horrible at it.)
Here is my code below:
/*
* Simple Java Survey Program
*/
import java.util.Scanner;
public class J2Strings {
public static void main(String[] args) {
// TODO Auto-generated method stub
// variables
String fName;
String lName;
String mName;
int age;
String say;
String fFood;
String fTV;
Scanner userInput = new Scanner(System.in);
System.out.println("Today you are going to take a small personal survey");
System.out.println("");
System.out.println("Begin by entering your first name: ");
fName = userInput.next();
System.out.println("Enter your last name:");
lName = userInput.next();
System.out.println("Enter your middle name:");
mName = userInput.next();
System.out.println("Enter your age:");
age = userInput.nextInt();
System.out.println("Enter your favorite saying:");
say = userInput.next();
System.out.println("Enter your favorite food:");
fFood = userInput.next();
System.out.println("Finally, enter your favorite TV show:");
fTV = userInput.next();
char f = fName.charAt(0);
char l = lName.charAt(0);
char m = mName.charAt(0);
System.out.println("Based on the information you entered, here are your initials: " + f + "." + m + "." + l);
System.out.println("This is how old you will be in 50 years: " + (age + 50));
}
}
Something like this
bool test = true;
while(test)
{
/*Your code here */
/*At the end you ask them if they want to try again*/
/*Then switch the boolean based on their answer*/
}
I hate Arrays
So I've been doing some coding and I've come up with an error (out of bounds exception) that I just can't seem to fix. I believe where I am saying 'array1[counter2][counter] = input2.nextLine();' is the problem but I don't know what is wrong! Help, I can't stand these Out of Bounds exceptions
The Idea for the program is an online phone book that you can add contacts, view them, and search by their first name, surname, and phone number.
Here's the code I'm using:
import java.util.Scanner;
import java.awt.*;
public class testMattWalker {
//
public static void main (String[] args){
//Declare all your variables here. Make sure to provide a comment explaining the purpose of each variable
Scanner input = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
Scanner input3 = new Scanner(System.in);
Scanner input4 = new Scanner(System.in);
int counter = 0;
int counter2 = 0;
boolean go = true;
//Temp VAriables for entry
String firstNameOfEntry = "";
String lastNameOfEntry = "";
String personPhoneNumber = "";
//
//create array
String [][] array1 = new String[5][3];
while (go) {
String choice = "";
System.err.println("\n\n\n\n\n\n\n\n\nDIDGITAL PHONE BOOK 2013");
System.out.println("1- Create phone book\n2- Display phone book\n3- Find person(s) by last name\n4- Find person(s) by first name\n5- Find person(s) by phone number\n6- Exit application");
choice = input.nextLine();
if (choice.equals("1") && counter2 != 6) {
System.err.println("\n\n\n\n\nPHONE BOOK ENTRY CREATOR:");
System.out.println("Please enter the first name of the person you wish to enter: ");
array1[counter2][counter] = input2.nextLine();
counter++;
System.out.println("Please enter the last name of the person you wish to enter: ");
array1[counter2][counter] = input3.nextLine();
counter++;
System.out.println("Please enter the phone number of this person: example:9057773344");
array1[counter2][counter] = input4.nextLine();
counter++;
counter2++;
}else if (choice.equals("2")) {
}else if (choice.equals("3")) {
}else if (choice.equals("4")) {
}else if (choice.equals("5")) {
}else if (choice.equals("6")) {
}
}
}// end of main
}// end of class
I know it's not close to done but I'm the kind of guy who likes to fix everything before moving on so any help would be appreciated! (:
You set the second dimension of your array as 3, but in your code you add 1 to counter 3 times, meaning it goes out of bounds of the array after the first iteration of the code.
As ljgw said array indexes start at 0, so a dimension of 3 means the corresponding indexes are 0,1 and 2.
Remember that array indexes start with 0. So: 5 is already out-of-bounds for counter2.
This question already has answers here:
Java being able to choose wether to add or subract
(3 answers)
Closed 9 years ago.
the idea is that if for example they choose * if will say wrong operator please try again but at the moment that is just looping if I choose the wrong operator and also if I choose the right operator the program needs to end , I cant seem to figure it out
my code is as follows
import java.util.Scanner;
public class Uppgift5 {
public static void main (String[] args){
int tal1, tal2;
int sum = 0;
int sub=0;
String operator;
Scanner input = new Scanner (System.in);
Scanner input2 = new Scanner (System.in);
System.out.println("write in first digit");
tal1 = input.nextInt();
System.out.println("Write in 2nd digit ");
tal2 = input.nextInt();
System.out.println("Enter + to add and - subtract ");
operator = input2.nextLine();
while (operator.equals("-") || operator.equals("+")|| operator.equals("*") || operator.equals(("/")) ){
if (operator.equals("+")){
sum = tal1+tal2;
System.out.println("the sum is " + sum);
}
else if (operator.equals("-")){
sub = tal1-tal2;
System.out.println("the subtracted value is " + sub);
}
if (operator.equals("*") || operator.equals("/")){
System.out.println("You have put in the wrong operator, your options are + or -");
}
}
}
}
Your problem is here:
operator = input2.nextLine();
while (operator.equals("-") || operator.equals("+")|| operator.equals("*") || operator.equals(("/")) )
Assume operator is +. The value of operator does not change within the while loop, so operator will always be +, and you have an infinite loop.
Your operator will never be different. For that reason, your loops never end. You should use if instead of while
Instead of using a while loop, use a do loop that starts before you read operator from the input and only loops back if operator is not + or -. Ideally the while at the end of the do loop should come before you attempt the calculation.
Well, of course your code never ends... because you have no stopping condition. Also, your looping condition is incorrect. As long as the operator is one of those values, the loop will run. Also, you never ask for an input inside the loop. The code below should work:
import java.util.Scanner;
public class tt {
public static void main (String[] args){
int tal1, tal2;
int sum = 0;
int sub=0;
String operator = "";
Scanner input = new Scanner (System.in);
Scanner input2 = new Scanner (System.in);
System.out.println("write in first digit");
tal1 = input.nextInt();
System.out.println("Write in 2nd digit ");
tal2 = input.nextInt();
System.out.println("Enter + to add and - subtract ");
while (true){
operator = input2.nextLine();
if (operator.equals("+")){
sum = tal1+tal2;
System.out.println("the sum is " + sum);
}
else if (operator.equals("-")){
sub = tal1-tal2;
System.out.println("the subtracted value is " + sub);
}
if (operator.equals("*") || operator.equals("/")){
System.out.println("You have put in the wrong operator, your options are + or -");
break;
}
}
}
}