Problems with scanning in java - java

I got a task, where I have to calculate the perimeter and area of a given object, that's determined by the user, with accompanying data - side length, radius, etc. To do this I have to do a "GUI" as my teacher said, and to do that, I have to use the Scanner.
Everytime I try to do the second scan, after the user has choosen what object we are dealing with, when it gets to the part, where the user's supposed to input their data about their object, it always crashes, with a java.util.NoSuchElementException error, according to NetBeans. I looked through it, and even copied in the working scanner, but to no avail.
Here's the full code:
package Methods2;
import java.util.Scanner;
public class Methods2 {
public static void main(String[] args) {
//initialization
int decider;
Scanner input1;
//defining
input1 = new Scanner(System.in);
System.out.println("Choose from these options to find the perimeter and area of any of these:\n1. Circle\n2. Square\n3. Rectangle");
decider = input1.nextInt();
input1.close();
//decision
if (decider == 1) {
circle();
} else if (decider == 2) {
square();
} else if (decider == 3) {
rectangle();
} else {
System.out.println("There aren't any other options, other than these three.");
}
}
public static void circle() {
//method specific initialization
int radius;
double pi;
double perimeter;
double area;
Scanner input2;
//define
pi = 3.14;
input2 = new Scanner(System.in);
System.out.println("Please type in the radius of the circle!");
radius = input2.nextInt(); //these are where my problem's lie
input2.close();
//calculate
perimeter = 2 * radius * pi;
area = radius * radius * pi;
//print
System.out.println("The perimeter of this circle is: " + perimeter);
System.out.println("The area of this circle is: " + area);
}
public static void square() {
//method specific initialization
int a;
int perimeter;
int area;
Scanner input3;
//define
input3 = new Scanner(System.in);
System.out.println("Please type in one side's length of the square!");
a = input3.nextInt(); //these are where my problem's lie
input3.close();
//calculate
perimeter = 4 * a;
area = a * a;
//print
System.out.println("The perimeter of this circle is: " + perimeter);
System.out.println("The area of this circle is: " + area);
}
public static void rectangle() {
//method specific initialization
int a;
int b;
int perimeter;
int area;
Scanner input4;
//define
input4 = new Scanner(System.in);
System.out.println("Please type in one of the sides' length of the rectangle!");
a = input4.nextInt(); //these are where my problem's lie
System.out.println("Now type the other, non-equal side, compared to the previous one!");
b = input4.nextInt(); //these are where my problem's lie
input4.close();
//calculate
perimeter = 2 * (a + b);
area = a * b;
//print
System.out.println("The perimeter of this circle is: " + perimeter);
System.out.println("The area of this circle is: " + area);
}
}
I have thought about it being multiple Scanner's, but after I realized, that variables don't carry over between methods, unless they're defined within the class, that was swiftly thrown out as a theory. Also, NetBeans didn't mark any problems with that line, so it made even less sense to me.

The reason why your code is "stopping" the scanner, is because you added input1.close();. What .close() does, is that it closes the scanner. Once a scanner is closed, you won't be able to open it again. According to your code, you use the Scanner.. even after it was closed. So to fix your problem, removed the line:
input1.close();
Here is a close up of where you should remove the line:
//initialization
int decider;
Scanner input1;
//defining
input1 = new Scanner(System.in);
System.out.println("Choose from these options to find the perimeter and area of any of these:\n1. Circle\n2. Square\n3. Rectangle");
decider = input1.nextInt();
//input1.close(); REMOVE THIS LINE

Related

Already declared variable cannot resolve

double width cannot be resolved along with int walls even though before I started my Surface Area calculations, it compiled.
import java.util.Scanner;
public class Assignment_3_4 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//Customer Name
System.out.println("Enter your First Name");
String Firstn = in.next();
System.out.println("Enter your Last Name");
String Lastn = in.next();
System.out.println("Valued Customer Name: " + Firstn + " " + Lastn);
//Wall Measurements
System.out.println("Enter the Width");
if(in.hasNextDouble()){
double width = in.nextDouble();
System.out.println("Width/Height: " + width);
} else {
System.out.println("Please enter only numbers");
}
System.out.println("Enter number of walls");
if(in.hasNextInt()){
int walls = in.nextInt();
System.out.println("Number of Walls: " + walls);
} else {
System.out.println("Please enter only integers");
}
//Calculate Surface Area - Width Height and Length are all the same measurement
double SA = ((width * width) * walls);
System.out.println("Area to be Painted: " + SA + " square meters");
Java has what is known as block scope
Any variable declared within a block {} is not accessible outside the block. You can use variables from outside the scope, but not the other way. What you need to do is declare the variable outside the scope. You probably also want to throw an exception to the user.
double width;
if(in.hasNextDouble()){
width = in.nextDouble();
System.out.println("Width/Height: " + width);
} else {
throw new IllegalArgumentException("Please enter only numbers");
}
You declared width inside the block of this if statement:
if(in.hasNextDouble()){
double width = in.nextDouble();
System.out.println("Width/Height: " + width);
}
So this block is the scope of width and it's not visible outside of it.
What you should do?
Declare it like this:
double width;
if(in.hasNextDouble()){
width = in.nextDouble();
System.out.println("Width/Height: " + width);
}
Now width will be visible to the rest of main() although it may be uninitialized. So maybe this is safer:
double width = 0.0;

