User input upperCase and lowerCase - Java - java

I am attempting to take an input of A or B in either Uppercase or LowerCase to follow on through the if statement. I can't figure out how to do this. At the moment, it's only taking in UpperCase A or B. Looked around the forum and the class notes, came up with nothing. Any help would be appriciated!
I tried using toUpperCase() but don't think i am putting it in the right place. It keeps giving me an error
import java.util.Scanner;
public class printNumber{
public static void main (String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Please select an option between A or B: ");
char user = input.next().charAt(0);
System.out.println("You have selected " +user+ " : ");
if (user == 'A'){
for(int n=1; n<=100; n++){
if((n%2)==0)
System.out.println(n);
}
}
else if (user =='B'){
for (int x =1; x<=100; x=x+2){
System.out.println(x);
}
}
else
System.out.println("Error, please try again!");
}
}

import java.util.Scanner;
public class printNumber{
public static void main (String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Please select an option between A or B: ");
String opt=input.nextLine();
System.out.println("You have selected " +user+ " : ");
if (opt.equalsIgnoreCase("A")){
for(int n=1; n<=100; n++){
if((n%2)==0)
System.out.println(n);
}
}
else if (opt.equalsIgnoreCase("B")){
for (int x =1; x<=100; x=x+2){
System.out.println(x);
}
}
else
System.out.println("Error, please try again!");
}
}
or you can simply use
import java.util.Scanner;
public class printNumber{
public static void main (String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Please select an option between A or B: ");
String opt=input.next();
System.out.println("You have selected " +user+ " : ");
if (opt == "A" || opt == "a"){
for(int n=1; n<=100; n++){
if((n%2)==0)
System.out.println(n);
}
}
else if (opt == "B" || opt == "b"){
for (int x =1; x<=100; x=x+2){
System.out.println(x);
}
}
else
System.out.println("Error, please try again!");
}
}

You can use
char user = input.next().toUpperCase().charAt(0);

Try this
if (user == 'A' || user == 'a')
The same for 'B'

You are calling next() method of Scanner class, which returns String, so rather than converting it into a character you can use equalsIgnoreCase() method on the input String for validation. But always check the length of the input string and show error message if the length of the string entered by user is greater than 1.
"a".equalsIgnoreCase("A") and "a".equalsIgnoreCase("a") will be always true.

Related

Guessing a number

I want to create a program that gives you three tries to find any given number. It's going to essentially be a guessing game. The problem is, I have to do this without any loops. So far, I'm only able to get input from the user, read that input and tell them if they've won or 'lost' the game. The program only runs once and stops(as expected).
I was told that it could be done without loops, albeit with a lot more code. Can you guys let me know what I'm doing wrong here and give me some pointers on what I should change? If you need clarification let me know.
Thanks.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner ran = new Scanner(System.in);
System.out.println("Enter a number: ");
int x = ran.nextInt();
if (x < 3) {
System.out.println("Too low. Try again.");
System.out.println("Enter a number: ");
} else if (x > 3) {
System.out.println("Too high. Try again");
} else if(x == 3) {
System.out.println("You win. Nice job.");
} else {
System.out.println("You lose");
}
System.out.println("Number Guessing Game (c) 2017 Anna Gibson");
}
}
You can do this using recursion. See this program. Find explanations within comments.
import java.util.Scanner;
public class HelloWorld {
private static Scanner ran = new Scanner(System.in);
//this is number of tries you want to give to user
private static int counter = 5;
//The actual number
private static final int NUM = 3;
public static boolean guessingMachine() {
//counter indicates that number of attempts remaining
if(counter == 0) {
return false;
}
counter--;
System.out.println("Enter a number: ");
int x = ran.nextInt();
if (x < NUM) {
System.out.println("Too low. Try again.");
//try again... call this method again
return guessingMachine();
} else if (x > NUM) {
System.out.println("Too high. Try again");
//try again... call this method again
return guessingMachine();
} else {
//x == NUM success
return true;
}
}
public static void main(String[] args) {
boolean result = guessingMachine();
if(result)
System.out.println("You win. Nice job.");
else
System.out.println("You lose");
System.out.println("Number Guessing Game (c) 2017 Anna Gibson");
}
}
You could next conditions:
get user input
if input is correct, congratulation user and exit
else
get user input //second attempt
if input is correct, congratulation user and exit
...
You can continue from there. The code you provided, where you tell the user if they are too high or low, would have to be included in each of the branches of the pseudocode above.
I think the main purpose of this exercise is intended for you to strengthen your nested if-else concepts.
import java.util.Scanner;
public class HelloWorld{
public static void main(String []args){
int num=3;
int count=1;
Scanner ran = new Scanner(System.in);
System.out.println("Enter a number: ");
int x = ran.nextInt();
if(x>num || x<num)
{
System.out.println("incorrect guess");
count++;
System.out.println("Enter a number: ");
x = ran.nextInt();
if(x>num || x<num)
{
System.out.println("incorrect guess");
count++;
System.out.println("Enter a number: ");
x = ran.nextInt();
if(x>num || x<num)
{
System.out.println("incorrect guess YOU LOSE");
}
else
{
System.out.println("YOU WIN");
}
}
else
{
System.out.println("YOU WIN");
}
}
if(x==num && count==1)
{
System.out.println("YOU WIN");
}
System.out.println("Number Guessing Game (c) 2017 Anna Gibson");
}
}

