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

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.

Related

How to take a string and read it for an array

Im having trouble finding out how to read letters and turn them into numbers like -1 and 1.
Here's the context:
I'm working on a word problem for my Java programming class. I'm asked to create a program in Java that receives input of a number of "L"s or "R"s, short for left or right. For each L the program should go one spot back in an array, and for each R it should go one spot forward. Like if you start at 0, and get an input of RR, it should move to be at 2. Hopefully that makes sense, here's a diagram to hopefully clarify.
Now, what I don't understand is how to take the input from using Scanner(System.in) that gives me the L/R combination (eg. LLR) and turn that into the series of directions for the program (eg. -1,-1,+1). How do i specify that the input of an L is equal to going one space back? And vice versa for any R's input into the program?
Any tips would be greatly appreciated, thanks a ton
Edit: Heres the current code I have:
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[] ) throws Exception {
int max = 100;
int min = 1;
int posMax = 10000;
int posMin = -10000;
boolean dataExists = false;
String inputData;
int initialPosition;
System.out.println("Insert sequence of commands (L and R)");
Scanner input = new Scanner(System.in);
inputData = input.nextLine();
System.out.println("Input starting position");
initialPosition = input.nextInt();
}
}
What it does it it defines the minimum and maximum commands (left and rights, which is 1-100) and the min and max positions which are -10000 and 10000. The next part would have been recieving the string of L's and R's and reading them to change the array but thats where im stuck.
The return value of Scanner.nextLine() is a String Object.
You can split up this String Object to a char array and check if the char is a 'L', 'R', or something else.
String cmds = "RRRRRLLLRLRLLRLRLLRLLRLRL";
char[] cCmds = cmds.toCharArray();
int pos = 39;
for (char c : cCmds) {
switch (c) {
case 'L' -> pos--;
case 'R' -> pos++;
default -> System.out.println("That was not an L or R...");
}
}
System.out.println("Position: " + pos);
Next step would now to add some conditions to check if the user input was too long or too short.
if (cmds.length() > MAX_INPUT || cmds.length() < MIN_INPUT) {
System.out.println("User input was too long or too short");
return;
}
The last step now is to check if you can move to another position each time if you want to move.
case 'L' -> { if (pos > POS_MIN) pos--; }
case 'R' -> { if (pos < POS_MAX) pos++; }
All in one, it would look like this (with Scanner):
import java.util.Scanner;
public class Solution {
static final int MIN_INPUT = 1;
static final int MAX_INPUT = 100;
static final int POS_MIN = -10000;
static final int POS_MAX = 10000;
public static void main(String[] args) {
System.out.println("Insert sequence of commands (L and R)");
Scanner input = new Scanner(System.in);
String cmds = input.nextLine();
if (cmds.length() > MAX_INPUT || cmds.length() < MIN_INPUT) {
System.out.println("User input was too long or short");
return;
}
System.out.println("Input starting position");
int pos = input.nextInt();
char[] cCmds = cmds.toCharArray();
for (char c : cCmds) {
switch (c) {
case 'L' -> { if (pos > POS_MIN) pos--; }
case 'R' -> { if (pos < POS_MAX) pos++; }
default -> System.out.println("That was not an L or R...");
}
}
System.out.println("Position: " + pos);
}
}
Keep in mind to catch the exception which the Scanner Object can cause.
(e.g. when scanner.nextInt() gets non Integer user input)
And also add a check if the user input for the initial position is in the given range.

How can I get many outputs using only one input?

I want to change decimal to binary, octagonal, hexadecimal, By setting only one input(decimal) int i, I want to get 3 output: binary, octal, hexadecimal.
But my problem is that when I write 'while' once to change to binary using int i, I can't get proper answer about next 'while' to change to octagonal using int i.
I thought my code about octal was wrong, but when I set another int o, it worked properly...I think the result of first 'while' is used as input in next 'while'.
I wonder if I use 'while' once using int i, then can't I use that original int i in next 'while'?
I want to know how to get 3 output using only one input.
For example,
input
output
2017
b 11111100001
o 3741
h 7e1
It's my first time studying coding, so my question can be weird. Sorry:(
Code below is I made using two input.
import java.util.Scanner;
public class LA {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int i = scn.nextInt();
String ab = "";
while (i > 0) {
ab = (i % 2) + ab;
i /= 2;
}
System.out.println("b " + ab);
int o = scn.nextInt();
String cd = "";
while (o > 0) {
cd = (o % 8) + cd;
o /=8;
}
System.out.println( "o " + cd);
}
}
You first while loop changes the value of i. At the end of this while loop i=0 so the next while loop will fail immediat.
Just keep the input in a separate variable which you don't change and copy it to i before each while loop:
int input = scn.nextInt();
int i= input;
while () {}
i=input;
while(i>0) { }
As far as I see and according to documentation.
https://www.tutorialspoint.com/java/util/scanner_nextint.htm
You are calling scn.nextInt() 2 times and should be only called 1 time.
Because scn.nextInt() expect input from keyboard.
Save original input in another variable.
Here is the code:
import java.util.Scanner;
public class LA {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int originalInput = scn.nextInt();
int i = originalInput; // copy by value, not by reference.
String ab = "";
while (i > 0) {
ab = (i % 2) + ab;
i /= 2;
}
System.out.println("b " + ab);
int o = originalInput; // again copy original input here.
String cd = "";
while (o > 0) {
cd = (o % 8) + cd;
o /=8;
}
System.out.println( "o " + cd);
}
}
I'm not sure if you're trying to do it the hard way on purpose, but you can also use System.out.printf() for octal and hex, and Integer.toBinaryString(anInt) for binary.

