Second scanner is ignoring input - java

I have written Java code that has Scanners. What it is supposed to do is get 2 inputs and then do the math. The problem is that the second scanner doesn't work properly. It automatically does the else statement without asking for input.
package stuff;
import java.util.Scanner;
public class Diagonal {
public static void main(String[] args) {
double a = Math.pow(getHeight(), 2);
System.out.println(a);
double b = Math.pow(getWidth(), 2);
double c = a + b;
System.out.println(Math.sqrt(c));
}
static double getWidth() {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the width.");
double width;
if(scan.hasNextDouble()) {
width = scan.nextDouble();
}
else {
System.out.println("Sorry, there was an error!");
width = 0;
}
scan.close();
return width;
}
static double getHeight() {
Scanner scan2 = new Scanner(System.in);
System.out.println("Enter the height");
double height;
if(scan2.hasNextDouble()) {
height = scan2.nextDouble();
}
else {
System.out.println("Sorry, there was an error!");
height = 0;
}
scan2.close();
return height;
}
}

You can not do this:
double a = Math.pow(getHeight(), 2);
System.out.println(a);
double b = Math.pow(getWidth(), 2);
because getHeight() and getWidth() are methods that close the scanner, which is closing the System.in stream too...
so your 2 condition scan.hasNextDouble() is never met!
Solution:
use 1 scanner instance and close it when you are done reading inputs

You can't reopen a standard input stream once you close it. Your getHeight() method closes it so your getWidth() method cannot open it again.
Open a standard input stream once for your program and don't close it until you're done reading all user inputs.

You cannot reopen standard input stream once it is closed. so in our code remove Scanner objects from both methods and initialize it in the 'main' function once. like this and use the 'scan' object in both functions.
`static Scanner scan;
public static void main(String[] args) {
scan = new Scanner(System.in);
double a = Math.pow(getHeight(), 2);
System.out.println(a);
double b = Math.pow(getWidth(), 2);
double c = a + b;
System.out.println(Math.sqrt(c));
scan.close();
}`

Related

Methods, and Loops

