How can I fix runtime Error of my this code? - java

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.

Related

Java ,Related To scanner

I have one query regarding Scanner in java.
I want to take input from user and perform same operation based on inputs.
If user inputs 1 2 in first line, 3 4 5 in second line, 6 7 8 9 in third line ... so it should call function(1,2); function(3,4,5); function(6,7,8,9); ... based on user input (which are different in parameter size) I want to call same function.
Can anyone suggest me optimal way to do this?
This is my program so far ...
import java.util.Scanner;
public class HelloWorld {
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int length = sc.nextInt(); // length of array
int query = sc.nextInt(); // how many queries you want to perform
int arr[] = new int[length];
for(int i=0;i<length;i++);
{
int arr[i] = sc.nextInt();
}
for(int j=0;j<query;j++) {
/* here i want to take input from user and if user inputs 2 integer than pass it like function(param1,param2) if he inputs 3 parameter than pass it like function(param1,param2,param3)
}
Note: For function I am using varargs: function(int... a) .
Use
while(scannerInstance.hasNextLine) to keep reading input and in the loop
Use String value = scannerInstance.nextLine() to read the entire line
Then value.split("\\s+") to split the input string based on
one or more whitespaces.
Parse each string as an Integer using Integer.toString().
Pass the integers got in step 4 to your method.
End while loop.

Reverse number using only loops;no Arrays,convert to String just beginner...Bug:Zero [duplicate]

This question already has answers here:
Reverse number using only loops;no Arrays,convert to String just beginner…Bug:Zero
(2 answers)
Closed 7 years ago.
first sorry about my English(not my native language).
I am new in programming (currently learning Java) and just finishing lecture about looping.
I had a task to reverse random number from 1 to 9999, and got stuck with a bug zero:
example: 23100 output:132 and solution is 00132
Since I still don't know Arrays, convert to String(manipulation),object solution etc…. I couldn't find beginner solution for this problem.
Since this page helped me a lot, I decided to, maybe help someone: this is beginners solution to problem:
123 reverse 321
12300 reverse to 00321 // bug problem with zero solved
now I am still stuck with problem : 00123 and output 32100 not 321
but hope solve this soon
Best regards
import java.util.Scanner;
public class MP{
public static void main(String[] args){
Scanner input=new Scanner(System.in);
System.out.print("enter number:\n");
int x=input.nextInt();
int temp=x;
int z;
while(temp>0){
z=temp%10;
if(z==0){
System.out.printf("%d",0);
}else{
System.out.printf("%d",z);
}
temp=temp/10;
}}}
Since you are the beginner why don't you work with String as with String?
It should suit your purpose:
import java.util.Scanner;
public class MP {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("enter number:\n");
String x = input.next();
for (int i=x.length();i>0;) {
char c=x.charAt(--i);
if (c<='9'&&c>='0')System.out.print();
}
System.out.println();
}
}
String lm = "00123";
StringBuffer bn = new StringBuffer(lm.replaceAll("^0+(?=\\d+$)", ""));
lm = bn.toString();
System.out.println(bn.reverse());
I did for strings it will not when we convert int to string as given is in hex format it will take 38 into string as 00123 is equivalent to 38 in integer.Hope you like my work.
Happy coding.
Well whenever you try to store 00123 as an integer it is stored as 123 [ EDIT: apparently Java assumes that those leading zeros means that you are inputting a hexadecimal number (base-16 rather than base-10) so the result will be not 123, but 291]. So then when you reverse it, the leading zeros are left out. It seems to me that the only way to do what you are trying to accomplish would be, unfortunately, to use either arrays or Strings (I would recommend using a String).
That being said, if you are avoiding using a String/array simply because you don't know how to use them, then have no fear; Strings are fairly easy to use. A problem you might be running into is that people tend to not make their code very easy to understand. If that is the case, we share the same pains. I will try to make an example that is easy to understand:
It would look something like this:
import java.util.Scanner;
public class MP{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("enter number:\n");
String temp = input.next(); //use next() to look for a String
int digit = temp.length()-1; //starting at the last digit
while (digit >= 0){
char z = temp.charAt(digit); //get the current digit
System.out.print(z); //Print that digit
digit = digit - 1; //Go backwards one digit
}
}
}
Eventually you should be able to write a much shorter program for the same thing:
import java.util.Scanner;
public class MP{
public static void main(String[] args){
System.out.print("enter number:\n");
String temp = new Scanner(System.in).next();
for (int i=temp.length()-1; i>=0; i--){
System.out.print(temp.charAt(i));
}
}
}

number converting to other number

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.

"Given 2 ints, a and b, return true if one if them is 10 or if their sum is 10." How can I apply real numbers

package cornett1;
import java.util.Scanner;
public class CodeRat {
public static boolean makes10(int a , int b)
{
return (a + b == 10 || a == 10 || b == 10);
}
public static void main (String[] args) {
Scanner s = new Scanner(System.in);
System.out.print(makes10(s.nextInt(),s.nextInt());
}
}
I am using a website called codingbat to do programming exercises and I solved the question
"Given 2 ints, a and b, return true if one of them is 10 or if their sum is 10." How can I apply this program and Input actual numbers.
Write a main method in the class, and pass in two numbers when invoking the program.
In the main method, Use
int a = Integer.parseInt(argument 0);
int b = Integer.parseInt(argument 1);
Now create a new instance of JOption class and invoke the method 'makes10' in the method with the arguments.
JOption opt = new JOption();
boolean answer = opt.makes10(a, b);
System.out.println(answer);
One of the easiest option you have is
java.util.Scanner
Defention: A simple text scanner which can parse primitive types and strings
using regular expressions.
A Scanner breaks its input into tokens
using a delimiter pattern, which by default matches whitespace.
The resulting tokens may then be converted into values of different types
using the various next methods.
Why using Scanner API?
1. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
2. A scanning operation may block waiting for input.
3 .A Scanner is not safe for multithreaded use without external synchronization.
For example:
Scanner input = new Scanner(System.in);
int i = sc.nextInt();
System.out.println("the number you entered is " + i);
Explanation:
you read from console and feed scanner variable which is input and you just want to read int. at the end, you print the read number on the console
Resources
first one
second one
Another option is using BufferedReader API
Reads text from a character-input stream, buffering characters so as
to provide for the efficient reading of characters, arrays, and lines.
The buffer size may be specified, or the default size may be used. The
default is large enough for most purposes.
take a look at this sample for your BufferReader need
BufferReader vs Scanner
BufferedReader has significantly larger buffer memory than Scanner. Use BufferedReader if you want to get long strings from a stream, and use Scanner if you want to parse specific type of token from a stream.
Scanner can use tokenize using custom delimiter and parse the stream into primitive types of data, while BufferedReader can only read and store String.
BufferedReader is synchronous while Scanner is not. Use BufferedReader if you're working with multiple threads.
In your case:
int a = 0;
int b = 0;
Scanner input = new Scanner(System.in);
System.out.println("Please enter two numbers");
a = input.nextInt();
b = input.nextInt();
JOption jp = new JOption();
jp.makes10(a, b);
}
public boolean makes10(int a, int b) {
return ((a + b) == 10 || a == 10 || b == 10);
}
Read up on this:
http://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html
This tells you how to take arguments form the command line and use those as variables in your program.
public static void main (String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
System.out.print(makes10(a,b));
}
If you want input at runtime, you can use the Scanner class or the Console class
Scanner s = new Scanner(System.in);
System.out.print(makes10(s.nextInt(),s.nextInt()));
You can use a Scanner to get input from a user :
Scanner sc = new Scanner(System.in);
System.out.println(makes10(sc.nextInt(),sc.nextInt()));

How to conver a string value to an integer

I want to convert a string value to an integer but I can't. My statement checked
=Integer.parseInt(input);
has an error, please help and thanks a lot in advance.
import java.util.Scanner;
public class ass2a
{
public static void main(String []args)
{
Scanner reader = new Scanner(System.in);
String input,b;
long checked;
System.out.print("Please enter the 12 digit:");
input = reader.nextLine();
if(input.length() < 12)
{
System.out.println("The digit is less than 12.");
}
int one,two,three,four,five,six,seven,eight,nine,ten,eleven,twevle;
checked =Integer.parseInt(input);
System.out.println(checked);
}
}
Use checked =Long.parseLong(input); instead of checked =Integer.parseInt(input);
12 digit numbers are very large and so you can not store it in int.So you need to store in Long
12 digits number is a really big number...Integer can't store it. That is you error - so you need another type to store the number.
I recommend you to use Long : Long.parseLong(input);
That should solve the problem.
Your issue is this line:
input = reader.nextLine();
try this:
checked = Long.parseLong(input);
use
checked= Long.parseLong(input)
instead of
Integer.parseInt
it can't handle a 12 digit long number
You're getting an error because the string value that you are giving as input is more than 2147483647. This is the max int can store (you can sysout Integer.MAX_VALUE to check this). If you intend to input a bigger number, may be you can use long (max value 9223372036854775807)
System.out.println(Integer.MAX_VALUE); // =2147483647 (2^31 - 1)
System.out.println(Long.MAX_VALUE); // =9223372036854775807 (2^63 - 1)
Depending on the input size, you might want to choose the correct data type.
Please see http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html for further details.
Here is the corrected program(assuming that your trying to find whether a User-inputted number is less than 12 and displaying the number
import java.util.Scanner;
public class ass2a
{
public static void main(String []args)
{
Scanner reader = new Scanner(System.in);
long input,b;
long checked;
System.out.print("Please enter the 12 digit:");
input = reader.nextLong();
if(String.valueOf(input).length() < 12)
{
System.out.println("The digit is less than 12.");
}
int one,two,three,four,five,six,seven,eight,nine,ten,eleven,twevle;
checked =(long)(input);
System.out.println(checked);
}
}

Categories

Resources