Cannot print out read integers: java - java

I am creating a program that will print out digits of pi up to a number specified by the user. I can read the input from the user, I can read the text file, but when I print the number of digits, it prints out the wrong number.
"Pi.txt" contains "3.14159".
Here is my code:
package pireturner;
import java.io.*;
import java.util.Scanner;
class PiReturner {
static File file = new File("Pi.txt");
static int count = 0;
public PiReturner() {
}
public static void readFile() {
try {
System.out.print("Enter number of digits you wish to print: ");
Scanner scanner = new Scanner(System.in);
BufferedReader reader = new BufferedReader(new FileReader(file));
int numdigits = Integer.parseInt(scanner.nextLine());
int i;
while((i = reader.read()) != -1) {
while(count != numdigits) {
System.out.print(i);
count++;
}
}
} catch (FileNotFoundException f) {
System.err.print(f);
} catch (IOException e) {
System.err.print(e);
}
}
public static void main(String[] args ) {
PiReturner.readFile();
}
}
This will print out "515151" if the user inputs 3 as the number of digits they wish to print. I do not know why it does this, and I am not sure what I am doing wrong, as there are no errors and I have tested the reading method and it works fine. Any help would be gladly appreciated. Thanks in advance.
By the way, casting integer 'i' to a char will print out 333 (assuming input is 3).