My Issue is that this code does not return and values when I call it.
I need to to read a set of values from another txt file and print out the answers.
Then I need to be able to have it print to another empty text file.
The values in the txt file is (without space in-between lines):
1 2 3 4 5 6
4 5 6
7.5 8.5 9
8.1 9.2 10.3
The source code as follows:
public class Lab5d {
public static void main(String args[]) {
// Scan the input
Scanner scan = new Scanner(System.in);
String line = scan.nextLine();
Scanner lineScan = new Scanner(line);
// Process each line separately
// If the next token is a double, assume there is an input line
while (scan.hasNextDouble()) {
processLine(line);
}
}
public static void processLine(String line) {
Scanner scan = new Scanner(System.in);
Scanner lineScan = new Scanner(line);
double a = lineScan.nextDouble();
double sum;
double product;
double count;
double average;
sum = 0;
count = 0;
product = 1;
while (lineScan.hasNext()) {
sum = sum + a;
product = product * a;
++count;
}
double ave = sum / count;
System.out.printf("sum= %.1f, product= %.1f, ave= %.1f, count= %.1f%n", sum, product, ave, count);
}
}
Can anyone help?
You're not reading the file in. Use the file path as a parameter for the Scanner object.
It can be two cases, you can either read values from a file or values from a command line.
First a main method look:
public static void main(String args[]) {
// Scan the input
processSystemIn();
// San the file
processFile("resource/values.txt");
}
The values.txt is following the format you presented in your question.
And read a value line by line using a hasNextLine method of a Scanner class then, use an another scanner instance for the each number from the line input.
case 1: A processSystemIn method with System.in
private static void processSystemIn() {
Scanner scanner = new Scanner(System.in);
String line = null;
while (scanner.hasNextLine()) {
line = scanner.nextLine();
processLine(line);
}
scanner.close();
}
case 2: A processFile method with file.
private static void processFile(String fileName) {
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
String line = null;
while (scanner.hasNextLine()) {
line = scanner.nextLine();
processLine(line);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
The processLine method is a little bit different with yours.
With a hasNextDouble method, you can get a value.
See the method as follows:
public static void processLine(String line) {
Scanner lineScan = new Scanner(line);
double a;;
double sum;
double product;
double count;
double average;
sum = 0;
count = 0;
while(lineScan.hasNextDouble())
{
a = lineScan.nextDouble();
product = 1;
sum += a;
product *= a;
++count;
average = sum / count;
System.out.printf("sum= %.1f, product= %.1f, ave= %.1f, count= %.1f%n", sum, product, average, count);
}
lineScan.close();
}
The result is here:
Does this result meet your expectation?
I hope this helps.

java runtime error (NZEC)

So i am working on this ATM problem on codechef and my program runs on my compiler and meets all the problem's requirement however codechef's compiler keeps giving me this NZEC runtime error and i cant figure out why. Here is the code: How can i fix it?
import java.util.Scanner;
public class ATM {
public static final double charge = 0.50;
public static void main(String args[]) {
int x,y;
Scanner keyboard = new Scanner(System.in);
while (keyboard.hasNext()) {
x = keyboard.nextInt();
y = keyboard.nextInt();
if( y > x + charge && x % 5 == 0) {
double balance = y - x - charge;
System.out.println(balance + "0");
} else {
System.out.println(y);
}
}
}
}
You can't use the scanner object in CodeChef. Use BufferedReader instead.
First of all, you did not choose proper data types for your input. Your second input, i.e, y should be of double type, not int type. Then you are not printing your answer in the proper format required by Codechef. Codechef strictly follows the format in which it accepts the answer. Here, your answer must display an output of double/float data type with exactly two decimal places.
Here, I have rectified your mistakes:
import java.util.Scanner;
class ATM {
public static final double charge = 0.50;
public static void main(String args[]) {
int x;
double y;
Scanner keyboard = new Scanner(System.in);
while (keyboard.hasNext()) {
x = keyboard.nextInt();
y = keyboard.nextDouble();
if( y > x + charge && x % 5 == 0) {
double balance = y - x - charge;
System.out.printf("%.2f",balance);
} else {
System.out.printf("%.2f",y);
}
}
}
}
Keep coding :)

java.util.NoSuchElementException in Java code

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();
}

Trying to combine multiple programs together

