This question already has answers here:
In Java, what does NaN mean?
(11 answers)
Closed 3 years ago.
I pass a file into the method. Then, I read the method by line. After that, if the line fulfills my condition, I will read the line by token-based, and update i. My question is, from the output, It looks like my I do not successfully update because my output is NaN. Could you help me to take look at this method, and tell me is anywhere going wrong?
import java.util.*;
import java.io.*;
public class ReadingData {
static Scanner console=new Scanner(System.in);
public static void main(String[] args)throws FileNotFoundException{
System.out.println("Please input a file name to input:");
String name1=console.next();
Scanner input=new Scanner(new File(name1));
choosegender(input);
}
public static void choosegender(Scanner input){
boolean judge=false;
while(judge==false) {
System.out.println("Parse by gender(m/f/M/F):");
String gender=console.next().toUpperCase();
if(gender.contains("F")||gender.contains("M")) {
count(input,gender);
judge=true;
}else {
System.out.println("Wrong...please select again!");
}
}
}
public static void count(Scanner input,String gender){
int i=0;
int totalage=0;
while(input.hasNextLine()) {
String line=input.nextLine();
if(line.contains(gender)) {
Scanner token=new Scanner(line);
int id=token.nextInt();
String name=token.next();
String sex=token.next();
int age=token.nextInt();
i++;
totalage=totalage+age;
}
}
double average=(double)totalage/i;
if(gender.equals("F")) {
System.out.printf("the number of female is "+" "+i+",and the average age is %.1f\n ",average);
}else {
System.out.printf("the number of male is"+" "+i+",and the average age is %.1f\n",average);
}
}
}
My output is :
Please input a file name to input:
student.txt
Parse by gender(m/f/M/F):
f
the number of female is 0,and the average age is NaN
NaN stands for Not a Number.
In javadoc, the constant field NaN is declared as following in the Float and Double Classes respectively.
public static final float NaN = 0f / 0f;
public static final double NaN = 0d / 0d;
If you divide a float or double number by 0, you will get NaN(not a number, see the answer from #Anup Lal)
In your case, if there is no line that contains gender, i will be 0 and you average will be NaN.
Related
I am writing a method to recursively convert an integer value to its binary representation.
The code that I wrote below accomplishes the task by just using a method, but I'd like to know how to actually write out a full method.
import java.util.Scanner;
public class Exercise18_21 {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.print("Enter a decimal integer: ");
int decimal = input.nextInt();
System.out.print("Enter a character: ");
System.out.printf("%d decimal is binary %s",decimal,dec2Bin(decimal));
}
//input: integer
//output: binary representation of integer as a string
public static String dec2Bin(int decimal){
return Integer.toBinaryString(decimal);
}
}
My question is how can this be accomplished with recursion?
I want to preserve your code as mush as I can. Therefore I just add a new method successiveDivision(int)
import java.util.Scanner;
public class Exercise18_21 {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a decimal integer: ");
int decimal = input.nextInt();
System.out.print("Enter a character: ");
System.out.printf("%d decimal is binary %s", decimal, dec2Bin(decimal));
}
// input: integer
// output: binary representation of integer as a string
public static String dec2Bin(int decimal) {
return successiveDivision(decimal);
}
public static String successiveDivision(int dec) {
if (dec <= 0) {
return "";
} else {
int bit = dec % 2;
return successiveDivision(dec / 2) + bit;
}
}
}
You can implement it the same way you can do it with pen and paper. Use the modulo operation.
divided by 2 is your parameter for the recursive call and mod 2 is your current digit.
This question already has answers here:
What is 'scope' in Java?
(2 answers)
Closed 2 years ago.
I am pretty new to coding and I have been having trouble with a Physics calculator I've been making. I made this trying to utilize OOP for a class project. The point I to let the user input the variables, then they get shipped into the equation on the class file, and then finally display the result. When I try to compile, it says that the function getAnswer can't see the result declared above it. I plan to make each of the 16 iterations of the equation, so I need to first figure out why this one doesn't work. Any answer is welcome.
-Thanks
import java.util.Scanner;
public class VFD {
public static void main( String[] args ) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Welcome to Kinmatics calculator");
System.out.println("You can find Final Velocity, Acceleration, DIsplacemnt, or Time");
System.out.println("What variable is not included in the equation?");
String missing = keyboard.next();
System.out.println("What variable are you looking for?");
String find = keyboard.next();
if (missing.equals("Final Velocity") && find.equals("Initial Velocity")) {
System.out.println("Please enter your available values");
System.out.println("Acceleration = (m/s^2)");
double a = keyboard.nextDouble();
System.out.println("Displacement = (m)");
double d = keyboard.nextDouble();
System.out.println("Time = (s)");
double t = keyboard.nextDouble();
VelocityFinder qviadt = new VelocityFinder();
qviadt.qviadt(a, d, t);
System.out.println(qviadt.getAnswer());
}
}
}
This is the class file
public class VelocityFinder {
public void qviadt( double a, double d, double t ) {
double result = d/(.5*a*(t*t))/t;
double answer = result;
}
public String getAnswer () {
return answer;
}
}
public class VelocityFinder {
private double answer;
public void qviadt( double a, double d, double t ) {
double result = d/(.5*a*(t*t))/t;
double answer = result;
}
public String getAnswer () {
return String.valueOf(answer);
}
}
The methods qviadt and getAnswer are in the same class, but they are not the same method. getAnswer is trying to return something that doesn't exist. To fix this, remove getAnswer and change qviadt to:
public void qviadt( double a, double d, double t ) {
double result = d/(.5*a*(t*t))/t;
double answer = result;
return answer;
}
and store the return value of it directly. This is called a scope issue and you should look into what scope is and how to use it.
I'm not allowed to use any loops in my assignments lately, which has me stumped on this latest assignment. I'm supposed to ask the user for a series of integers, indefinitely, until they enter a non-integer, then inform them of the greatest integer. This following code, however, only takes in a single input:
public class GreatestNumber {
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
int a;
int g=0;
System.out.println("Enter several numbers. Enter a non-integer to end.");
if(in.hasNext()){
try{a=in.nextInt();
g=Greatest(a); }
catch (NumberFormatException e){
System.out.println("Greatest number in that sequence is "+g);
}}}
public static int Greatest(int x){
int g=0;
if (x>g){
g=x;
}
return g;
}
}
That is a lot of code. You could use recursion. Define greatest as taking a Scanner, check for an int and recurse with Math.max(int, int). Like,
public static int greatest(Scanner in) {
if (in.hasNextInt()) {
return Math.max(in.nextInt(), greatest(in));
}
return Integer.MIN_VALUE;
}
Then to call it, you only need something like
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter several numbers. Enter a non-integer to end.");
System.out.println("Greatest number in that sequence is " + greatest(in));
}
i have this assignment :
File input scores.txt contains matric number and marks for six quizzes. Maximum mark for each quiz is 15. Write a program that reads matric number and marks from the input file. Calculate total and average for each student and write into output file. Scores are separated by blanks. Using the calculated average mark, convert it to percentage and set a grade based on UTM grading scheme.
i do this coding but i have problem when i press run there is errors
import java.io.PrintWriter;
import java.util.*;
public class Q1 {
public static int number,number1,number2;
public static double sum,sum1,sum2,average,average1,average2;
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
java.io.File file=new java.io.File("input.txt");
Scanner input=new Scanner(file);
while(input.hasNext()){
number=input.nextInt();
int q1=input.nextInt();
int q2=input.nextInt();
int q3=input.nextInt();
int q4=input.nextInt();
int q5=input.nextInt();
sum=q1+q2+q3+q4+q5;
average=sum/5;
number1=input.nextInt();
int q21=input.nextInt();
int q22=input.nextInt();
int q23=input.nextInt();
int q24=input.nextInt();
int q25=input.nextInt();
sum1=q21+q22+q23+q24+q25;
average1=sum/5;
number2=input.nextInt();
int q31=input.nextInt();
int q32=input.nextInt();
int q33=input.nextInt();
int q34=input.nextInt();
int q35=input.nextInt();
sum2=q31+q32+q33+q34+q35;
average2=sum/5;
input.close();
}
PrintWriter output=new java.io.PrintWriter("file1.txt");
output.print(number);
output.print(sum);
output.println(average);
output.print(number1);
output.print(sum1);
output.println(average1);
output.print(number2);
output.print(sum2);
output.println(average2);
output.close();
PrintWriter output1=new java.io.PrintWriter("file2.txt");
output.print(number);
output.print(sum);
output.println(check(average));
output.print(number1);
output.print(sum1);
output.println(check(average1));
output.print(number2);
output.print(sum2);
output.println(check(average2));
output.close();
}
public static double check(double a){
if(a>=80){
System.out.print("A");
}
else if((a<80)&&(a>=70)){
System.out.print("B");
}
else if((a>=60)&&(a<70)){
System.out.print("C");
}
else
System.out.print("D");
return a;
}
}
You do have a typo regarding the output:
PrintWriter output1=new java.io.PrintWriter("file2.txt");
output.print(number);
output.print(sum);
output.println(check(average));
output.print(number1);
output.print(sum1);
output.println(check(average1));
output.print(number2);
output.print(sum2);
output.println(check(average2));
output.close();
You forgot to change it to output1.
So I'm learning Java in class and I'm really loving it so far but its really hard to understand sometimes. Right now I'm trying to understand how methods work. My question is why my code is not working. I am trying to read in an integer from user input then square it.
Here is my code:
package freetime;
import java.util.Scanner;
public class methods {
public static void main(String []args){
Scanner input = new Scanner(System.in);
System.out.println( " enter a number ");
int number = input.nextInt();
square(number);
}
public static int square(int number){
int num;
num = number * number;
return (num);
}
}
Let's say I input 5 on the console, the program immediately terminates and I cannot figure out why.
As mentioned by others, you don't print the value and the console will close as soon as the program ends. So you could try something like this
public class ScannerTest {
public static void main(String []args){
while(true){
Scanner input = new Scanner(System.in);
System.out.println( " enter a number (-1 to stop)");
int number = input.nextInt();
if(number == -1){
break;
}
int output = square(number);
System.out.println(output);
}
}
public static int square(int number){
int num;
num = number * number;
return (num);
}
}
This will print the result and loop ask for new input as long as you don't stop the program.
In Java, when main method comes to end and if there aren't any non-deamon threads running, the JVM ends. Your program came to an end without printing out the result of the square() call.
/*here is your solution :*/
import java.util.*;
import java.lang.*;
import java.io.*;
/*in java everything has to be in a class */
class SquareNumber
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner input = new Scanner(System.in);
System.out.println( " enter a number ");
int number = input.nextInt();
System.out.println(square(number));
/*something to print the squared number*/
}
public static int square(int number){
int num;
num = number * number;
return (num);
}
}
Your program is terminated because there is no other statement after square(number); statement. So your program executes square(...) method and after then it found end of main function so the program is terminated. To see some output you must print result of square(...) method.
package freetime;
import java.util.Scanner;
public class methods {
public static void main(String []args){
Scanner input = new Scanner(System.in);
System.out.println( " enter a number ");
int number = input.nextInt();
int result=square(number);//executing square(...) method and store the returned value of square method to result variable
System.out.println("Square of "+number+" is : "+ result);//printing result
}
public static int square(int number){
int num;
num = number * number;
return (num);
}
}