Simple Java Guessing program. Continuing

I am just playing around with java and wanted to make a simple program where the user; me has to guess/type in the correct number until it's correct. What can I do so the program can keep running, printing out "Make another guess" until the user/me puts in the correct number. Maybe a boolean? I'm not sure. This is what I have so far.
import java.util.Scanner;
public class iftothemax {
public static void main(String[] args) {
int myInt = 2;
// Create Scanner object
Scanner input = new Scanner(System.in);
//Output the prompt
System.out.println("Enter a number:");
//Wait for the user to enter a number
int value = input.nextInt();
if(value == myInt) {
System.out.println("You discover me!");
}
else {
//Tell them to keep guessing
System.out.println("Not yet! You entered:" + value + " Make another guess");
input.nextInt();
}
}
You might want to use a while loop to repeat some code:
while (value != myInt) {
System.out.println("Not yet! You entered: " + value + ". Make another guess");
value = input.nextInt();
}
System.out.println("You discovered me!");
This program would do the trick:
public static void main(String [] args){
int myInt = 2;
int value = 0;
Scanner input = new Scanner(System.in);
boolean guessCorrect = false;
while(!guessCorrect){
System.out.println("Not yet! You entered:" + value + " Make another guess");
value = input.nextInt();
if(value == myInt){
guessCorrect = true
}
}
System.out.println("You discover me!");
}
Simply introduce a loop.
import java.util.Scanner;
public class iftothemax {
public static void main(String[] args) {
int myInt = 2;
// Create Scanner object
Scanner input = new Scanner(System.in);
for(;;) {
//Output the prompt
System.out.println("Enter a number:");
//Wait for the user to enter a number
int value = input.nextInt();
if(value == myInt) {
System.out.println("You discover me!");
break;
}
else {
//Tell them to keep guessing
System.out.println("Not yet! You entered:" + value + " Make another guess");
}
}
}
}

if a user inputs a letter instead of a number tell them it's not a number

I'm making a guessing game, all the code works fine except for that I want them to make a number to guess between, I can't seem to figure out how to make it so that if the user inputs a letter like "d" instead of a number like "15" it will tell them they can't do that.
Code:
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
while (true) {
System.out.print("Pick a number: ");
int number = input.nextInt();
if (number != int) {
System.out.println("That's not a number");
} else if (number == int) {
int random = rand.nextInt(number);
break;
}
}
System.out.println("You have 5 attempts to guess the number or else you fail. Goodluck!");
System.out.println("");
System.out.println("Type 'begin' to Begin!");
System.out.print("");
String start = input.next();
if (start.equals("begin")) {
System.out.print('\f');
for(int i=1; i<6; i++) {
System.out.print("Enter a number between 1-" + number + ": ");
int number = input.nextInt();
if (number > random) {
System.out.println("Too Big");
System.out.println("");
} else if (number < random) {
System.out.println("Too Small");
System.out.println("");
} else if (number == random) {
System.out.print('\f');
System.out.println("Correct!");
break;
}
if (i == 5) {
System.out.print('\f');
System.out.println("You have failed");
System.out.println("Number Was: " + random);
}
}
} else if (start != "begin") {
System.out.print('\f');
System.out.println("Incorrect Command");
System.out.println("Please Exit Console And Retry");
}
}
}
use try catch
for example
try{
int a=sc.nextInt();
}catch(Exception e){
System.out.println("not an integer");
}
You could use nextLine() instead of nextInt() and check the out coming String if it matches() the regular expression [1-9][0-9]* and then parse the line with Integer.valueOf(str).
Like:
String str=input.nextLine();
int i=0;
if(str.matches("[1-9][0-9]*"){
i=Integer.valueOf(str);
} else {
System.out.println("This is not allowed!");
}
I hope it helps.
Do something like this:
Scanner scan = new Scanner(System.in);
while(!scan.hasNextInt()) { //repeat until a number is entered.
scan.next();
System.out.println("Enter number"); //Tell it's not a number.
}
int input = scan.nextInt(); //Get your number here

How to fix this code for a Java program that simulates a simple calculator?

Kindly help me to fix this code for a Java program that simulates a simple calculator.
It reads two integers and a character. If the character is a +, the sum is printed; if it is a -, the difference is printed; if it is a *, the product is printed; if it is a /, the quotient is printed; and if it is a %, the remainder is printed.
import java.util.Scanner;
class calc {
private int a,b,and;
private char c;
public static void main (String args[])
{
System.out.println ("Enter the first Integer");
Scanner scan = new Scanner (System.in);
a=scan.nextInt();
System.out.println("Enter the second Integer");
b=scan.nextInt();
System.out.println("Enter the operation sign");
c=scan.nextChar();
if (c=='+')
and=a+b;
else if (c=='-')
and=a-b;
else if (c=='*')
and=a*b;
else if (c=='/')
and=a/b;
else if (c=='%')
and=a%b;
else
{
System.out.println("Wrong operation");
exit(0);
}
System.out.println("The result is "+ ans);
}
}
Couple of things:
Make all your variables static so that you can use them within main or i would suggest move them within main.
Use nextLine().charAt(0) instead of nextChar which isn't defined in Scanner.
Instead of newxInt(); use nextInt(); api of Scanner
out is a static field (note lower case o), so change System.Out to System.out.
do an import static java.lang.System.exit; so you could use exit(0); without any issues from compiler.
Edit: Just for OP (Make sure you give meaningful name to variables) -
import static java.lang.System.exit;
import java.util.Scanner;
public class calc {
public static void main(String args[]) {
int a, b, ans = 0;
char c;
System.out.println("Enter the first Integer");
Scanner scan = new Scanner(System.in);
a = scan.nextInt();
scan.nextLine();
System.out.println("Enter the second Integer");
b = scan.nextInt();
scan.nextLine();
System.out.println("Enter the operation sign");
c = scan.nextLine().charAt(0);
if (c == '+')
ans = a + b;
else if (c == '-')
ans = a - b;
else if (c == '*')
ans = a * b;
else if (c == '/')
ans = a / b;
else if (c == '%')
ans = a % b;
else {
System.out.println("Wrong operation");
exit(0);
}
System.out.println("The result is " + ans);
}
}
Output:
Enter the first Integer
10
Enter the second Integer
20
Enter the operation sign
+
The result is 30
Change
c=scna.nextChar();
to
c=scan.nextChar();
Also change
exit(0)
to
System.exit(0)
b=scan.newxInt(); to b=scan.nextInt();
Change all Out to out

How to add for loops to if statements?

In my code below I am not sure what order to put it in to work properly.
I first want it to print out for the user to select an option which it does, then if they select 1 it asks them their name and verifies it with the loop etc.
When I enter a name it starts to just loop the question enter your name and I don't know how to fix it.
Do I need to add more statements to my program, if I do then can I still use if statements for the user to select an option?
import java.util.Scanner;
public class username {
public static void main(String[] args) {
{
int UseLift;
int AuditReport;
int ExitLift;
int a;
UseLift = 1;
AuditReport = 2;
ExitLift = 3;
}
System.out.println("choose an option");
System.out.println("Uselift(1)");
System.out.println("see audit report(2)");
System.out.println("Exit Lift(3)");
Scanner d = new Scanner(System.in);
int a = d.nextInt();
Scanner kb = new Scanner(System.in);
// array containing usernames
String[] name = {"barry", "matty", "olly", "joey"}; // elements in array
if (a == 1) {
System.out.println(" Enter your name ");
}
String name1 = kb.nextLine();
boolean b = true;
int j = 0;// counter will start at 0
outerloop:
while (j < 3) {
System.out.println("Enter your name");
}
for (int i = 0; i < name.length; i++) {
if (name[i].equals(name1)) {
System.out.println("you are verified you may use the lift, calling lift ");
}
break;// to stop loop checking names
}
System.out.println("Username Invalid");
j++;
if (a == 2) {
System.out.println("");
}
if (a == 3) {
System.out.println(" Please Exit Lift ");
}
}
}
here you go:
public static void main(String... args) {
String[] verifiedNames = { "barry", "matty", "olly", "joey" };
System.out.println("choose an option");
System.out.println("Uselift(1)");
System.out.println("see audit report(2)");
System.out.println("Exit Lift(3)");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1:
scanner.nextLine(); // get '\n' symbol from previous input
int nameAttemptsLeft = 3;
while (nameAttemptsLeft-- > 0) {
System.out.println(" Enter your name ");
String name = scanner.nextLine();
if (Arrays.asList(verifiedNames).contains(name)) {
System.out.println("dear " + name + " you are verified " +
"you may use the lift, calling lift ");
break; // break out of loop
}
}
if (nameAttemptsLeft < 0) {
System.out.println("Username Invalid");
}
break;
case 2:
System.out.println("option 2");
break;
case 3:
System.out.println(" Please Exit Lift ");
break;
}
scanner.close();
}
Your while loop below:
while (j < 3) {
System.out.println("Enter your name");
}
will loop forever since j is not incrementing (j++). I believe you've mis-matched your curly braces at some point.

Categories