The value 51 is the Unicode code point (and the ASCII value) for the character '3'.
To display 3 instead of the 51 you need to cast the int to char before printing it:
System.out.print((char)i);
You also have an error in your loops. You should have a single loop where you stop if either you reach the end of the file, or if you reach the required number of digits:
while(((i = reader.read()) != -1) && (count < numdigits)) {
Your code also counts the character . as a digit, but it is not a digit.

Your inner loop is not left before outputting numdigit times 3
while (count != numdigits) {
System.out.print(i);
count++;
}
instead ...
int numdigits = Integer.parseInt (scanner.nextLine ());
// for the dot
if (numdigits > 1)
++numdigits;
int i;
while ((i = reader.read ()) != -1 && count != numdigits) {
System.out.print ((char) i);
count++;
}

You only read one character from the file - '3' (character code 51, as Mark Byers points out) and then you print it 3 times.
int i;
while((count < numdigits) && ((i = reader.read()) != -1)) {
System.out.print((char)i);
count++;
}
If the user says they want 4 digits of pi, are you intending to print 3.14 or 3.141?
The above code would print 3.14 for 4 - because it's 4 characters.

Related

Scanner for hex-input not working as expected inside loop

I need to solve this problem where i need to convert hexadecimal numbers to decimals.
Issue
I have compiled it without any errors, but my output came out wrong. Can someone show how to fix these errors?
Code
import java.util.Scanner;
import java.io.*;
class HexToDecException extends Exception {
public HexToDecException(String msg) {
super(msg);
}
}
public class Main {
public static int hexToDec(String hex) throws HexToDecException {
char currentChar;
int dec=0;
int power = 0;
for(int i=hex.length()+1;i>=0;i--){// by reverse
currentChar = hex.charAt(i);
if(currentChar>='0' && currentChar<='9'){
dec+= Math.pow(16,power)*(currentChar - '0');
power++;
}
else if(currentChar>='a' && currentChar<='f'){
dec+= Math.pow(16,power)*(currentChar - 'a' + 10);
power++;
}
else if(currentChar>='A' && currentChar<='G'){
dec+= Math.pow(16,power)*(currentChar - 'A' + 10);
power++;
}
else
throw new IllegalArgumentException("Invalid Character in Hexadecimal string");
}
return power;
}
public static void main(String[] args){
Scanner scan = null;
try{
scan = new Scanner(System.in);
int n = scan.nextInt();
for(int i=0;i<n;i++)
System.out.println(hexToDec(scan.next()));
}
catch(Exception ex){
ex.printStackTrace();
}
finally{
System.out.println("That's all.");
}
}
}
Example
Input:
5 6B 5 4AZ A5 9
Expected Output:
107 5 Invalid hexadecimal number 165 9
Output that i got:
That's all
Your solution is close. Here are changes to make so that it runs correctly:
modify the return statement of hexToDec() to return the decimal number you've constructed, not the power, so change this: return power to this: return dec
modify throws clause to this: throw new HexToDecException("Invalid hexadecimal number"); – use the custom exception you defined, and edit the string message to match the output you're expecting
change the for loop in hexToDec() so it that properly checks each position in the input string, so change this: for (int i = hex.length() + 1 to this: for (int i = hex.length() - 1. Maybe read up on how String.length() works in relation to charAt(). If a string has a length N, the corresponding "Nth" position in that string has to be referenced by N-1. N itself would never work, and N+1 would also not work.
finally, rewrite the main loop to wrap the call to hexToDec() in a try-catch, and print the exception message if an exception is thrown:
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
for (int i = 0; i < n; i++) {
String nextInput = scan.next();
try {
int x = hexToDec(nextInput);
System.out.print(x + " ");
} catch (HexToDecException e) {
System.out.print(e.getMessage() + " ");
}
}
After those changes, this input:
5 6B 5 4AZ A5 9
will produce this output:
107 5 Invalid hexadecimal number 165 9

Why am I getting the error in a loop that reoccurs at a single particular iteration every run-time? (Binary Queries problem from HackerEarth)

I'm trying to solve this question:
Binary Queries,
https://www.hackerearth.com/practice/data-structures/arrays/1-d/practice-problems/algorithm/range-query-2/
Question summary:
N digits of binary numbers are given; Q queries are then given.
Two types of queries:
"0 X": Flip the Xth bit
"1 L R": Print if binary no. formed by L to R(position) is odd or even.
Simple solution is to check only rightmost bit; if it's 1, the number is odd, else, even.
My code throws "Wrong answer" every time;
however, IN ALL TEST CASES, there's ONLY ONE wrong output, and this wrong output happens EXACTLY 99 lines before the total number of output lines*.
There seems to be no other pattern.
*I tried flipping output when I reach (Q-99)th query to check; however, there's no way to find number of output queries without storing all queries, since query type[0] has no output, only type1 has an output. Thus, Q cannot be used.
Images: All testcases fail Eg.1 The only line of error Eg.2 Another example.
Here's my code:
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String inpArr[] = (br.readLine().split("\\s"));
int n=Integer.parseInt(inpArr[0]); //number of digits
int q=Integer.parseInt(inpArr[1]); //number of queries
//read binary digits w/o space, and store them as chars
String binArrStr=br.readLine().replace(" ","");
char[] binArr=binArrStr.toCharArray();
int i;
for(i=0;i<q;i++) //all queries
{
String query[]=br.readLine().split("\\s"); //read the query
if(query[0].equals("1")) //Flip the bit if query[0]=1
{
if(binArr[Integer.parseInt(query[1])-1]=='1') //take position(query[1]) as int and flip
binArr[Integer.parseInt(query[1])-1]='0';
else
binArr[Integer.parseInt(query[1])-1]='0';
}
else //Print odd or even if query[0]=0
{
//query[1] is leftmost bit.
//Sufficient to check only the bit in rightmost position, given by
//3rd argument(Rightmost bit) which is query[2]
//If rightmost bit==1, ODD, else EVEN
if(binArr[Integer.parseInt(query[2])-1]=='1')
System.out.println("ODD");
else
System.out.println("EVEN");
}
}
}
I could skip this problem, but it's better to know why exactly this happens, I think.
if(query[0].equals("1")) //Flip the bit if query[0]=1
{
if(binArr[Integer.parseInt(query[1])-1]=='1') //take position(query[1]) as int and flip
binArr[Integer.parseInt(query[1])-1]='0';
else
binArr[Integer.parseInt(query[1])-1]='0';
}
in your if statement you checked that if it's 1 then flip it to 0 but in your else block you are not flipping the number to 1 because else block will come to action if the number is 0. Hence you are only partially flipping.
Here is my solution
import java.util.Scanner;
class TestClass {
public static void main(String args[]) throws Exception {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int q = scan.nextInt();
int[] bits = new int[n + 1];
for (int i = 1; i <= n; i++) {
bits[i] = scan.nextInt();
}
for (int i = 1; i <= q; i++) {
if (scan.nextInt() == 1) {
int index = scan.nextInt();
if (bits[index] == 0) bits[index]++;
else bits[index]--;
} else {
int lIndex = scan.nextInt();
int rIndex = scan.nextInt();
System.out.println(bits[rIndex] == 0 ? "EVEN" : "ODD");
}
}
}
}

How can I count the number of characters in java without using length?

I'm trying to create a program that will count the number of characters in a word that the user input and I don't want to use the .length function.
My problem is that whatever I do the program gives me the answer that there is one more letter than I entered.
Here is my code:
import java.io.IOException;
import java.io.InputStreamReader;
public class count {
public static void main(String args[]) throws IOException
{
InputStreamReader cin = null;
int counter=0;
try {
cin = new InputStreamReader(System.in);
System.out.println("Enter text: ");
char c;
do {
c = (char) cin.read();
System.out.print(c);
counter++;
} while(c != '\n');
} finally {
counter -=1;
System.out.println("Number of characters: " + counter);
if (cin != null) {
cin.close();
}
}
}
};
This is because even \n makes your code increment the counter.
One way to change your loop is the following:
while ((c = (char) cin.read()) != '\n') {
System.out.print(c);
counter++;
}
System.out.println(); // this is to print the new line character anyway
This performs the test up front instead, so that the counter is not incremented.
Note that c = (char) cin.read() not only assigns the value of the read character to c, but also is an expression which value is the character that has just been read. That's why we can compare this thing to \n.
More generally, the assignment operation (=) is also an expression, which value is the value of the right hand side of the assignment (you can also see it as the value of the variable after the assignment).
As pointed out by #Jan, in order to be platform independent, you might as well consider checking for \r (which would stop before a \r\n too):
while ((c = (char) cin.read()) != '\n' && c != '\r') {
System.out.print(c);
counter++;
}
System.out.println(); // this is to print the new line character anyway

Java input random numbers and keep a counter for each number

So I am trying to create a loop that accepts number "0 - 10". If it is less than "0" than the loop exits and the program prints out all the numbers and the number of times each was entered. So Lets say you enter values like 1 2 3 4 5 1 It will print out something like Number:1 Times Entered:2 then next line will print out Number:2 Times Entered:1. If it goes higher than 10 I will just give them an input error. If someone can just help me out creating the correct variables and format I think I can take it from there. Here is what I have thus far... I know it's not correct but this is the idea I am trying to do.
import java.io.*;
public class test {
public static void main(String[] args) throws IOException{
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(reader);
String str;
Integer[] numbers = new Integer[1000]
int count = 0;
str = input.readLine();
while(str != null){
numbers[count] = Integer.parseInt(str);
// Here I will create some [if else] statements like
if(numbers < 0)
break;
else if(numbers >= 0 || numbers <= 50)
numbers[count]++;
else
System.out.print("You must enter a value less than 51");
} // Close while loop here
System.out.println("Number:" + number + " Times Entered:" + count);
}
}
import java.io.*;
public class Demo {
public static void main(String[] args) throws IOException{
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(reader);
String str;
int i,number;
Integer[] numbers = new Integer[10];
int count = 0;
for(i=0;i<10;i++)
numbers[i]=0;
str = input.readLine();
while(str != null){
number = Integer.parseInt(str);
// Here I will create some [if else] statements like
if(number == 0)
break;
else if(number >= 0 && number <= 10)
numbers[number-1]++;
else
System.out.print("You must enter a value less than 11");
str = input.readLine();
} // Close while loop here
for(i=0;i<10;i++)
System.out.println("Number:" + (i+1) + " Times Entered:" + numbers[i]);
}
}
This should work.And put some efforts form your side so that you can learn

How to implement Java "Scanner" in C++?

Please have a look at the following java code
import java.util.Scanner;
public class Main
{
static int mul=1;
static String convert;
static char[] convertChar ;
static StringBuffer buffer = new StringBuffer("");
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
int number=0;
int loopValue = scan.nextInt();
//System.out.println("print: "+loopValue);
for(int i=0;i<loopValue;i++)
{
number = scan.nextInt();
// System.out.println("print: "+number);
for(int a=1;a<=number/2;a++)
{
if(number%a==0)
{
//System.out.println(a);
mul = mul*a;
//System.out.println(mul);
}
}
convert = String.valueOf(mul);
convertChar = convert.toCharArray();
if(convertChar.length>4)
{
/*System.out.print(convertChar[convertChar.length-4]);
System.out.print(convertChar[convertChar.length-3]);
System.out.print(convertChar[convertChar.length-2]);
System.out.print(convertChar[convertChar.length-1]);
System.out.println();*/
buffer.append(convertChar[convertChar.length-4]);
buffer.append(convertChar[convertChar.length-3]);
buffer.append(convertChar[convertChar.length-2]);
buffer.append(convertChar[convertChar.length-1]);
System.out.println(buffer);
}
else
{
System.out.println(mul);
}
//System.out.println(mul);
mul = 1;
}
}
}
This code is built to compute the product of positive divisors of a given number. I have used scanner here because I don't know how many inputs will be entered. That is why I can't go something like
int a, b;
cin >> a >> b
in C++. All the inputs will be inserted by a test engine, into one single like like following
6 2 4 7 8 90 3456
How can I implement the Java "Scanner" using C++ ? Is there a header file for that? Please help!
You seem to be using Scanner to read one integer at a time from the standard input stream. This is easily accomplished with the extraction operator, operator>>.
Replace this code:
Scanner scan = new Scanner(System.in);
int number=0;
int loopValue = scan.nextInt();
//System.out.println("print: "+loopValue);
for(int i=0;i<loopValue;i++)
{
number = scan.nextInt();
// System.out.println("print: "+number);
With this:
int number=0;
int loopvalue=0;
std::cin >> loopvalue;
for(int i = 0; i < loopValue; i++)
{
std::cin >> number;
You should check the value of std::cin after the >> operations to ensure that they succeeded.
Refs:
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html
http://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt
If you use std::cin >> value; to read the value then you can only process the entire line once a new-line has been detected.
If you want to process each number as it is typed then you could use a function like:
int nextInt()
{
std::stringstream s;
while (true)
{
int c = getch();
if (c == EOF) break;
putch(c); // remove if you don't want echo
if ((c >= '0' && c <= '9') || (c == '-' && s.str().length() == 0))
s << (char)c;
else if (s.str().length() > 0)
break;
}
int value;
s >> value;
return value;
}
OK, there are probably more efficient ways to write that but it will read the input character by character until a number is encountered and will return whatever number is read when anything other than a number is encountered.
E.g. 1 2 3 4 would return 1 on the first call, 2 on the second etc.

Categories