So here's a simple code to adjust the right "st", "nd", "rd", "th" with the input number. It's placed in a loop for a reason. Nevermind that.
System.out.println("How many?");
int num = x.nextInt();
for(int i=1;i<=num;i++){
System.out.print("Enter the " + i);
System.out.println(i==1? ("st"):(i==2? "nd":i==3? "rd":"th") + " number!");
}
when num is input as 5 here's the output:
Enter the 1st
Enter the 2nd number!
Enter the 3rd number!
Enter the 4th number!
Enter the 5th number!
Question is where's "number!" with the case "1st"??
You forgot a pair of braces, change:
System.out.println(i==1? ("st"):(i==2? "nd":i==3? "rd":"th") + " number!");
to:
System.out.println((i==1? ("st"):(i==2? "nd":i==3? "rd":"th")) + " number!");
^ ^
Notice the condition of your print :
i == 1 ? ("st") : ((i==2? "nd":i==3? "rd":"th") + " number!")
^ ^
true false
I added parenthesis to the false part so it is easier for you to understand.
I believe what you want is :
(i == 1 ? ("st") : (i==2? "nd":i==3? "rd":"th")) + " number!"
^
Now we add it to the result of what is returned for the condition.
System.out.println(i==1? ("st"):(i==2? "nd":i==3? "rd":"th") + " number!");
is the source of the problem. Do you see how you have + " number!"); after the : that separates the 1st and the 2nd/3rd? You need to have this twice.
System.out.println(i==1? ("st number"):(i==2? "nd":i==3? "rd":"th") + " number!");
or
System.out.println((i==1? ("st"):(i==2? "nd":i==3? "rd":"th")) + " number!");
Related
one problem I noticed is that the program crashes if you enter non digits even though there is a catch statement. can someone help me out? I can't seem to find the problem.
Can you also explain what I'm doing wrong and why it's wrong? Thank you in advance.
//previous code had an issue while I was creating a new scanner. it's correct now.
import java.util.*;
public class HighLow {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int numberOfAttempts = 0;
System.out.println("WIN THE THREE ROUNDS TO WIN THE GAME!.");
int theNumber = (int) (Math.random() * 10 + 1);
System.out.println("Round 1: I am thinking of a number between" + "\n" + "1 and 10, can you guess the number in " + "\n" + "less than 3 attempts?");
System.out.println("Type a number below and press enter.");
int guess = 0;
do {
try {
guess = scan.nextInt();
if (guess != theNumber) {
if (guess < theNumber) {
System.out.println("Sorry " + guess + " is too low, please try again");
}else if (guess > theNumber) {
System.out.println("Sorry " + guess + " is too high, please try again." );
}
numberOfAttempts = numberOfAttempts + 1;
}else {
System.out.println(guess + " is the correct answer. You got it on" + "\n" + "attempt number " + (numberOfAttempts + 1) + ". Proceeding to round 2.");
theNumber = (int) (Math.random() * 100 + 1);
System.out.println("\n" + "Round 2: I am thinking of a number between " + "\n" + "1 and 100, can you guess the number in " + "\n" + "less than 6 attempts?");
numberOfAttempts = 0;
int secondRoundGuess = 0;
do {
try {
secondRoundGuess = scan.nextInt();
if (secondRoundGuess != theNumber) {
if (secondRoundGuess < theNumber) {
System.out.println("Sorry " + secondRoundGuess + " is too low, please try again");
}else{
System.out.println("Sorry " + secondRoundGuess + " is too high, please try again");
}
numberOfAttempts = numberOfAttempts + 1;
}
else {
System.out.println(secondRoundGuess + " is the correct answer. You got it on " + "\n" + "attempt number " + (numberOfAttempts + 1) + "." + "\n" + "Proceeding to round 3.");
System.out.println("\n" + "Round 3: I am thinking of a number between " + "\n" + "1 and 1000, can you guess the number in " + "\n" + "less than 10 attempts?");
theNumber = (int)(Math.random() * 1000 + 1);
numberOfAttempts = 0;
int thirdRoundGuess = 0;
do {
try {
thirdRoundGuess = scan.nextInt();
if (thirdRoundGuess != theNumber) {
if (thirdRoundGuess < theNumber) {
System.out.println("Sorry " + thirdRoundGuess + " is too low, please try again");
}else {
System.out.println("Sorry " + thirdRoundGuess + " is too high, please try again");
}
numberOfAttempts = numberOfAttempts + 1;
}else{
System.out.println(thirdRoundGuess + " is the correct answer.");
System.out.println("You won the game, you are a badass." + "\n" + "I made this game and I cant even beat " + "\n" + "level 3.");
System.out.println("I am a newbie at programming and it's my " + "\n" + "fourth month on this java journey ." + "\n" + "I am looking for fellow newbies who are willing " + "\n" + "to learn and grow together (or advanced programmers " + "\n" + "who will not get annoyed by teaching newbies)." + "\n" + "If you get to this point in the game " + "\n" + "and see this message, hit me up via direct " + "\n" + "messaging, lets create a group where we can learn " + "\n" + "and grow together.");
}
}catch(Exception e) {
System.out.println("Please enter a number.");
thirdRoundGuess = scan.nextInt();
}
}while(numberOfAttempts != 10);
System.out.println("Game over, you were so close. Try again");
}
}catch(Exception e) {
System.out.println("Please enter a number.");
secondRoundGuess = scan.nextInt();
}
}while(numberOfAttempts != 6);
System.out.println("Game Over. Try again?");
}
}catch(Exception e) {
System.out.println("Please enter a number.");
guess = scan.nextInt();
}
}while (numberOfAttempts != 3);
System.out.println("Game Over. Try again?");
scan.close();
}
}
The root cause of the problem is using scan.nextInt() inside the catch block. What is happening is guess = scan.nextInt(); just below the try is throwing an exception for non-integer input and the control enters the catch block where it encounters guess = scan.nextInt(); again which tries to consume the Enter from the last input causing the program to crash as Enter is not an int.
How to get rid of it?
You need to make two changes to get rid of the problem:
A. Use guess = Integer.parseInt(scan.nextLine()); in which scan.nextLine() will also consume Enter.
B. Comment out the line, guess = scan.nextInt(); as shown below:
} catch (Exception e) {
System.out.println("Please enter a number.");
//guess = scan.nextInt();
}
This is the exception stack trace you get when you run the code:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at HighLow.main(HighLow.java:137)
When you handle the exception first time the user types in a non-numeric value, the exception gets handled below:
catch(Exception e) {
System.out.println("Please enter a number.");
guess = scan.nextInt();
}
When it reaches guess = scan.nextInt();, the previous non-numeric value is still present in the scanner. And when it tries to get an integer out of the scanner when it has a non-numeric value, it throws another InputMismatchException inside catch that is not handled.
I want to display the sum of two numbers beside the equal sign.
Scanner scan = new Scanner(System.in);
int i ;
System.out.println("enter a number: " );
i = scan.nextInt();
int a = i - 1 ;
while(a >= 1){
System.out.println(i +" + "+ a + " = " );
//i want to display the sum of two numbers beside the equal sign.
i =i + a ;
System.out.println(i);
a --;
// how can I display the answer beside the equal sign?
}
}
}
How can I display the answer beside the equal sign?
Change your first println to print.
As per your question I think you are most probably asking how we can show the sum of two numbers in the print statement.
So in your code after "=" you just need to add (i+a) this will sum the value of i and a.
System.out.println(i +" + "+ a + " = " + (i+a)).
I hope this answers your question.
System.out.println() method prints a "newline character" (\n) right after its' input.
There is another method that does not do this:
System.out.print()
You should change
System.out.println(i +" + "+ a + " = " ); to
System.out.print(i +" + "+ a + " = " ); this.
I am trying to run a do...while while a condition is not met but for some reason my code keeps looping every time regardless of the value of the condition. I've checked my debugger and the value of the variable is correct and the conditions within the loop are met according to similar logic. For some reason the ! doesn't work. Here is my code
do
{
if(isRaceHorse.equalsIgnoreCase("Y"))
{
System.out.print("Please enter the number of races your horse has been in >> ");
numRaces = input.nextInt();
input.nextLine();
System.out.println("Your horse is named " + name + " it is a " + color + " horse born in " + birthYear + " and it has been in " + numRaces + " races.");
}
else if(isRaceHorse.equalsIgnoreCase("N"))
{
System.out.println("Your horse is named " + name + " it is a " + color + " horse born in " + birthYear + ".");
}
else
{
System.out.println("Please use Y for yes and N for no.");
System.out.print("Is your horse a race horse? Enter Y for yes and N for no >> ");
isRaceHorse = input.nextLine();
}
}while(!(isRaceHorse.equalsIgnoreCase("y")) || !(isRaceHorse.equalsIgnoreCase("n")));
Anybody have any ideas as to why this is not giving me what I want?
!(isRaceHorse.equalsIgnoreCase("y")) || !(isRaceHorse.equalsIgnoreCase("n"))
In English, this means the loop will continue as long as isRaceHorse is not equal to "y" or isRaceHorse is not equal to "n". Since it cannot be equal to both "y" and "n" at the same time, I'm pretty certain you want to use && instead:
!isRaceHorse.equalsIgnoreCase("y") && !isRaceHorse.equalsIgnoreCase("n")
Edit: Just wanted to say thank you to everyone who've helped so far! I'm new to Java and my professor recommended this site for outside help. It's been great so far. I'm going to take a few moments and work on the code and implement the suggestions I've received. Thanks!
I'm trying to create a program that converts temperatures from degrees Fahrenheit to degrees Celsius, and vice-versa. If the user does not enter the correct unit, the program loops back and asks them to re-enter the unit or enter Q to quit the program. This is what I have so far:
My thinking is to incorporate a loop into the default portion of my switch statement, but I'm not sure which loop to use (maybe for?) that will loop back and ask the user to re enter the unit or Q to quit. Any help is really, really appreciated! I've been stuck on this for hours!
System.out.print("\tEnter 'F' (or 'f') for Fahrenheit or "
+ "'C' (or 'c') for Celcius: ");
f_or_c = console.next();
double fahrenheit = 5*(temperature-32)/9;
double celcius = (9*(temperature)/5)+32;
switch (f_or_c) {
case "C":
case "c":
System.out.println("\n\t" + temperature + " " + " degrees Celcius "
+ "= " + celcius + " degrees Fahrenheit.");
break;
case "F":
case "f":
System.out.println("\n\t" + temperature + " " + " degrees Fahrenheit "
+ "= " + fahrenheit + " degrees Celcius.");
break;
default:
System.out.println("\n\tUnknown units -"
+ "\n\tCannot do calculation -"
+ "\n\tPlease next time enter either 'F' for Fahrenheit or 'C' Celcius");
System.out.print("\nEnter 'Q' to quit or " +
"any other character to perform another temperature conversion: ");
break;
Let's think this through logically: you want to loop until the user enters the correct input. So, does this mean that you will know prior to starting the loop how many times the loop should iterate? This is key.
Once you know this information, the correct loop falls out, since:
for loops are used when you know in advance how many times you'll loop.
While loops are for when you don't know this information in advance.
You can go with while loop. There are better ways to do this. But just helping you with your code.
System.out.print("\tEnter 'F' (or 'f') for Fahrenheit or "
+ "'C' (or 'c') for Celcius: ");
f_or_c = console.next();
boolean flag=false;
double fahrenheit = 5*(temperature-32)/9;
double celcius = (9*(temperature)/5)+32;
while(true) {
switch (f_or_c) {
case "C":
case "c":
System.out.println("\n\t" + temperature + " " + " degrees Celcius "
+ "= " + celcius + " degrees Fahrenheit.");
flag=false;
break;
case "F":
case "f":
System.out.println("\n\t" + temperature + " " + " degrees Fahrenheit "
+ "= " + fahrenheit + " degrees Celcius.");
flag=false;
break;
default:
System.out.println("\n\tUnknown units -"
+ "\n\tCannot do calculation -"
+ "\n\tPlease next time enter either 'F' for Fahrenheit or 'C' Celcius");
System.out.print("\nEnter 'Q' to quit or " +
"any other character to perform another temperature conversion: ");
flag=true;
break;
}
if(flag)
continue;
break;
}
Put the switch statement into a method, and then call that method upon itself for the default case. It's using recursion, but keep in mind if you use recursion in the future, make sure it doesn't infinitely loop or you'll get a stack overflow error.
I might be changing your way of thinking here, but I would Implement it differently. Wrap a while loop around the switch case. This will make sure the switch case is re-executed with the next user input value. I've included an example of what it could look like. Note that I haven't included the input code as there are many options for you. Also, I haven't included the quit code, it only breaks the loop.
bool repeat = TRUE;
while (repeat)
{
switch (f_or_c)
{
case "C":
case "c":
System.out.println("\n\t" + temperature + " " + " degrees Celcius "
+ "= " + celcius + " degrees Fahrenheit.");
repeat = FALSE;
break;
case "F":
case "f":
System.out.println("\n\t" + temperature + " " + " degrees Fahrenheit "
+ "= " + fahrenheit + " degrees Celcius.");
repeat = FALSE;
break;
case "Q":
***YOUR CODE TO QUIT***
repeat = FALSE;
break;
default:
System.out.println("\n\tUnknown units -"
+ "\n\tCannot do calculation -"
+ "\n\tPlease next time enter either 'F' for Fahrenheit or 'C' Celcius");
System.out.print("\nEnter 'Q' to quit or " +
"any other character to perform another temperature conversion: ");
***CODE TO PROMPT USER FOR F_OR_C VALUE***
repeat = TRUE;
break;
}
}
How about a do{}while()?
boolean badInput;
do {
badInput = false;
System.out.print("\tEnter 'F' (or 'f') for Fahrenheit or "
+ "'C' (or 'c') for Celcius: ");
f_or_c = console.next();
double fahrenheit = 5*(temperature-32)/9;
double celcius = (9*(temperature)/5)+32;
switch (f_or_c) {
case "C":
case "c":
System.out.println("\n\t" + temperature + " " + " degrees Celcius "
+ "= " + celcius + " degrees Fahrenheit.");
break;
case "F":
case "f":
System.out.println("\n\t" + temperature + " " + " degrees Fahrenheit "
+ "= " + fahrenheit + " degrees Celcius.");
break;
default:
System.out.println("\n\tUnknown units -"
+ "\n\tCannot do calculation -"
+ "\n\tPlease next time enter either 'F' for Fahrenheit or 'C' Celcius");
System.out.print("\nEnter 'Q' to quit or " +
"any other character to perform another temperature conversion: ");
badInput = true; //we got bad input so we'll continue looping
break;
} while(badInput);
Essentially we set badInput to false at the beginning, assuming it to be good input. If we end up getting bad input, we make badInput true, so we will continue looping.
The general difference between a do-while and a while loop is that do-whiles are used for code that you want to execute at least once. It works well in this case, because you know you want to read input at least once.
In my example, the variable badInput is called a flag. Basically, a flag is just a variable that tracks whether something is "on" or "off". In this case, badInput is tracking whether or not we have bad input. Its a simple "on" "off", "true" "false" scenario.
I am a beginner in Java so I wrote a program to understand the OOP concepts but it gives me an error when trying to use System.out.println().
Here's the code
public static void main(String[] args) {
sampleClass ADD = new sampleClass();
Scanner input = new Scanner(System.in);
int fNum;
int sNum;
System.out.println("Enter the first number to Add");
fNum = input.nextInt();
System.out.println("Now enter the second number");
sNum = input.nextInt();
int sum;
sum = ADD.add(fNum, sNum);
System.out.println("The sum of " fNum " and " sNum " is " sum);
}
Replace this line System.out.println("The sum of " fNum " and " sNum " is " sum); with
System.out.println("The sum of " +fNum+ " and " +sNum+ " is " +sum);
Please Note: In Java, the operator "+" normally acts as an arithmetic operator unless one of its operands is a String. If necessary it converts the other operand to a String before joining the second operand to the end of the first operand.
Examples:
If one of the operands is not a String it will be converted:
int age = 12;
System.out.println("My age is " + age);
Sign "+" is used for concatenation and you missed it between your
String.
The correct format is:
System.out.println("The sum of " + fNum + " and " + sNum + " is " +
sum);
You're missing some +'s between things like "The sum of " and fNum, e.g. "The sum of " + fNum + ....