I am trying to take 3 different programs I have created and put them under a single class. My professor has stated I must do this and I have no clue on how to. I am not looking for a hand out here, just some how I can do this quickly and efficiently. I am also trying to figure out how to call from the same scanner for each program or if I should just make multiple ones.
import java.util.Scanner;
public class AssignmentOneFahrenheit {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello, I can convert Fahrenheit to Celsius!");
System.out.println("Please enter the degrees Fahrenheit you want converted.");
double degreesF;
double degreesC;
Scanner keyboard = new Scanner(System.in);
degreesF = keyboard.nextDouble(); //Allows user to input decimal number
keyboard.close();
System.out.println("The temperature in Degrees Celsius is: ");
degreesC = 5*(degreesF - 32)/9;
System.out.printf("%.2f", degreesC);
}
import java.util.Scanner;
public class AssignmentOneHate {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a line containing 'hate'.");
String text = keyboard.nextLine();
System.out.println("I have changed that line to read: ");
System.out.println(text.replaceFirst("hate", "love"));
keyboard.close();
}
import java.util.Scanner;
public class AssignmentOneVerticalDisplay {
public static void main(String[] args) {
// TODO Auto-generated method stub
int userInput;
System.out.println("Please enter a 4 digit integer.");
Scanner keyboard = new Scanner(System.in);
userInput = keyboard.nextInt();
System.out.println(userInput / 1000);
userInput = userInput % 1000;
System.out.println(userInput / 100);
userInput = userInput % 100;
System.out.println(userInput / 10);
System.out.println(userInput % 10);
keyboard.close();
}
}
I basically just copied and pasted 2 programs I created. If anybody can help guide me in the correct direction here that would be great.
You can use the Double.parseDouble(String string); function together with a try-Catch to check if it was a number or a string in the input.
(...)
String text = keyboard.nextLine();
try {
//We try and assume that it is a number
Double number = Double.parseDouble(text);
/**
* Do stuff with the number like in the 1st program
*/
}
catch (NumberFormatException e)
{
//The input turned out not to be a number.
/**
* Do stuff here with the string like the 2nd program
*/
}
Am not really certain what your trying to accomplish, but if it's really necessary you combine all three classes together try using Java Inner Classes
I think that your professor is looking for a more object oriented solution. You can create a class that contains the three programs as separated methods like this
import java.util.scanner;
public class AssignmentScanner {
public double convertToCelsius() {
Scanner keyboard = new Scanner(System.in);
double degreesF = keyboard.nextDouble();
keyboard.close();
return 5*(degreesF - 32)/9;
}
public String replaceHate() {
Scanner keyboard = new Scanner(System.in);
String text = keyboard.nextLine();
String replacedText = text.replaceFirst("hate", "love");
keyboard.close();
return replacedText;
}
public int oneVerticalDisplay() {
Scanner keyboard = new Scanner(System.in);
int userInput = keyboard.nextInt();
System.out.println(userInput / 1000);
userInput = userInput % 1000;
System.out.println(userInput / 100);
userInput = userInput % 100;
System.out.println(userInput / 10);
System.out.println(userInput % 10);
keyboard.close();
}
}
You still need to create a main program that use this object like this:
public class AssignmentMain {
public static void main(String[] args) {
AssignmentScanner assignmentScanner = new AssignmentScanner();
System.out.println("Hello, I can convert Fahrenheit to Celsius!");
System.out.println("Please enter the degrees Fahrenheit you want converted.");
double degreesC = assignmentScanner.convertToCelsius();
System.out.println("The temperature in Degrees Celsius is: ");
System.out.printf("%.2f", degreesC);
System.out.println("Please enter a line containing 'hate'.");
String replacedText = assignmentScanner.replaceHate();
System.out.println("I have changed that line to read: ");
System.out.println(replacedText);
System.out.println("Please enter a 4 digit integer.");
assigmentScanner.oneVerticalDisplay();
}
}
This way your main program only knows about the AssignmentScanner and its three methods. This make the main program easier to read and maintain. There is still room for improvement but i think it's OK for a first approach.

Scanner not working with while loop

Maybe my google-fu is just terrible, but I'm having a very hard time figuring out how to do this. I'm trying to get a scanner to read a string, add the inputs, and return a value. I feel like I am just missing something... for example, I'm not sure how to get a variable set to the first double in the scanner.
import java.util.Scanner;
public class adding {
public static double sum(Scanner input){
Scanner s=new Scanner (System.in);
double i = (s.nextDouble());
double sumAnswer = 0;
while (s.hasNext()){
sumAnswer = sumAnswer + i;
i = s.nextDouble();
}
return sumAnswer;
}
public static void main(String[] args){
System.out.println(sum(new Scanner("1.2 2.8 3.9")));
}
}
You don't really need an i variable.
And, as already mentioned, don't have 2 Scanner's.
public static double sum(Scanner input){
double sumAnswer = 0;
while (input.hasNext()){
sumAnswer += input.nextDouble();
}
return sumAnswer;
}
You shouldn't be resetting the scanner after passing the input.
public class adding {
public static double sum(Scanner input){
double i = (input.nextDouble());
double sumAnswer = 0;
while (input.hasNext()){
sumAnswer = sumAnswer + i;
i = input.nextDouble();
}
return sumAnswer;
}
That ought to work better for you, maybe. I could also be mixing something up there...

Categories