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.
Related
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);
}
}
}
I have a program that prompts a user for integers until they type a value to continue the program onto the next step. How would I increment a variable called count every time the user inputs an integer? I'm using count++ to increment the count amount by the way, I just don't know how to make it go up when the user puts in data.
Code so far
//variables
int num, count = 0, high, low;
Scanner userInput = new Scanner(System.in);
//loop
do {
System.out.print("Enter an integer, or -99 to quit: --> ");
num = userInput.nextInt();
high = num;
low = num;
//higher or lower
if(count > 0 && num > high)
{
high = num;
}
else if(count > 0 && num < low)
{
low = num;
}
else
{
System.out.println("You did not enter any numbers.");
}
} while (num != -99);
System.out.println("Largest integer entered: " + high);
System.out.println("Smallest integer entered: " + low);
It's simple. Just put count++ inside the while loop as follows,
// variables
int num, count = 0, high, low;
Scanner userInput = new Scanner(System.in);
// loop
do {
System.out.print("Enter an integer, or -99 to quit: --> ");
num = userInput.nextInt();
count++; // here it goes
high = num;
low = num;
// higher or lower
if(count > 0 && num > high)
{
high = num;
}
else if(count > 0 && num < low)
{
low = num;
}
else
{
System.out.println("You did not enter any numbers.");
}
} while (num != -99);
System.out.println("Largest integer entered: " + high);
System.out.println("Smallest integer entered: " + low);
You can put count++; anywhere in your do loop.
I understand why you're using it but why use the counter at all?
The code below uses a different technique to acquire integers from the User. It also ensures that the supplied number is indeed a integer that falls within the Integer.MIN_VALUE and Integer.MAX_VALUE range:
Scanner userInput = new Scanner(System.in);
String ls = System.lineSeparator();
int high = 0;
int low = Integer.MAX_VALUE;
int num;
String input = "";
while(input.equals("")) {
System.out.print("Enter an integer, (q to quit): --> ");
input = userInput.nextLine().toLowerCase();
if (input.equals("q")) {
if (low == Integer.MAX_VALUE) {
low = 0;
}
break;
}
if (!input.matches("^-?\\d+$")) {
System.err.println("Invalid Entry (" + input + ")! "
+ "You must supply an Integer (int) value!" + ls);
input = "";
continue;
}
boolean invalidInteger = false;
long tmpVal=0;
try {
tmpVal = Long.parseLong(input);
} catch(NumberFormatException ex) {
invalidInteger = true;
}
if (invalidInteger || tmpVal < Integer.MIN_VALUE || tmpVal > Integer.MAX_VALUE) {
System.err.println("Invalid Entry (" + input + ")! " + ls
+ "Number too large (Minimum Allowable: " + Integer.MIN_VALUE
+ " Maximum Allowable: " + Integer.MAX_VALUE + ")!" + ls
+ "You must supply an Integer (int) value!" + ls);
input = "";
continue;
}
num = Integer.parseInt(input);
if (num > high) {
high = num;
}
if (num < low) {
low = num;
}
input = "";
}
System.out.println("Largest integer entered: " + high);
System.out.println("Smallest integer entered: " + low);
If you want to keep track of how many entries the User made then you can still apply a counter if you like.
is it possible in Java to check if a certain input is between a certain range and also an integer?
I have written the following code:
public void getBetAmountFromUser() {
//Get Amount of Bet
int x = 0;
System.out.println("Your current pot is: " + potAmount);
System.out.println("Enter your bet amount: ");
x = input.nextInt();
//Error message if bet is larger than pot and less than 0
while (x>potAmount || x<0 || !(input.hasNextInt())){
System.out.println("Error - cannot bet less than 0 or more than " + potAmount + "..Enter your bet amount: ");
x = input.nextInt();
}
//Bet should be less than or equal to pot if 0 user quit
if (x > 0 && x <= potAmount) {
betAmount = x;
potAmount = potAmount - betAmount;
} else if (x == 0) {
System.out.println("You end the game with pot " + potAmount);
System.exit(0);
}
}
The following loop did not work on validating Integer
while (x>potAmount || x<0 || !(input.hasNextInt())){
System.out.println("Error - cannot bet less than 0 or more than " + potAmount + "..Enter your bet amount: ");
x = input.nextInt();
}
You can try to use String in lieu of int. Then, you can go ahead with again int using Integer.parseInt(x) because it's already been verified as being valid integer after do-while
String x;
String regex = "[0-9]+"; // to check the string only is made up of digits
int potAmount = 10;
Scanner input = new Scanner(System.in);
do {
System.out.println("Please input an integer");
x = input.next();
} while (!x.matches(regex) || Integer.parseInt(x) > potAmount || Integer.parseInt(x) < 0);
int validBet = Integer.parseInt(x);
/* .
.
. *\
Whenever I try to run the code, it gives me an error after I input how many tickets I would like to buy. This is for a lottery program. Here is the code
import java.util.Scanner;
public class Lottery {
public static void main(String[] args) {
//local data
String guess;
int numTickets;
int counter;
Scanner in = new Scanner(System.in);
//output
System.out.println("How many tickets would you like to buy?");
numTickets = in.nextInt();
for (counter = 0; counter < numTickets; counter++) {
System.out.println("Please enter your three numbers (e.g. 123): ");
guess = in.nextLine();
int randNum = (int) (Math.random() * 1000);
String randNumb;
randNumb = Integer.toString(randNum);
char ch1 = randNumb.charAt(0);
char ch2 = randNumb.charAt(1);
char ch3 = randNumb.charAt(2);
if (ch1 == guess.charAt(0) && ch2 == guess.charAt(1) && ch3 == guess.charAt(2)) {
System.out.print("Winner: " + randNumb);
System.out.print("Congratulations, both pairs matched. /n");
} else if (ch3 == guess.charAt(2) && ch2 == guess.charAt(1)) {
System.out.print("Winner: " + randNumb);
System.out.print("Congratulations, the end pair matched.");
} else if (ch1 == guess.charAt(0) && ch2 == guess.charAt(1)) {
System.out.print("Winner: " + randNumb);
System.out.print("Congratulations, the first pair matched.");
} else {
System.out.print("The Correct Number: " + randNumb);
}
System.out.println("\t Sorry, no matches, You only had");
System.out.println("\t one chance out of 100 to win anyway.");
}
}
}
Exception:
Exception in thread \"main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 0 at
java.lang.String.charAt(String.java:658) at
lottery.Lottery.main(Lottery.java:32)
C:\Users\Ben\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53:
Java returned: 1
This is the exception error displayed when I try to run the program.
Help would be much appreciated!
The error is caused by the behaviour of nextInt method of the Scanner. In addition, your code has other errors as well.
The nextInt method only reads the next integer and nothing else. This means that the new line character (\n or \r or \r\n depending on the OS) is not read. This is fine until you call nextLine. nextLine reads every character until it encounters a new line character. So nextLine sees this unread new line character and stops reading any further and it returns an empty string, which is then put into your guess variable. When you try to access the first character of guess using charAt(0), it crashes because guess does not have any characters.
I suggest you use Integer.parseInt(in.nextLine()) to read an integer from the user.
I've fixed the code for you:
String guess;
int numTickets;
int counter;
Scanner in = new Scanner(System.in);
//output
System.out.println("How many tickets would you like to buy?");
numTickets = Integer.parseInt(in.nextLine());
Random rand = new Random();
for (counter = 0; counter < numTickets; counter++) {
System.out.println("Please enter your three numbers (e.g. 123): ");
guess = in.nextLine();
int randNum = rand.nextInt(1000);
String randNumb = String.format("%03d", randNum);
char ch1 = randNumb.charAt(0);
char ch2 = randNumb.charAt(1);
char ch3 = randNumb.charAt(2);
if (ch1 == guess.charAt(0) && ch2 == guess.charAt(1) && ch3 == guess.charAt(2)) {
System.out.print("Winner: " + randNumb);
System.out.print("Congratulations, both pairs matched. /n");
} else if (ch3 == guess.charAt(2) && ch2 == guess.charAt(1)) {
System.out.print("Winner: " + randNumb);
System.out.print("Congratulations, the end pair matched.");
} else if (ch1 == guess.charAt(0) && ch2 == guess.charAt(1)) {
System.out.print("Winner: " + randNumb);
System.out.print("Congratulations, the first pair matched.");
} else {
System.out.print("The Correct Number: " + randNumb);
}
System.out.println("\t Sorry, no matches, You only had");
System.out.println("\t one chance out of 100 to win anyway.");
}
As you can see, I made other improvements. Firstly, Math.random() * 1000 can return non three digit numbers so I changed it so that it uses a Random object. Using rand.nextInt(900) + 100 only generates three digit numbers.
Secondly, I used String.valueOf(randNum) as XtremeBaumer has said in the comments.
Hello my purpose is this:
Write a method that can accept values only between 10 and 50.Sample execution:Enter a number between 10 and 50Enter a number: 5Enter a number between 10 and 50Enter a number: 12Number Entered: 12.Enter a number: 0Good ByeSo as you can see it only finishes when user enters 0.And it says different things when number is between 10 and 50 or not.I deleted again my code and started but i got stuck on some points and i gave up.My final code was:
import java.util.Scanner;
public class A{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter case number: ");
int caseVal = scan.nextInt();
switch(caseVal){
case 1:
System.out.println("Enter a number between 10 and 50");
System.out.println("Enter a number: ");
int num = scan.nextInt();
betweenMethod(num);
if(num == 0){
System.out.println("Good Bye");
break;
}
while(num != 0){
betweenMethod(num);
}
break;
case 2:
System.out.println("Enter a number to display its divisors: ");
int x = scan.nextInt();
System.out.println("The divisors of " + x + " are:");
divisorsMethod(x);
break;
}
scan.close();
}
public static void divisorsMethod(int a){
if(a <= 0)
System.out.println("The number should be greater than 0");
else{
for(int b = 1; b <= a; b++){
if(a % b == 0 && b != a)
System.out.print(b + ", ");
else if(b == a)
System.out.println(b);
}
}
}
public static void betweenMethod(int a){
Scanner inputscan = new Scanner(System.in);
if(a >= 10 && a <= 50){
System.out.println("Enter a number:");
a = inputscan.nextInt();
}
else if((a < 10 || a > 50) && a != 0){
System.out.println("Enter a number between 10 and 50");
System.out.println("Enter a number:");
a = inputscan.nextInt();
}
else{
System.out.println("Good Bye");
}
inputscan.close();
}
}
Sorry for uncut version.It is case 1.Every time i tried it didnt work fully.If anyone can help i would appreciate it.I'm sorry if i didnt write this question in rules.(Sorry for the grammar as well)THIS IS WHERE I AM STUCK= When i type 0 it doesnt say GoodBye and end the loop.Thats where i need help.TO EVERYONE THAT NEEDS ANSWER TOO:I figured out what to do.Basically we say while its not equal to zero right?I wrote a new method that (after last inputscan for variable)checks if the number is zero and prints good bye.So with this way it prints good bye and it goes to starting.But it cannot do anythink else because we said while not equal to 0.Anyway thats one solution.
Don't close() System.in
When you call inputscan.close() that closes the underlying InputStream, which is System.in.
Return the Value
Your method should be prompting for input between two values and returning a single value. Also, you could move your Scanner to a static (or class) field. Something like
private static Scanner inputscan = new Scanner(System.in);
public static int betweenMethod(final int a, final int b) {
int min = Math.min(a, b);
int max = Math.max(a, b);
while (true) {
System.out.printf("Please enter a number between %d and %d%n", min, max);
int in = inputscan.nextInt();
if ((in == 0) || (in >= min && in <= max)) {
return in;
}
}
}
Primitives1 are Passed-By Value
You need to assign the result of the call back to your value when you loop. Something like,
int num = betweenMethod(10, 50);
while (num != 0) {
System.out.printf("Number Entered: %d.%n", num);
num = betweenMethod(num);
}
System.out.println("Good Bye");
break;
1and Everything Else in Java.