if char equals a letter then execute a code - java

Please help I cannot run this block of code:
import java.util.Scanner;
public class Methods_in_java {
public static void main(String[] args) {
boolean gameover = true;
int score = 5000;
int Levelcomplete = 5;
int bonus = 100;
boolean prize = true;
System.out.println("Please enter your name");
Scanner lic = new Scanner(System.in);
String ab = lic.nextLine();
char fir = Character.toUpperCase(ab.charAt(1));
if(fir == 'A'){
prize = true;
}
Calculatescore(gameover,score,Levelcomplete,bonus,prize);
}
public static void Calculatescore(boolean gameover,int score,int levelcomplete,int bonus,boolean prize){
if(gameover){
int finalscore = score + (levelcomplete * bonus);
if (prize){
finalscore += 1000;
}
System.out.println("Your final score is "+ finalscore);
}
}
}

charAt is zero based.
You should use ab.charAt(0) if you use only a single char.
Another good advice is to start method names with a lower case and use the camelCase format.

String ab = lic.nextLine();
char fir = Character.toUpperCase(ab.charAt(1));
Is fir supposed to be the first character in the user String? In that case you want to make sure to take zero-based indexing into account:
char fir = Character.toUpperCase(ab.charAt(0));

You have initialized your prize variable as true that will remain always true even its meet if condition or not just change it to false.
and as you were accessing the String's 2nd character using charAt(1), the index starts from 0 and if you try using charAt(0) then you will access 1st character.
Just change your code to:
public class cn {
public static void main(String[] args) {
boolean gameover = true;
int score = 5000;
int Levelcomplete = 5;
int bonus = 100;
boolean prize=false;
System.out.println("Please enter your name");
Scanner lic = new Scanner(System.in);
String ab = lic.nextLine();
char fir = Character.toUpperCase(ab.charAt(0));
if(fir == 'A'){
prize = true;
}
Calculatescore(gameover,score,Levelcomplete,bonus,prize);
}
public static void Calculatescore(boolean gameover,int score,int levelcomplete,int bonus,boolean prize){
if(gameover){
int finalscore = score + (levelcomplete * bonus);
if (prize){
finalscore += 1000;
}
System.out.println("Your final score is "+ finalscore);
}
}
}

It would be helpful if you elaborated more on what your problem is,
do you have a run time error, a compile time error, or it the output just not what you'd expect.
Your problem may be that arrays start at 0 so the first letter is charAt(0).
Actually I believe another user mentioned that the prize variable was initialized to true. I believe that that is the issue and that answer should be marked correct.

Related

How can I use char/String as an aswer for yes or no on math question(n1>2, n1<n2)

Im struggling with that code.
how can I use string with yes/no on that question: n1>n2, n1<n2.
the operators also need to change.
import java.util.Scanner;
import java.util.Random;
public class s {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Random r = new Random();
int n1 = r.nextInt(10) + 1;
int n2 = r.nextInt(10) + 1;
int max = Math.max(n1, n2);
System.out.println("What is higher: "+n1+" or "+n2+" ");
int result = s.nextInt();
if(result==max)
System.out.println("Well done");
else
System.out.println("Wrong answer");
}
}
I tried a way to not use a lot of IF’S by splitting the two possible cases and not having many repeated coding lines.
By avoiding this situation, I started creating: random numbers, the random operator “>” or “<” and a boolean variable which value depends on the answer of the user.
Then I defined a variable called “reality” that will provide the correct answer, referring to which number is bigger or smaller than the other.
Finally, the program verifies if the answer of the user is the same to the reality printing the expected answer.
public static void main(String[] args) {
int bol_op= (int) Math.random()>0.5?1:0;
String operator= bol_op==1?">":"<";
int num1=(int) (Math.random()*100+1);
int num2=(int) (Math.random()*222+1);
String str_num1=num1+"";
String str_num2=num2+"";
Scanner sc= new Scanner(System.in);
System.out.println("********Logic Program**********");
System.out.println("Question: "+str_num1+operator+str_num2);
System.out.print("Answer (yes/no): ");
String answer =sc.nextLine().toLowerCase();
boolean value=false;
if(answer.equals("yes")){
value=true;
}
boolean reality=num1>num2?true:false;
if(bol_op==0){
reality=num1<num2?true:false;
}
if(reality==value){
System.out.println("Well done");
}
else{
System.out.println("Wrong answer");
}
}

How do i increment static variables in java