How can I prevent the code from printing a negative output?

This is the code I am working on. The problem is when I enter a non hexadecimal value such as "rr" or "z", it prints a negative value. How can I stop it from doing this? Also, how can I solve this question? When the program starts it asks the user to enter a hexadecimal number of lengths 2 (e.g., 1F). The smallest number the user should enter is 90 (decimal equivalent 144) and the largest is FF (decimal equivalent 255).
import java.util.Scanner;
public class HexaConverter {
public static int hex2decimal(String s)
{
String digits = "0123456789ABCDEF";
s = s.toUpperCase();
int val = 0;
for (int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
int d = digits.indexOf(c);
val = 16*val + d;
}
return val;
}
//Start of conversion method
public static void main(String args[])
{
String hexadec_num;
int dec_num, i=1, j;
int bin_num[] = new int[100];
Scanner scan = new Scanner(System.in);
System.out.print("Please enter a Hexadecimal Number: ");
hexadec_num = scan.nextLine();
final int MAX_LENGTH = 2;
if(String.valueOf(hexadec_num).length() <= MAX_LENGTH) {
/* first convert the hexadecimal to decimal */
dec_num = hex2decimal(hexadec_num);
System.out.print("Equivalent Dec Number is : "+ dec_num);
System.out.println();
/* now convert the decimal to binary */
while(dec_num != 0)
{
bin_num[i++] = dec_num%2;
dec_num = dec_num/2;
}
System.out.print("Equivalent Binary Number is : ");
System.out.print("\n");
for(j=i-1; j>0; j--)
{
System.out.print(bin_num[j]);
}
}
else
{
System.out.println("ERROR: Input number was too long");
main(args); // calling to return to the main method
}
}
}
int d = digits.indexOf(c); will return -1 if the character doesn't exist in the digits string, if you add in a check for this:
int d = digits.indexOf(c);
if (d == -1) return 0; // CHECK HERE
val = 16*val + d;
Then you can handle the error as you like, in this example I just returned 0
As for the second part of the question, you can just check the value of the returned result is within the range 144 and 255
if (144 <= dec_num && dec_num <= 255) return "SUCCESS";
return "FAIL";

Printing error for every character read in the string

I'm looking not only how to do it, but also how to do it and produce an error message for a character that I don't want. So what I mean is I have the user put in input, then I want to produce an error message if the input the user put didn't have a 0 or a 1. So a 1121 would produce an error, but a 1101 would be fine.
I have this so far and in the shell it prints "error" after every character, even if it's correct.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n;
System.out.print("Please enter a sequence of 1's and 0's");
String binInput = scan.nextLine();
System.out.println(binaryToDecimal(binInput));
char c;
for (int j = 0; j < binInput.length(); j++) {
c = binInput.charAt(j);
if (c<0 || c>1){
System.out.print("Error");}
}
public static int binaryToDecimal(String binString) {
int size = binString.length();
if (size == 1) {
return Integer.parseInt(binString);
} else {
return binaryToDecimal(binString.substring(1, size)) + Integer.parseInt(binString.substring(0, 1)) * (int) Math.pow(2, size - 1);
}
}
Any help would be appreciated
Change the if statement like this
if (!(c == '0' || c == '1')){//...
It means
if c isn't character 0 or chararcter 1
c is defined as a char and java allows chars to utilize relational and equivalent operators. The charAt(int) method pulls the specific char out. In this case you should change your if statement to something like this:
if(c != '0' && c != '1')
O.K. let's see if this code will give you an error. (Please, be sure that you'r input didn't include any 'white spaces'
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n;
System.out.print("Please enter a sequence of 1's and 0's");
String binInput = scan.nextLine();
// System.out.println(binaryToDecimal(binInput));
char c;
for (int j = 0; j < binInput.length(); j++) {
c = binInput.charAt(j);
if (!(c == '0' || c == '1')) {
System.out.print("Error");
}
}
I commented out one statement - it isn't relevant...

Cannot print out read integers: 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.

Categories