Hello I have a bit of a problem with calculating numbers from a file.
My input is the following rawData.txt:
19.95
5
The output however is this:
49.0 57
My code looks like this:
import java.util.Scanner;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.PrintStream;
class ReadAndWrite
{
public static void main(String args[])
throws FileNotFoundException {
Scanner diskScanner = null;
diskScanner = new Scanner(new FileReader("rawData.txt"));
PrintStream diskWriter = new PrintStream("cookedData.txt");
double total;
double unitPrice = diskScanner.findWithinHorizon(".", 0).charAt(0);
System.out.println(unitPrice);
int quantity = diskScanner.findWithinHorizon(".", 0).charAt(0);
System.out.println(quantity);
total = unitPrice * quantity;
diskWriter.println(total);
diskScanner.close();
}
}
Eventually the cookedData.txt file contains the number 2793.0
Please help
You are fetching only the first character of each line - because of the charAt(0), then cast it to a double (casting char to double!!)
I can't understand what you are trying to do, but converting char to double using casting is almost always NOT what you should do.
Try using Double.parseDouble instead. see it here: https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#parseDouble(java.lang.String)
diskScanner.findWithinHorizon(".",0).charAt(0);
means that you are getting any character, because the first parameter of findWithinHorizon is a regular expression, and "." means one character. From that string you take the first char, i.e. 1. The ascii value of 1 is... 49.
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
I want to print a string formed by concatenating two strings: the first one is declares; the second one is inputed via nextLine(). While this code works when I enter two strings with one space as input, it doesn't work when I try to enter a sentence.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
int i = 4;
double d = 4.0;
String s = "HackerRank ";
Scanner scan = new Scanner(System.in);
/* Declare second integer, double, and String variables. */
int iq;
double dq;
String sq;
iq=scan.nextInt();
dq=scan.nextDouble();
sq= scan.nextLine();
/* Read and save an integer, double, and String to your variables.*/
// Note: If you have trouble reading the entire String, please go back and review the Tutorial closely.
/* Print the sum of both integer variables on a new line. */
System.out.println(i+iq);
System.out.println(d+ dq);
s= s.concat(sq);
System.out.println(s);
/* Print the sum of the double variables on a new line. */
/* Concatenate and print the String variables on a new line;
the 's' variable above should be printed first. */
scan.close();
}
}
First of All, Above mentioned code is not working with any String or Sentence. It is known issue that Scanner will not work expectedlywhen you use Scanner.nextLine after Scanner.next() or any Scanner.nextFoo method .
WorkAround:
add Scan.nextLine() after scan.nextDouble()
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
int i = 4;
double d = 4.0;
String s = "HackerRank ";
Scanner scan = new Scanner(System.in);
/* Declare second integer, double, and String variables. */
int iq;
double dq;
String sq;
iq=scan.nextInt();
dq=scan.nextDouble();
scan.nextLine();
sq= scan.nextLine();
/* Read and save an integer, double, and String to your variables.*/
// Note: If you have trouble reading the entire String, please go back and review the Tutorial closely.
/* Print the sum of both integer variables on a new line. */
System.out.println(i+iq);
System.out.println(d+ dq);
s= s.concat(sq);
System.out.println(s);
/* Print the sum of the double variables on a new line. */
/* Concatenate and print the String variables on a new line;
the 's' variable above should be printed first. */
scan.close();
}
}
I am a newbie in java. I am trying to solve the following problem using java language.
You are to write a program that reduces a fraction into its lowest
terms.
Input
The 1st line of the input file gives the number of test cases N (<=
20). Each of the following N lines contains a fraction in the form of
p=q (1 <= p; q <= 10^30).
Output
For each test case, output the fraction after simplification.
Sample Input
4
1 / 2
2 / 4
3 / 3
4 / 2
Sample Output
1 / 2
1 / 2
1 / 1
2 / 1
My little approach is:
package bigfraction;
import java.math.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner num = new Scanner(System.in);
int n = num.nextInt();
int i;
for(i=1;i<=n;i++){
Scanner s = new Scanner(System.in);
String input1 = s.next();
String d1 = s.next();
String input2 = s.next();
// convert the string input to BigInteger
BigInteger val1 = new BigInteger(input1);
BigInteger val2 = new BigInteger(input2);
BigInteger gcd = val1.gcd(val2);
BigInteger q1 = val1.divide(gcd);
BigInteger q2 = val2.divide(gcd);
System.out.println(q1+" / "+q2);
}
}
}
I am getting runtime error when I submit exact the code in online judge. This is my first submission in java language. I am unable to fix the runtime error.
Your code is fine, just the thing is you can't read a file with system.in. Either google how to parse your sample input from file correctly into your code (maybe you can use map or something like that, also I'll suggest to remove white spaces in the input file) or accept the inputs from keyboard as System.in accepts inputs from keyboard.
Also try to print proper message which value you are going to accept next before accepting it.
one more thing is you don't need multiple scanner objects, you can accept as many inputs from single scanner as you want. Also the variable d1 seems to be unused, remove it if you're not using it
I have sorted out the solution just now.Now it is accepted.
My accepted code:
import java.io.IOException;
import java.math.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception{
Scanner num = new Scanner(System.in);
int n = num.nextInt();
String extra;
int i;
for(i=1;i<=n;i++){
extra = num.nextLine();
String input1 = num.next();
String d1 = num.next();
String input2 = num.next();
// convert the string input to BigInteger
BigInteger val1 = new BigInteger(input1);
BigInteger val2 = new BigInteger(input2);
BigInteger gcd = val1.gcd(val2);
BigInteger q1 = val1.divide(gcd);
BigInteger q2 = val2.divide(gcd);
System.out.println(q1+" / "+q2);
}
}
}
As Lino commented, this works fine as long as you write your faction in the format that the task specified. If you use whitespaces (2 / 4 instead of 2/4) in between the fractions you will receive the simplification.
I'm attempting to get a user input of a decimal, then round it to two decimal points. This is the code I currently have which is not working correctly, and I'm not sure why.
package code;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Scanner;
public class DecimalPlaces {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("#.##");
df.setRoundingMode(RoundingMode.CEILING);
Scanner qweInput = new Scanner(System.in);
System.out.println("Enter a decimal number:");
String qwe1 = qweInput.next();
df.format(qwe1);
System.out.println(qwe1);
}
}
With scanner, better use nextLine() when you can do it, it preserves from errors with the return line char:
String qwe1 = qweInput.nextLine();
Then you need to parse to double, because if not it tries to cast from Object to double and it crashes
df.format(Double.parseDouble(qwe1));
Then the format method return the string formated, because String are immutable, so you need to print direclty or save it :
qwe1 = df.format(Double.parseDouble(qwe1));
System.out.println(qwe1);
//----------------------------------OR----------------------------------
System.out.println(df.format(Double.parseDouble(qwe1)));
Edit : to avoid parsing to Double you can use nextDouble() from Scanner, as it it would direclty save as a double, but to save the format you would need another String so, with proper name ;)
Instead of
String qwe1 = qweInput.next();
try
double qwe1 = qweInput.nextDouble();
By the way, qwe1 is a terrible name for a variable! Variable names should reflect what they are for.
I would suggest getting the user input as a double and then do this:
double roundNum = Math.round(num * 100.0) / 100.0;
Here is an example of such input.
A 3
B 1
A 2 etc.
As shown above, each input is separated by a line and appears an indeterminate amount of times.
How do I only read the numbers next to the 'A' and convert it all into a string using Scanner?
You can write something like:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main29 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String string = scanner.next();
int number = scanner.nextInt();
System.out.println(number);
}
}
}
output:
3
1
2
As you can see I just write a loop which works until scanner can read token from STDIN. Inside of loop I read String tokens use next method and then read Integer tokens use nextInt method.
I think now you can add and required logic to the loop i.e. print numbers after A as you wish.
I am trying to write a program that basically will read any integer from 1,000 to 999,999 and will then display it with a comma separating the thousands. So far I have this, and eclipse doesn't like it. Why?
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// Scanner scan = new scanner(system.in);
double value, integer;
System.out.println("Enter your value without a comma");
integer = scan.nextdouble();
System.out.println(integer,);
scan.close();
you have a lot of errors in the code which is why eclipse doesnt like it ;)
To name a few:
new scanner -> Scanner with capital S
system.in -> same with system
check out this snippet below and it will run just fine :)
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone {
public static void main(String[] args) throws java.lang.Exception {
Scanner scan = new Scanner(System.in);
double value, intValue;
System.out.println("Enter your value without a comma");
intValue = scan.nextDouble();
System.out.println(intValue);
scan.close();
}
Your code looks pretty problematic, to say the least. First of all, is the line in which you declare the Scanner supposed to be commented? If not, that could be part of the problem. You should watch out that you pass the upper-case System.in to your Scanner. You also want to use the nextDouble() method. (Java is case sensitive!) You also want to be careful in your second print statement that you do something more like System.out.println(integer+",");
So, first, the solution:
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Scanner;
public class Ideone {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number:");
long number = scan.nextLong();
NumberFormat f = NumberFormat.getInstance(Locale.ENGLISH);
System.out.println(f.format(number));
scan.close();
}
}
And the problems with you code:
the package declaration is commented, why ?
you import java.lang.* but you don't use it.
your main method throws java.lang.Exception, but I don't see anything in your code throwing that.
you have commented out the scan declaration.
scanner should have the first letter uppercase (java is case-sensitive), same thing for system
you declare a double called value, but you don't use it.
you declare a double called integer (when what you really want is an integer).
you use scan.nextdouble() instead of scan.nextDouble() (but remember, you want an integer, so you should call scan.nextInt()).
I don't see any code trying to put a "," in your number.
you print integer,, this is not even close to what you want, you could have tried integer+"," to concatenate, but it's also not what you want.
you are missing the closing brackets.
the indentation of your code is really bad.
You should have a look at https://stackoverflow.com/tags/java/info in the section Beginners' resources, and try to understand a little bit more and to solve some of your problems by yourself.
Why have you commented the scanner instantiation, also I see the typo in there. The compiler will throw an exception on uninitialized 'scan' object.
Scanner scan = new Scanner(system.in);
In addition to Micah answer, I would suggest you do a check on the input from users to check the range 1000 - 999,999 and re-prompt the user to input the value, if not it will beat the purpose of the range.
System.out.println("Enter your value without a comma");
integer = scan.nextDouble();
while (integer > 999999 OR integer < 1000)
{
System.out.println("Please keep your range in between 1000 - 999,999");
integer = scan.nextDouble();
}