I'm very new to java but i have decent experience with c++ and python. So, I'm doing a question in which im required to implement an airplane booking system, which does the following -
1.initialize all seats to not occupied(false)
2.ask for input(eco or first class)
3.check if seat is not occupied
4.if seat is not occupied allocate seat else look for next seat
5.if economy seats are booked out, ask if user wants to bump up to first class
6.if user is negative display msg "next plane is in 3hrs"
but,
package oop;
import java.util.Arrays;
import java.util.Scanner;
public class AirplaneBooking {
private final static int MAX_ECO_SEATS = 5;
private final static int MAX_FIRST_CLASS_SEATS = 3;
private final static boolean[] ECO_SEATS = new boolean[MAX_ECO_SEATS];
private final static boolean[] FIRST_CLASS_SEATS = new boolean[MAX_FIRST_CLASS_SEATS];
private static int current_eco_seat = 0;
private static int current_first_class_seat = 0;
public static void initialilze_seats(boolean[] first_class_seats, boolean[] eco_class_seats){
Arrays.fill(first_class_seats, Boolean.FALSE);
Arrays.fill(eco_class_seats, Boolean.FALSE);
}
public static void display(boolean[] seats){
System.out.print("[");
for(boolean seat : seats){
System.out.print(seat + ",");
}
System.out.println("]");
}
public static void book_seat(boolean [] seats, int current_seat){
seats[current_seat] = true;
current_seat++;
System.out.println(current_seat);
}
public static int user_input() {
Scanner input = new Scanner(System.in);
System.out.print("Enter 1 for Economy class or 2 for First class : ");
int user_seat_prefrence = input.nextInt();
if (user_seat_prefrence == 1){
if(current_eco_seat < MAX_ECO_SEATS){
book_seat(ECO_SEATS, current_eco_seat);
}
else{
System.out.println("Looks like eco seats are full, would you like to book for first class insted(1/0) ?");
Scanner next_input = new Scanner(System.in);
int user_next_seat_prefrence = next_input.nextInt();
if (user_next_seat_prefrence == 1){
book_seat(FIRST_CLASS_SEATS, current_first_class_seat);
user_seat_prefrence = 2;
}
else{
System.out.println("next flight leaves in 3 hrs");
}
}
}
else if (user_seat_prefrence == 2){
if (current_first_class_seat < MAX_FIRST_CLASS_SEATS){
book_seat(FIRST_CLASS_SEATS, current_first_class_seat);
}
else{
System.out.println("Looks like first class seats are full, would you like to book economy instead?(1/0)");
int user_next_seat_prefrence = input.nextInt();
if (user_next_seat_prefrence == 1){
book_seat(ECO_SEATS, current_eco_seat);
user_seat_prefrence = 1;
}
else{
System.out.println("Next flight leaves in 3hrs");
}
}
}
else {
System.out.println("Enter valid option");
}
return user_seat_prefrence;
}
public static void print_boarding_pass(int user_seat_prefrence){
if (user_seat_prefrence == 1){
System.out.println("eco");
System.out.println(current_eco_seat - 1);
}
else{
System.out.println("first class");
System.out.println(current_first_class_seat - 1);
}
}
public static void main(String args[]){
initialilze_seats(FIRST_CLASS_SEATS, ECO_SEATS);
display(FIRST_CLASS_SEATS);
display(ECO_SEATS);
while(true){
int user_seat_prefrence = user_input();
print_boarding_pass(user_seat_prefrence);
display(FIRST_CLASS_SEATS);
display(ECO_SEATS);
System.out.print("book another seat:");
Scanner choice = new Scanner(System.in);
boolean book_another_seat = choice.nextBoolean();
if (book_another_seat == false)
break;
}
}
}
The problem i'm having with this code is if the seats for eco class(for example) are full, the program is supposed to ask if i want to book for first class instead and wait for my input, if I press 1 it should book in first class but the program does not await for my input and proceeds to else statement instead.
Also, i use a static variable current_eco_seat and current_first_class_seat to keep track of the current seat being booked, and i pass that static variable to book_seat function, the program then books the seat and increments the current_eco_seat or current_first_class_seat(depending which is passed) so that next seat can be booked in next interation. But the static variable does not get incremented at all.
These are the only problems i have with the program.
Any help is appreciated, thanks
As Java calls methods by value,
Your problem about static is you are passing the value of current_seat to the book_seat method, so changing the value doesn't affect that variable after returning from the method.
To solve it just call the method and do not pass your static vars. It's static, so you have access it from everywhere.
i.e:
public static void book_seat(boolean [] seats){
seats[current_seat] = true;
current_first_class_seat++;
System.out.println(current_seat);
}
Checking Inout stream
Not sure wether your question is related to "static" variables or more related to "How to handle Input Stream?".
Regarding:
if I press 1 it should book in first class but the program does not await for my input and proceeds to else statement instead.
You should think about "flushing" the Input Stream before reading again. flush-clear-system-in-stdin-before-reading
Method Parameter usage
On the other hand this method is wrong
public static void book_seat(boolean [] seats, int current_seat){
seats[current_seat] = true;
current_seat++;
System.out.println(current_seat);
}
this command has no affect, but printing an information to the User. The variable you used in the caller "current_eco_seat" will not change at all.
you don't need to insist incrementing the exact variable, just do the following :
make book_seat() to return incremented value
public static int book_seat(boolean [] seats, int current_seat) {
seats[current_seat] = true;
System.out.println(current_seat + 1);
return current_seat + 1;
}
set returned value to current_first_class_seat or current_eco_seat
if (current_first_class_seat < MAX_FIRST_CLASS_SEATS){
current_first_class_seat = book_seat(FIRST_CLASS_SEATS, current_first_class_seat);
}
else{
System.out.println("Looks like first class seats are full, would you like to book economy instead?(1/0)");
int user_next_seat_prefrence = input.nextInt();
if (user_next_seat_prefrence == 1){
current_eco_seat = book_seat(ECO_SEATS, current_eco_seat);
user_seat_prefrence = 1;
}
else{
System.out.println("Next flight leaves in 3hrs");
}
}
Then you can use book_seat() for both eco and first class reservations handling as previously you have intended.

