My code has to guess the hidden number from 0 to 100 in 7 attempts. And every time I need to call the same operations again. How can I move these operations into a separate method and call them from there?
public class Main {
public static void main(String[] args) throws IOException {
int min = 0;
int max = 100;
int midrange = Math.round((min + max)/2);
String strInput = "";
Scanner scan = new Scanner(System.in);
while (!strInput.equals("1")){
System.out.println("Guess a number from 0 to 100: I'll guess it in 7 attempts! Enter 1 to continue:");
strInput = scan.nextLine();
}
while (!strInput.equals("+") && !strInput.equals("-") && !strInput.equals("=")){
System.out.println("Is this number greater than, less than or equal to " + midrange + "? " +
"Enter '+', if it's greater, '-' if it's less and '=' if it's equal:");
strInput = scan.nextLine();
}
if (strInput.equals("=")) System.out.println("Great! Thank you for the game.");
else if (strInput.equals("+")){
// reduce the range
min = midrange;
// find a new midrange
midrange = Math.round((min + max)/2);
} else if (strInput.equals("-")){
max = midrange;
midrange = Math.round((min + max)/2);
}
strInput = "";
while (!strInput.equals("+") && !strInput.equals("-") && !strInput.equals("=")){
System.out.println("Is this number greater than, less than or equal to " + midrange + "? ");
strInput = scan.nextLine();
}
// ... and so on until the correct number is found.
}
}
You don't need multiple while loops. Just check for equality and put your if-else-block into the while loop. If you guessed the number correct just break out of the loop.
public static void main(String[] args) throws IOException {
int min = 0;
int max = 100;
int midrange = Math.round((min + max) / 2);
String strInput = "";
Scanner scan = new Scanner(System.in);
System.out.println("Guess a number from 0 to 100: I'll guess it in 7 attempts! Enter 1 to continue:");
strInput = scan.nextLine();
while (!strInput.equals("=")) {
System.out.println("Is this number greater than, less than or equal to " + midrange + "? " +
"Enter '+', if it's greater, '-' if it's less and '=' if it's equal:");
strInput = scan.nextLine();
if (strInput.equals("=")) {
System.out.println("Great! Thank you for the game.");
break;
} else if (strInput.equals("+")) {
min = midrange;
midrange = Math.round((min + max) / 2);
} else if (strInput.equals("-")) {
max = midrange;
midrange = Math.round((min + max) / 2);
}
}
}
Related
Im trying to stop a loop that takes integers after typing in the console "End", but i cant seem to find a way to do it.
Scanner scan = new Scanner(System.in);
int bottles = Integer.parseInt(scan.nextLine()) * 750;
int cnt = 1;
int platesTotal;
int potsTotal;
int nrPlates = 0;
int nrPots = 0;
while(true){
int plates = scan.nextInt();
platesTotal = plates * 5;
if(cnt%3==0) {
int pots = scan.nextInt();
nrPots = nrPots + pots;
nrPlates = nrPlates + pots;
potsTotal = pots * 15;
if (bottles < potsTotal + platesTotal) {
System.out.println("Not enough detergent, " + (potsTotal + platesTotal - bottles) + " ml. more necessary!");
break;
}
else
if(bottles >= potsTotal + platesTotal) {
String enough = scan.nextLine();
if (enough.equals("End")) {
if (bottles >= potsTotal + platesTotal) {
System.out.println("Detergent was enough!");
System.out.println(nrPlates + " dishes and " + nrPots + "pots were washed.");
System.out.printf("Leftover detergent %d ml.", bottles - potsTotal - platesTotal);
break;
}
}
}
}
cnt++;
}
after inputting the string ("End"), it needs to show me the total of dishes and pots, and how much detergent it has left, and if the required amount of detergent is more than the available amount, it needs to show me how much more is needed.
Try this String enough = scan.next(); instead of scan.nextLine();
I would suggest printing messages to console to confirm to the user you want input. Otherwise, it'll just show a blank window. I would also suggest you define a boolean variable to escape the while loop while switching your enough to .next rather than .nextLine. This way, you redefine your boolean as false to break the while loop while also getting the output you desire to control your program output a bit more. This compiled with all entries of 1:
package com.climatedev.test;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("How many bottles?");
Scanner scan = new Scanner(System.in);
int bottles = scan.nextInt() * 750;
int cnt = 1;
int platesTotal;
int potsTotal;
int nrPlates = 0;
int nrPots = 0;
boolean run = true;
while(run){
System.out.println("How many plates?");
int plates = scan.nextInt();
platesTotal = plates * 5;
if(cnt%3==0) {
int pots = scan.nextInt();
nrPots = nrPots + pots;
nrPlates = nrPlates + pots;
potsTotal = pots * 15;
if (bottles < potsTotal + platesTotal) {
System.out.println("Not enough detergent, " + (potsTotal + platesTotal - bottles) + " ml. more necessary!");
break;
}
else
if(bottles >= potsTotal + platesTotal) {
System.out.println("Would you like to end the program? (Enter End)");
String enough = scan.next();
if (enough.equals("End")) {
if (bottles >= potsTotal + platesTotal) {
System.out.println("Detergent was enough!");
System.out.println(nrPlates + " dishes and " + nrPots + "pots were washed.");
System.out.printf("Leftover detergent %d ml.", bottles - potsTotal - platesTotal);
run = false;
System.out.println("Goodbye");
break;
}
}
}
}
cnt++;
}
}
}
I also changed your bottles slightly to use nextInt, though that depends on your use. If you're thinking the end user might type something like "The number of bottles are..." that'll be better, but otherwise why not use a simpler nextInt call?
if you want to use a scanner object for both strings and numbers you must parse the number:
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
int num = Integer.parseInt(scanner.nextLine());
or you can have two scanners(one for strings and another for numbers):
Scanner strScanner = new Scanner(System.in);
Scanner numScanner = new Scanner(System.in);
String str = strScanner.nextLine();
int num = numScanner.nextInt();
I am creating a program that will determine and print the number of odd, even, and zero digits in an integer from the keyboard. I have tried a few different ways and have gotten the same result with each. I cannot get java to recognize 0 as 0, but only as an even number. Ex. 1005 will give 2 Odds and 2 Evens.
public static void main(String[] args) {
int odd = 0;
int even = 0;
int zero = 0;
int input;
Scanner scan = new Scanner (System.in);
System.out.println("Input an integer please: ");
input = scan.nextInt();
System.out.println("Your number is: " + input);
String x = Integer.toString(input);
for (input = 0; input < x.length(); input++){
char a = x.charAt(input);
System.out.println(a);
Character.getNumericValue(a);
if (a==0){
System.out.println ("+1 Zero");
zero++;
}
else if (a%2 == 0 && a>1){
System.out.println("+1 Even");
even++;
}
else {
System.out.println("+1 Odd");
odd++;
}
}
System.out.println("There are " + odd + " odd numbers!");
System.out.println("There are " + even + " even numbers!");
System.out.println("There are " + zero + " zero numbers!");
}
you haven't assigned Character.getNumericValue(a) to int value .
char a = x.charAt(input);
System.out.println(a);
int y= Character.getNumericValue(a);
if (y==0){
System.out.println ("+1 Zero");
zero++;
}
else if (y%2 == 0 && y>1){
System.out.println("+1 Even");
even++;
}
else {
System.out.println("+1 Odd");
odd++;
}
the Character.getNumericValue(a); method returns an int. It does not implicitly change the parameter (the character variable 'a' in this case).
Thus, you should compare the return value of the getNumericValue method and not the original character.
I basically want to be able to loop an X + Y = Z equation until the user inputs something other than an integer, like the letter "A" and also when having any number make the loop stop displaying a message.
Also, I am confused on how to randomly position the "?" which the user must input the correct answer.
For example
System.out.println("What is: " + num1 + " + ? = " + answer);
So far:
I am positioning the "?" manually through the IF statements. Can this be done in a more efficient way?
public static void main(String[] args) {
Random rand = new Random();
Scanner input = new Scanner(System.in);
int num1, num2, number3, answer;
do {
num1= 1 + rand.nextInt(10);
num2= 1 + rand.nextInt(10);
answer= num1 + num2;
System.out.println("What is: " + num1 + " + ? = " + answer);
number3= input.nextInt();
if (number3 == num2)
System.out.println("That is correct");
else
System.out.println("That is wrong");
num1= 1 + rand.nextInt(10);
num2= 1 + rand.nextInt(10);
answer= num1 + num2;
System.out.println(num1 + " + ? = " + answer);
number3= input.nextInt();
} while(number3 !=0);
}
Here is one way to do it:
public static void main(String[] args) {
Random rand = new Random();
Scanner scanner = new Scanner(System.in);
int[] xyz = new int[3];
String[] display = new String[3];
int answer, position;
do {
xyz[0] = 1 + rand.nextInt(10);
xyz[1] = 1 + rand.nextInt(10);
xyz[2] = xyz[0] + xyz[1];
for (int i = 0; i < xyz.length; i++)
display[i] = String.valueOf(xyz[i]);
position = rand.nextInt(3);
display[position] = "?";
System.out.println("What is: " + display[0] + " + " + display[1] + " = " + display[2]);
do {
System.out.println("Please enter an integer or 'S' to stop");
String input = scanner.nextLine();
if (input.equals("S")) {
scanner.close();
System.out.println("Stopped");
return;
}
else if (input.matches("\\d+")) { // \\d+ means "a digit (0-9) once or more
answer = Integer.parseInt(input);
break;
}
} while (true);
if (answer == xyz[position])
System.out.println("That is correct");
else
System.out.println("That is wrong");
} while (true);
}
Notes:
I use an inner do-while loop to repeatedly check the input and ask the user for a valid input.
I use 2 arrays: one for storing the numbers and another for storing the display values.
I also added a stop condition since the outer loop is infinite. Always close the Scanner when you finish.
I randomly pick 1 of 3 positions for the "?".
I would like to write a game about who would take the last marble and I've successfully run it. But when I attempted to add some error messages to it, such as showing "Incorrect range" when the inputs are out of range, it doesn't work properly. I know the problem is due to the incorrect recognition of variable "totalNum", but how to solve it? Thanks in advance :)
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int pn = 1;
System.out.print("Intial no. of marbles [10 ~ 100]: ");
int totalNum = in.nextInt();
int input = 0;
int from = 1;
int to = totalNum/2;
if (totalNum < 10||totalNum > 100) {
System.out.println("Incorrect range. Try again!");
System.out.print("Intial no. of marbles [10 ~ 100]: ");
totalNum = in.nextInt();
}
else {
while (totalNum > 1) {
totalNum = in.nextInt();
System.out.print("Player" + pn + " [" + from + " ~ " + to + "]: ");
input = in.nextInt();
if (input < from||input > to) {
System.out.println("Incorrect range. Try again!");
continue;
}
totalNum = totalNum - input;
System.out.println("Remaining no. of marbles: " + totalNum);
if (pn == 1) {
pn = 2;
}
else {
pn = 1;
}
}
}
System.out.println("Player" + pn + " takes the last marble.");
if (pn == 1) {
pn = 2;
}
else {
pn = 1;
}
System.out.println("Player" + pn + " wins!");
}
I imagine this line in the while loop is the problem:
totalNum = in.nextInt();
It keeps trying to take the next input from the user but there isn't a second integer. Not sure what happens after that.
Also, your entire program seems to be roughly equivalent to doing
totalNum%2+1
and printing the answer.
I'm trying to write a java code in java that has following output.
---JGRASP exez: java Guess
Is the number 50? H
Ia the number 75? L
Is the number 62? L
Is the number 56? L
Is the number 53? L
Is the number 51? C
It took me 6 guesses!
---JGRASP: operation complete.
As you see it always cuts range in half.I spent hours trying to figure it out without results.I would really appreciate if you could at least give a hint.Here's my unsuccessful attempt to write the code.
import java.util.Scanner;
public class GuessNumber
{
public static void main(String[]args)
{
int num1 = 0,num2 = 100,guesses = 0;
String answer;
boolean correct = false;
Scanner keyboard = new Scanner(System.in);
do{
System.out.print("Is the number " + <?> + "? "); //have no idea
answer = keyboard.next();
if(answer.equalsIgnoreCase("C")) {
correct = true;
guessses++;
}
else if(answer.equalsIgnoreCase("H")){
? = (num1 + num2) / 2; //lost here
guesses++;
}
else if(answer.equalsIgnoreCase("L")){
? = (num1 + num2) / 2; //lost here
guesses++;
}
}while(correct == false);
System.out.print("It took me " + guesses + " guesses!");
}
}
public static void main(String[]args)
{
Random randomNumber = new Random();
int num1 = 0,num2 = 100,guesses = 0, guess=0;
String answer;
boolean correct = false;
Scanner keyboard = new Scanner(System.in);
do{
guess=randomNumber.nextInt(num2-num1) + num1;
System.out.print("Is the number " + guess + "? ");
answer = keyboard.next();
if(answer.equalsIgnoreCase("C")) {
correct = true;
guessses++;
}
else if(answer.equalsIgnoreCase("H")){
num1 = guess;
guesses++;
}
else if(answer.equalsIgnoreCase("L")){
num2 = guess;
guesses++;
}
}while(correct == false);
System.out.print("It took me " + guesses + " guesses!");
}
Try this, what it does is that, while the answer is not correct, It will take in num1(the min value for the guess) and num2(the max value for the guess) and find their average. If the number is higher than the latest guess, we set the lower bound to the latest guess, if it's lower, we set the upper bound to the latest guess.
import java.util.Scanner;
public class GuessNumber{
public static void main(String[]args)
{
int num1 = 0,num2 = 101,guesses = 0, guess=0;
String answer;
boolean correct = false;
Scanner keyboard = new Scanner(System.in);
do{
guess=(num1+num2) /2 > 0? (num1+num2) /2:1;
System.out.print("Is the number " + guess + "? ");
answer = keyboard.next();
if(answer.equalsIgnoreCase("C")) {
correct = true;
guesses++;
}
else if(answer.equalsIgnoreCase("H")){
num1 = guess;
guesses++;
}
else if(answer.equalsIgnoreCase("L")){
num2 = guess;
guesses++;
}
}while(correct == false);
System.out.print("It took me " + guesses + " guesses!");
}
}