How to print a static method in java that takes an int as parameter and returns a double

I'm having difficulty trying to print the result of the static method calcArea, which takes the int radius as parameter to calculate the area of a circle and returns the area.
Here's the code below 👇 Any help would be appreciated.
public class CircleArea {
public int radius;
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter the radius of the circle: ");
int radius = input.nextInt();
System.out.print("The area of the circle is:" + calcArea()); <-- ERROR HERE
}
public static double calcArea(int radius){
double area = Math.PI * Math.pow(radius, 2);
return area;
}
}
Your call to calcArea needs a parameter passed in. Probably calcArea(radius).
The function calcArea() takes the value of radius and then returns area. To do this, you need to pass an argument to calcArea(). So, your code should be like this:
System.out.print("The area of the circle is:" + calcArea(radius));
The error you're getting clearly points out that you're missing an argument.
call method calcArea, you need give a parameter,Here are the correct example"
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter the radius of the circle: ");
int radius = input.nextInt();
System.out.print("The area of the circle is:" + calcArea(radius));
}

a java program exercises in Triangle area

I'm working in a project to make a program to ask the user to find the areas of different shapes, like a triangle, circle and squares.
the following code is to get from the user the area of a triangle which lengths is known, I want to add at the end of this class a return value of total correct answers to use it in main class later to show the progress of his work and scores.
+ what do you recommend to add or improve this program?
package tringle_project;
import java.util.Scanner;
public class Tringle_project
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String a1;
int correctCount = 0;
int incorrect = 0;
int total=(correctCount+incorrect);
do
{
int a = (int)(Math.random() * 20);
int b = (int)(Math.random() * 20);
int c = (int)(Math.random() * 20);
double input;
int p = (a + b + c) / 2;
double area = (Math.sqrt(p * (p - a) * (p - b) * (p - c)));
System.out.println("Welcome to the Tringle Area exercise!");
System.out.println("Enter the area of a tringle if you know the 3 sides as: " + a + ", " + b + ", " + c + " in cm.");
input = keyboard.nextDouble();
while (input != area)
{
System.out.println("Ohh wrong answer :( please try again! ");
input = keyboard.nextDouble();
incorrect++;
}
System.out.println("Excellent Work!");
correctCount++;
System.out.println("To continue enter Yes, to end enter done.");
a1 = keyboard.next();
} while (a1.equalsIgnoreCase("Yes"));
}
}

How do I fix my "java.util.InputMismatchException" error?

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 )

When I try to invoke method "calcArea", error message "non-static method calcArea() cannot be referenced from a static context" appears

I've messed around with this for an hour now and can't get it to work. I've also looked this question up but the wording used in answers I've found haven't helped me at all.
Any help would be much appreciated.
Also, the invocation in question is at the very end of the program, inside main.
import java.util.Scanner;
public class Area {
Scanner input = new Scanner (System.in);
/**
* #param args the command line arguments
*/
public static void areaTriangle (double height, double length){
System.out.println((height * length) * .5);
}
public static void areaRectangle (double height, double length,
double width){
System.out.println(height * length * width);
}
public static void areaCircle (double radius){
System.out.println(Math.PI * (radius * radius));
}
public void calcArea (){
double i;
System.out.println("Which shape's area would you like to calculate?: \n"
+ "Enter '1' for Triangle \n"
+ "Enter '2' for Rectangle \n"
+ "Enter '3' for Circle \n"
+ "Enter '0' to quit the program");
i = input.nextDouble();
if (i == 1)
{
System.out.print("Enter the height of your triangle: ");
double height = input.nextDouble();
System.out.print("Enter the height of your length: ");
double length = input.nextDouble();
areaTriangle(height, length);
}
else if ( i == 2)
{
System.out.print("Enter the height of your rectangle: ");
double height = input.nextDouble();
System.out.print("Enter the length of your rectangle: ");
double length = input.nextDouble();
System.out.print("Enter the width of your rectangle: ");
double width = input.nextDouble();
areaRectangle(height, length, width);
}
else if ( i == 3)
{
System.out.print("Enter the radius of your circle");
double radius = input.nextDouble();
areaCircle(radius);
}
else if ( i == 0)
return;
else
System.out.println("Please input a number from 0 - 3");
}
public static void main(String[] args) {
calcArea();
}
}
put static in calcArea
public static void calcArea ()
or you can do this in your main
public static void main(String[] args) {
YourClassName variable= new YourClassName();
variable.calcArea();
}
just change the "YourClassName" to the name of your class and also you can change the variable object

Categories