import java.io.*;
import java.util.*;
public class volumeConeD
{//class
public static void main (String [] args)
{//main
Scanner keyBoard = new Scanner(System.in);//input for keyBoard
//variables
double volume;
double radius;
double hieght;
double oneThird = 0.3333;
double pie = 3.14;
double yes = 1.0;
boolean r = true;
try
{//begin of try
while(r == true){
System.out.print("Volume of a Cone... V=1/3(3.14)r^2(h)");
System.out.println ();
System.out.println ();
radius = getRadius(radius);//call to method
radius = keyBoard.nextDouble ();
System.out.print("Enter a Height ");
hieght = keyBoard.nextDouble ();
//math
volume = oneThird * pie * radius * radius * hieght;
System.out.printf ("Volume = " + volume);
}//end of try
catch (Exception Error){
System.out.println("You entered wrong data");
}
System.out.println ();
System.out.print("Does the user wish to try again?");
System.out.println ();
System.out.print("Enter 1 to go again OR any other key to end.");
yes = keyBoard.nextDouble();
}//end of while
}//end of main
public static double getRadius(double mRadius)
{
System.out.print("Enter Radius Squared Number ");
return mRadius;
}
}//end of program
this is my first time posting on this forum, so please excuse how ask...here goes... all i am trying to do with this is repeat this problem under user control using a sentinel method(while loop). I had it almost working earlier but i kept getting errors about how i defined "r". Now i get errors about my catch try blocks. please help.
volumeConeD.java:35: error: 'catch' without 'try'
catch (Exception Error){
^
volumeConeD.java:35: error: ')' expected
catch (Exception Error){
^
volumeConeD.java:35: error: not a statement
catch (Exception Error){
^
volumeConeD.java:35: error: ';' expected
catch (Exception Error){
^
volumeConeD.java:19: error: 'try' without 'catch', 'finally' or resource declarations
try
^
5
You placed your try { outside the while loop, but the corresponding catch is within the while loop. But must be either outside the loop or inside the loop, together.
Try placing the try { lines inside the while loop.
Additionally, it looks like these lines won't work either:
radius = getRadius(radius);//call to method
radius = keyBoard.nextDouble ();
All getRadius does is print out a prompt and return the passed in parameter, radius. But radius hasn't been initialized yet. But it looks like nothing is done with it yet anyway. Rename the method something like promptForRadius, and it doesn't need to take in a parameter or return anything.
public static void promptForRadius()
{
System.out.print("Enter Radius Squared Number ");
}
Then when calling it:
promptForRadius();
// Then you can call this line (unchanged)
radius = keyBoard.nextDouble();
Where your comment says // end of try it should really say // end of while and vice versa.
I have reformatted the code. Braces for try/catch block cannot end before while loop braces. Also you have to initialize variables before using them (e.g,. radius). Eclipse like IDE will be helpful to format and identify compilation errors. BTW I have not checked the logical correctness of the code but more of compilations and syntax issues
import java.util.Scanner;
public class volumeConeD
{
public static void main(String[] args)
{
Scanner keyBoard = new Scanner(System.in);// input for keyBoard
// variables
double volume;
double radius = 0.0;
double hieght;
double oneThird = 0.3333;
double pie = 3.14;
double yes = 1.0;
boolean r = true;
try
{// begin of try
while (r == true)
{
System.out.print("Volume of a Cone... V=1/3(3.14)r^2(h)");
System.out.println();
System.out.println();
radius = getRadius(radius);// call to method
radius = keyBoard.nextDouble();
System.out.print("Enter a Height ");
hieght = keyBoard.nextDouble();
// math
volume = oneThird * pie * radius * radius * hieght;
System.out.printf("Volume = " + volume);
System.out.println();
System.out.print("Does the user wish to try again?");
System.out.println();
System.out.print("Enter 1 to go again OR any other key to end.");
yes = keyBoard.nextDouble();
}// end of while
}// end of try
catch (Exception Error)
{
System.out.println("You entered wrong data");
}
}// end of main
public static double getRadius(double mRadius)
{
System.out.print("Enter Radius Squared Number ");
return mRadius;
}
}// end of program
This seems to be your problem
try
{
while (...)
{
int blammo;
try
{
... code
blammo = 9;
}
catch ...
{
// catching here means that the while loop will continue looping.
}
System.out.println("Blammo: " + blammo); // This results in the error: variable
// blammo might not have been initialized. This is because the assignment
// "blammo = 9" is inside the try block and if an exception was thrown before
// the assignment then it (the assignment) will never execute and blammo will
// be uninitialized.
} // end of while loop
} // end of outter try
catch ...
{
// catching here means that the exception exits the while loop.
}
You use a catch, but it's not matching with the try...
oneThird variable can be set as 1 / 3 (more precision).
Same for PI, the Math library already has a PI definition.
The function getRadius is useless, you should take it off, or maybe replace it by a function which asks the user to enter a double number.
import java.util.Scanner;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double volume, radius, height, oneThird = (1.0 / 3);
int continueExecution = 1;
try {
while (continueExecution == 1) { // same as r == true (redundant)
System.out.println("Volume of a Cone... V=1/3(3.14)r^2(h)\n\n"); // '\n' is the newline character
radius = getDoubleValue(sc, "Enter radius : ");
height = getDoubleValue(sc, "Enter height : ");
volume = oneThird * Math.PI * Math.pow(radius, 2) * height;
System.out.println("Volume = " + volume + "\nEnter 1 to start again, or another number to exit: ");
continueExecution = sc.nextInt();
}
} catch (Exception e) { // Pokemon exception handling !
System.err.println(e.getMessage());
}
}
public static double getDoubleValue(Scanner sc, String msg) {
System.out.print(msg);
return sc.nextDouble();
}
Related
So I'm trying to make a simple calculator.
How do I make when I enter the first number, it works but if I insert "abc" it will give me an error.
How I make it in order when you write "abc" to say " please enter a number "
import java.util.Scanner;
public class calculator
{
public static void main(String[] args0) {
Scanner test = new Scanner(System.in);
int x;
int y;
String c;
System.out.println("Insert a number ");
x = test.nextInt();
System.out.println("insert a value e.g * / + -");
c = test.next();
System.out.println("Insert another number");
y = test.nextInt();
if ( c.equals("*")) {
System.out.println("the total is " + x*y);
}
if (c.equals("+")) {
System.out.println("the total is " + (x+y));
}
if (c.equals("-")) {
System.out.println("the total is "+ (x-y));
}
if (c.equals("/")) {
System.out.println("the total is "+ (x/y));
}
}
}
You can verify the input until be a int using a scanner property Scanner.hasNextInt()
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!scanner.hasNextInt()) scanner.next();
Example:
public static void main(String[] args0) {
Scanner test = new Scanner(System.in);
int x;
int y;
String c;
System.out.println("Insert a number ");
while (!test .hasNextInt()) test .next(); // Scanner Validation
int x = test .nextInt();
}
JavaDoc of Scanner
The error you get is an exception. You can actually "catch" your exceptions, so that when they appear, your program doesn't break, and you can do what is in place for that error (output a "Please, insert only numeric values" feedback?)
You can find some info on try-catch blocks here try-catch blocks
Try this:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner test = new Scanner(System.in);
int x;
int y;
String c;
try {
System.out.println("Insert a number ");
x = test.nextInt();
System.out.println("insert a value e.g * / + -");
c = test.next();
System.out.println("Insert another number");
y = test.nextInt();
if (c.equals("*")) {
System.out.println("the total is " + x*y);
}
if (c.equals("+")) {
System.out.println("the total is " + (x+y));
}
if (c.equals("-")) {
System.out.println("the total is "+ (x-y));
}
if (c.equals("/")) {
System.out.println("the total is "+ (x/y));
}
} catch(InputMismatchException e) {
System.out.println("Please enter correct values.");
}
}
Modifications:
The error you are getting is known as RunTime Error or Exceptions due to wrong input type. In order to handle RunTime Exceptions, You need to use try and catch block.
try and catch blocks are used to handle RunTime Exceptions. If any error or exception occurs within try block then It will be thrown to catch block to be handled instead of terminating your program.
Try this:
boolean success = false;
while (!success) {
try {
y = test.nextInt();
success = true;
} catch (InputMismatchException e) {
test.nextLine();
System.out.println("Please enter a number.");
}
}
If you're willing to accept doubles instead of ints, java doubles have a built in method isNaN(), where NaN stands for Not a Number.
if (Double.isNaN(doubleValue)) {
...
}
I created a module that's called within another module, and it looks something like this:
public static double calculateAnswer (double itemRadius, String itemShape);
{
double circleArea;
if (itemShape.equalsIgnoreCase("c"))
{
circleArea = 3.14159 * (itemRadius * itemRadius);
System.out.print("The area of the circle in inches is " + circleArea);
return circleArea;
}
else
{
calculateAnswerSphere (itemRadius);
}
/////////////////////////////////////////////// seperating method
public static double calculateAnswerSphere(double itemRadius);
{
double sphereVolume;
sphereVolume = (4.0/3) * 3.14159 * (itemRadius * itemRadius * itemRadius);
system.out.print("The volume of the sphere in cubic inches is " +sphereVolume);
}
end If;
but, I'm getting the error of "illegal start of expression" with the line where I make the method header for the second module. It looks constructed correctly.
Complete code as follows:
//This program will find the area or volume of a circle or sphere, respectively.
import javax.swing.JOptionPane;
public class Java_Chapter_9
{
public static void main(String args[])
{
//Declarations
String itemShape; //type of shape
String runProgram; //user control
Double itemRadius; //radius of tem
Double finalAnswer; //calculation for final answer
//End Declarations
showGreeting (); //Call greeting module
runProgram = JOptionPane.showInputDialog("Please enter 'Y' to run the program, or 'N' to quit"); //giving user control
while (runProgram.equalsIgnoreCase("y")) //loop for continuous use
{
itemShape = getItemShape (); //calling itemShape module
itemRadius = getItemRadius (); //calling itemradius module
finalAnswer = calculateAnswer (itemRadius, itemShape); //calling the module for calculation with paramaters
runProgram = JOptionPane.showInputDialog("Enter 'Y' to input more, or 'N' to Quit");
}
showGoodbye ();
////////////////////////////////////////////////// starting modules
public static void showGreeting () //greeting module
{
System.out.println("Welcome to the program");
System.out.println("This program will show you the area or volume of a shape");
}
///////////////////////////////////////////////// seperating modules
public static String getItemShape ()
{
String typeOfShape;
typeOfShape = JOptionPane.showInputDialog("Please enter 'C' for a Circle, or 'S' for a Sphere"); //getting input for shape
return typeOfShape; //returning to method
}
////////////////////////////////////////////////// seperating modules
public static double getItemRadius ()
{
double radiusOfItem; //variable withing scope of module
String radiusOfItemInput;
radiusOfItemInput = JOptionPane.showInputDialog("Please enter the radius of the item in inches: ");
radiusOfItem = Double.parseDouble(radiusOfItemInput);
return radiusOfItem;
}
////////////////////////////////////////////////// seperating modules
public static double calculateAnswer (double itemRadius, String itemShape);
{
double circleArea;
if (itemShape.equalsIgnoreCase("c"))
{
circleArea = 3.14159 * (itemRadius * itemRadius);
System.out.print("The area of the circle in inches is " + circleArea);
return circleArea;
}
else
{
calculateAnswerSphere(itemRadius);
}
/////////////////////////////////////////////// seperating method
public static double calculateAnswerSphere(double itemRadius);
{
double sphereVolume;
sphereVolume = (4.0/3) * 3.14159 * (itemRadius * itemRadius * itemRadius);
system.out.print("The volume of the sphere in cubic inches is " +sphereVolume);
}
end If;
}
public static void showGoodbye ()
{
System.out.println("Thank you for using the program. Goodbye.");
}
Specifically, I appear to be having problems in general calling the modules, but none of the text is overly clear and how to make a module fit within the main method, which is where I'm struggling.
There are a lot of errors in your code.
Remove the ; in function. ; is not needed for function.
public static double calculateAnswerSphere(double itemRadius); // remove ;
After showGoodBye() method is being called, you miss to add a close brackets.
You have a typo in this line
system.out.print
It should be System.out.print and so on...
I've been given a task to make some conversions from ft and in to cm. I've gotten most of this down and the conversions do work. I also want to include the statement of A negative number... or A non-digit... when I type a string, for example, or a negative number, to display said message.
The problem I am getting is that when I do type up a string or negative number, I get the output of testProgram.NegativeNumberException when I enter -9, for example. And testProgram.NonDigitNumberException, when I enter joe, for example.
I am thinking there is something wrong in the catch but not sure exactly where it won't click.
package testProgram;
import java.util.InputMismatchException;
import java.util.Scanner;
public class conversion{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double cm = -1;
while(cm == -1){
cm = convertToCentimeters(scan);
if(cm!=-1){
System.out.println("Your result = " +cm);
}
else{
System.out.println("Please enter the values again.");
}
scan.nextLine();
}
}
public static double convertToCentimeters(Scanner scan){
double centimeters = -1;
try{
double foot = getFootValue(scan);
double inch = getInchValue(scan);
double totalInches = foot * 12 + inch;
centimeters = totalInches * 2.54;
}catch(NegativeNumberException e1){
System.out.println(e1);
}
catch(NonDigitNumberException e2){
System.out.println(e2);
}
return centimeters;
}
public static double getFootValue(Scanner scan) throws NegativeNumberException, NonDigitNumberException{
try{
System.out.println("Enter the foot value: ");
double foot = scan.nextDouble();
if(foot <= 0){
throw new NegativeNumberException ("A negative foot value has been entered.");
}
return foot;
}
catch(InputMismatchException e){
throw new NonDigitNumberException ("A non-digit foot value has been entered.");
}
}
public static double getInchValue(Scanner scan)throws NegativeNumberException, NonDigitNumberException{
try{
System.out.println("Enter the inch value: ");
double inch = scan.nextDouble();
if(inch <= 0){
throw new NegativeNumberException ("A negative inch value has been entered.");
}
return inch;
}
catch(InputMismatchException e){
throw new NonDigitNumberException ("A non-digit inch value has been entered.");
}
}
}
Alternatively to #Scary's suggestion, you can add a constructor to your custom exceptions as -
NegativeNumberException(String str) {
System.out.println(str);
}
This shall help you print the message when you
throw new NegativeNumberException ("A n....");
I get this exception:
Please provide width: 4
Please provide height: Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at rr.fr.op.lab.prob1.Rectangle.scanner(Rectangle.java:51)
at rr.fr.op.lab.prob1.Rectangle.main(Rectangle.java:31)
My code is:
package rr.fr.op.lab.prob1;
import java.util.Scanner;
public class Rectangle {
public static void main(String[] args) {
if(args.length != 2 && args.length != 0){
System.err.println("Invalid number of arguments was provided.");
System.exit(1);
double a = Double.parseDouble(args[0]);
double b = Double.parseDouble(args[1]);
double area = area(a,b);
double perimeter = perimeter(a,b);
System.out.println("You have specified a rectangle of width " + a + " and height "
+ b + ". Its area is " + area + " and its perimeter is " + perimeter);
}
double x,y,z;
if(args.length == 0){
System.out.printf("Please provide width: ");
x = scanner();
System.out.printf("Please provide height: ");
y = scanner();
}
}
private static double area(double a, double b){
return a*b;
}
private static double perimeter(double a, double b){
return 2*(a+b);
}
private static double scanner (){
Scanner sc = new Scanner (System.in);
double number = sc.nextDouble();
sc.close();
return number;
}
}
After that, I would like to use method trim() to delete whitespaces. Is that possible? And, I need isEmpty() method too. This code must calculate area and perimeter of rectangle. Inputs are form keyboar or command line.
You close the scanner after you use it. This also closes the underlying stream, System.in in this case, since it implements Closeable.
When you next create a scanner, System.in is already closed, so you can't read more elements from it.
Create a single scanner and reuse it multiple times.
It is considered a bad practice to close a stream if you didn't open it (or you have potentially leaked the reference).
There may be other code which relies upon the stream being open, so you closing it can lead to failures in that code. Failures remote from the cause like that are notoriously difficult to debug.
Unfortunately, it is very easy to close streams unintentionally, since classes like Scanner, BufferedInputStream etc close their underlying stream when they are closed.
You can basically pass scanner object to your method and close it after you are done with your scanning outside your scanner() method.
...
if (args.length == 0) {
Scanner sc = new Scanner(System.in);
System.out.printf("Please provide width: ");
x = scanner(sc);
System.out.printf("Please provide height: ");
y = scanner(sc);
sc.close();
}
...
private static double scanner(Scanner sc){
double number = sc.nextDouble();
return number;
}
Scanner sc = new Scanner(System.in);
System.out.println("Please provide width: ");
int number1 = 0;
try {
number1 = Integer.parseInt(sc.nextLine());
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
System.out.println("Please provide height:");
int number2 = 0;
try {
number2 = Integer.parseInt(sc.nextLine());
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
All I need it to do is loop again so the user can continuously use the program if they to. Let me know if there are any reference that I can read up to, to help me understand more about this problem. Thanks in advance.
import java.util.Scanner;
public class Module3Assignment1 {
// public variables
public static String letterChosen;
public static int loop = 0;
public static double radius, area;
public static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
// tells user what the program is about
System.out.println("Welcome to the Round Object Calculator");
System.out.println("This program will calculate the area of a circle of the colume of a sphere.");
System.out.println("The calculations will be based on the user input radius.");
System.out.println("");
// loops while the user wants to calculate information
while (loop == 0){
Input();
System.out.print(Answer());
System.out.println("Do you want to calculate another round object (Y/N)? ");
String input = scanner.next().toUpperCase();
if (input == "N"){
loop = 1;
}
}
// ending message/goodbye
Goodbye();
scanner.close();
}
private static void Input(){
// prompts user for input
System.out.print("Enter C for circle or S for sphere: ");
letterChosen = scanner.nextLine().toUpperCase();
System.out.print("Thank you. What is the radius of the circle (in inches): ");
radius = scanner.nextDouble();
}
private static double AreaCircle(){
// calculates the area of a circle
area = Math.PI * Math.pow(radius, 2);
return area;
}
private static double AreaSphere(){
// calculates the area of a sphere
area = (4/3) * (Math.PI * Math.pow(radius, 3));
return area;
}
private static String Answer(){
//local variables
String answer;
if(letterChosen == "C"){
// builds a string with the circle answer and sends it back
answer = String.format("%s %f %s %.3f %s %n", "The volume of a circle with a radius of", radius, "inches is:", AreaCircle(), "inches");
return answer;
}else{
// builds a string with the sphere answer and sends it back
answer = String.format("%s %f %s %.3f %s %n", "The volume of a sphere with a radius of", radius, "inches is:", AreaSphere(), "cubic inches");
return answer;
}
}
private static String Goodbye(){
// local variables
String goodbye;
// says and returns the goodbye message
goodbye = String.format("%s", "Thank you for using the Round Object Calculator. Goodbye");
return goodbye;
}
}
The below is the console output and the error I am getting after execution
Welcome to the Round Object Calculator
This program will calculate the area of a circle of the colume of a sphere.
The calculations will be based on the user input radius.
Enter C for circle or S for sphere: C
Thank you. What is the radius of the circle (in inches): 12
The volume of a sphere with a radius of 12.000000 inches is: 5428.672 cubic inches
Do you want to calculate another round object (Y/N)?
Y
Enter C for circle or S for sphere: Thank you. What is the radius of the circle (in inches): C
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextDouble(Scanner.java:2387)
at Module3Assignment1.Input(Module3Assignment1.java:48)
at Module3Assignment1.main(Module3Assignment1.java:24)
import java.util.Scanner;
public class Module3Assignment1 {
// public static variables are discouraged...
private static char letterChosen; //char takes less memory
private static char useAgain = 'Y'; //just use the answer to loop...
private static double radius, area;
private static String answer;
private static Scanner scanner = new Scanner(System.in);
//you might want to clear the screen after the user gave an answer to another round object
private static void clearScreen(){
for(int i =0;i<50;i++){System.out.print("\n");}
}
public void input(){
// prompts user for input
System.out.print("Enter C for circle or S for sphere: ");
letterChosen = scanner.next().charAt(0);
System.out.print("Thank you. What is the radius of the circle (in inches): ");
radius = scanner.nextDouble();
this.answer= answer(letterChosen);
}
public double areaCircle(double radius){
// calculates the area of a circle
area = Math.PI * Math.pow(radius, 2);
return area;
}
public double areaSphere(double radius){
// calculates the area of a sphere
area = (4/3) * (Math.PI * Math.pow(radius, 3));
return area;
}
public String answer(char letterChosen){
//local variables
String answer = "";
if(letterChosen=='c'||letterChosen=='C'){
answer = String.format("%s %f %s %.3f %s %n", "The volume of a circle with a radius of", radius, "inches is:", areaCircle(radius), "inches");
}else{
answer = String.format("%s %f %s %.3f %s %n", "The volume of a sphere with a radius of", radius, "inches is:", areaSphere(radius), "cubic inches");
}
return answer;
}
private static String goodbye(){
// local variables
String goodbye;
// says and returns the goodbye message
goodbye = String.format("%s", "Thank you for using the Round Object Calculator. Goodbye");
return goodbye;
}
public static void main(String[] args) {
// tells user what the program is about
System.out.println("Welcome to the Round Object Calculator");
System.out.println("This program will calculate the area of a circle of the colume of a sphere.");
System.out.println("The calculations will be based on the user input radius.");
System.out.println("");
Module3Assignment1 ass1 = new Module3Assignment1();
// loops while the user wants to calculate a round object
while (useAgain == 'Y'||useAgain=='y'){
ass1.input();
System.out.print(answer);
System.out.println("Do you want to calculate another round object (Y/N)? ");
useAgain = scanner.next().charAt(0);
System.out.println(useAgain);
clearScreen();
}
// ending message/goodbye
System.out.println(goodbye());
scanner.close();
}
}
Some things that I changed:
I used char instead of String. String takes up more memory than char.
added clearScreen() method which "clears" the screen when you're using console.
I added a parameter radius to areaSphere and areaCircle methods. This makes the methods reusable.
I changed all the public static variables to private static. using public static variables is HIGHLY DISCOURAGED. You may read this to find out why.
and to prevent public static variables, I created an instance of Module3Assignment1 instead of having everything in static.
changed the casing of method names. Please follow camel-casing, which means that the first letter of the method is lowercase and the other words will have the first letter in uppercase (e.g. input(), areaSphere() )
A comment about comparing Strings:
== compares REFERENCES TO THE OBJECT , NOT VALUES
use .equals() or .equalsIgnoreCase() if you want to compare the values of two Strings. here is a sample syntax:
if(string1.equals(string2)){
//do something
}
Concept One
Always use .equals Method while Comparing String in Java
So
if(letterChosen == "C")
Should be if(letterChosen.equals("C")) and so the Others
Concept Two.
This might be one of the reason that is happening with your code . You have already taken a UserInput from the keyboard object of the scanner class that's why it's giving the else response. This particularly happens when you take other than String input from that object
Thats because the Scanner#nextDouble method does not read the last newline character of your input, and thus that newline is consumed in the next call to Scanner#nextLine.
WorkAround Fire a blank Scanner#nextLine call after Scanner#nextDouble to consume newline.
Or Use Two Scanner Object.
Demo What Happens With Same Scanner Object for Both nextLine() and nextInt()
public class Test {
public static void main(String[] args) {
Scanner keyboard= new Scanner(System.in);
int n=keyboard.nextInt();
String userResponse;
while(true) {
userResponse = keyboard.nextLine();
if(userResponse.length() == 1 && userResponse.charAt(0) == 'y') {
System.out.println("Great! Let's get started.");
break;
}
else if(userResponse.length() == 1 && userResponse.charAt(0) == 'n') {
System.out.println("Come back next time " + "" + ".");
System.exit(0);
}
else {
System.out.println("Invalid response.");
}
}
}
}
Output
5
Invalid response.
now change the code structure to get String Input from that scanner Object and not get another kind of data types the code works.
With String as previous Input
public class Test {
public static void main(String[] args) {
Scanner keyboard= new Scanner(System.in);
String n=keyboard.nextLine();
String userResponse;
while(true) {
userResponse = keyboard.nextLine();
if(userResponse.length() == 1 && userResponse.charAt(0) == 'y') {
System.out.println("Great! Let's get started.");
break;
}
else if(userResponse.length() == 1 && userResponse.charAt(0) == 'n') {
System.out.println("Come back next time " + "" + ".");
System.exit(0);
}
else {
System.out.println("Invalid response.");
}
}
}
}
Output
j
y
Great! Let's get started.
Without any previous response with that object your code will work.
public class Test {
public static void main(String[] args) {
Scanner keyboard= new Scanner(System.in);
String userResponse;
while(true) {
userResponse = keyboard.nextLine();
if(userResponse.length() == 1 && userResponse.charAt(0) == 'y') {
System.out.println("Great! Let's get started.");
break;
}
else if(userResponse.length() == 1 && userResponse.charAt(0) == 'n') {
System.out.println("Come back next time " + "" + ".");
System.exit(0);
}
else {
System.out.println("Invalid response.");
}
}
}
}
and Gives me the desired output
y
Great! Let's get started.
I usually have been doing this whole time creating two OBJECT of Scanner Class one to get String Input and other to get other data types Input
(Too be frank even i have been not able to figure out why i needed to create two Object's for receiving String and Other data types in java without any error. If anyone know please let me know )