I have one variable but Java considers them as two

I have initiated the variable 'answer' in the near header of the class.
Later on when, a random number within an entered range has been generated, that same variable gets a new different value (due to the random generator). But as you can see, the variable 'answer' is indicated in two different colors (blue vs light brown), and as you expect, the routines that I have made are therefore not working. Somehow answer is not equal to answer. What did I do wrongly???? (unfortunately here you don't see the difference in colors).
In eclipse the color of 'answer' at the very top static int answer = 0; is BLUE.
But the one int answer = ThreadLocalRandom.current().nextInt(1, userinput); is GREY
Here's my code:
package Package1;
import java.util.concurrent.ThreadLocalRandom;
import java.util.Scanner;
public class test6KOPIE
{
static int numberofattempts = 0;
static int maxnummerofattemptsallowed = 5;
static int answer = 0;
public static void main(String[] args)
{
if (answer == 0)
{
Scanner maxinput = new Scanner(System.in);
System.out.println("Under which number do you want to guess");
int userinput = maxinput.nextInt();
int answer = ThreadLocalRandom.current().nextInt(1, userinput);
System.out.println(answer);
main(args);
}
else if (numberofattempts < maxnummerofattemptsallowed)
{
Scanner higherlower = new Scanner(System.in);
System.out.println("Higher or Lower");
int digit = higherlower.nextInt();
if (answer == digit)
{
System.out.println("very well");
}
else {
if (answer > digit )
{
++numberofattempts;
System.out.println("Higher, you have " +(maxnummerofattemptsallowed - numberofattempts)+" attempt(s) left)");
System.out.println(numberofattempts);
main(args);
}
else
{
++numberofattempts;
System.out.println("Lower, you have " +(maxnummerofattemptsallowed - numberofattempts)+" attempt(s) left)");
main(args);
}
}
higherlower.close();
}
else {
System.out.println("Maximum number of attempts used, the answer was" +answer);
}
}
This is because you are re-initializing your answer variable by retyping int before it. If you simply want to reassign the value, the line should be:
answer=ThreadLocalRandom.current().nextInt(1, userinput);

Why won't my program loop correctly?

I'm new to programming and I'm making a guessing game where the program randomly generates a number between 1 and 10, the user then is asked to guess what the number is, the user should be able to keep guessing until he guesses correctly and the system asks them if they want to play again,
In my code I've printed the number that the system has randomly generated so that it is quicker to complete the game whilst testing. When I try and execute the program and enter the number that the system has generated the message that they are correct and asking if they want to play again does not come up.
Any help would be greatly appreciated!
Thank you in advance,
(Also, anything wrong with this question just tell me, it's my first time asking on here)
Here is my code,
import java.util.Scanner;
import java.util.Random;
public class GuessingGame1 {
public static int randomizer() {
Random rand = new Random();
int num = rand.nextInt(10)+1;
System.out.println(num);
int count = 0;
return num;
}
public static int userInput() {
System.out.println("I've thought of a number between 1 and 10");
System.out.println("Enter your guess...");
Scanner scan = new Scanner(System.in);
int guess = scan.nextInt();
return guess;
}
public static String compare() {
int count = 0;
String result = null;
if (userInput() == randomizer()) {
System.out.println("You guessed it - I was thinking of " + randomizer());
count++;
result = "It took you " + count + " guesses.";
return result;
}
else if (userInput() > randomizer()) {
result = "Lower!";
count++;
return result;
}
else if (userInput() < randomizer()) {
result = "Higher";
count++;
}
return result;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scanLine = new Scanner(System.in);
String playAgain = "";
do {
randomizer();
do {
userInput();
compare
} while (userInput() != randomizer());
System.out.println("Play again? Yes/No");
playAgain = scanLine.nextLine();
} while (playAgain.equalsIgnoreCase("yes") || playAgain.equalsIgnoreCase("y"));
}
}
The problem is that you call twice to Randomizer!
call randomizer once as parameter to compare and return boolean from compare for a match.
You must change your methods something like this
public static String compare(int a,int b) {
int count = 0;
String result = null;
if (a == b) {
System.out.println("You guessed it - I was thinking of " + b);
count++;
result = "It took you " + count + " guesses.";
return result;
}
else if (a > b) {
result = "Lower!";
count++;
return result;
}
else if (a < b) {
result = "Higher";
count++;
}
return result;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scanLine = new Scanner(System.in);
String playAgain = "";
int a;
int b;
do {
do {
a=userInput();
b= randomizer();
System.out.println(compare(a,b));
} while (a != b);
System.out.println("Play again? Yes/No");
playAgain = scanLine.nextLine();
} while (playAgain.equalsIgnoreCase("yes") || playAgain.equalsIgnoreCase("y"));
}
}
you have left the () in compare and the count will always be zero as it is been initialized when the compare function is called.

Java for/while loop for unique integer

Need help figuring out what's wrong with my code. I am taking a
beginning java course so I have to use simple code.
an integer N is unique if there exists an integer i such that: N = i*i
+ i Here are some examples of unique numbers: 2 (because 2 = 1*1 + 1) 6 (because 6 = 2*2 + 2) 12 (because 12 = 3*3 + 3)
Asks the user to enter an integer N. Prints out whether that number is
a unique number. If not print not a unique number
import java.util.Scanner;
public class task4 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.printf("Enter an integer N: ");
int N = in.nextInt();
boolean unique = true;
int i = 1;
while ((i*i)+i == N)
{
if ((i*i)+i != N)
{
unique = false;
i++;
}
}
if (unique)
{
System.out.printf("%d is unique.\n",N);
}
else
{
System.out.printf("%d is not unique.\n", N);
}
}
}
Your while loop will only evaluate if 1*1 + 1 == N is true. I don't want to give you the answer directly so I will give you a hint: how can you change the while loop to return true for every value up to N?
Also try redoing the inside of the while loop. Think about how you can make it to make unique true if any value of i is valid.
This should be of some hlep to you. Check for i should always be lesser than N in the while loop. At least it has got some exit condition (which is logical). In your case there is no exit condition out of while loop when your (i*i)+i grows beyond N.
import java.util.Scanner;
public class Task4 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.printf("Enter an integer N: ");
int N = in.nextInt();
boolean unique = false;
int i = 1;
while (((i*i)+i) <= N)
{
if ((i*i)+i != N) {
i++;
} else {
unique = true;
break;
}
}
if (unique)
{
System.out.printf("%d is unique.\n",N);
}
else
{
System.out.printf("%d is not unique.\n", N);
}
}
}
Maybe you can try this:
import java.util.Scanner;
public class task4 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.printf("Enter an integer N: ");
int N = in.nextInt();
boolean unique = true;
double sd = Math.sqrt(N);
double fd = Math.floor(sd);
if(sd * (sd+1) != N){
unique = false;
}
if (unique)
{
System.out.printf("%d is unique.\n",N);
}
else
{
System.out.printf("%d is not unique.\n", N);
}
}
}

Categories