How can I get many outputs using only one input? - java

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.

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.

An error with for loop

I am working on problem of string manipulation.Following is my code snippet.
I am really not sure why my code control is not going inside IF loop.
public class test{
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int searchVariable = scan.nextInt();
int numberOfValues = scan.nextInt();
scan.nextLine();
while (numberOfValues-- != 0) {
String strg = scan.nextLine();
String[] arrayInt = strg.split(" ");
for (int i = 0; i < arrayInt.length; i++) {
// System.out.println("test 1===");
// System.out.println("i value" + i);
// System.out.println("i " + strg.charAt(i));
// System.out.println(searchVariable);
if (searchVariable==strg.charAt(i)) {
System.out.println("===>");
System.out.println("index " + i);
return;
}
}
}
}
}
Input
4
6
1 4 5 7 9 12
Output
output should be 4.
As i am writing this code for finding integer 4 in the third line of input.
Problem
Program control is not going inside the loop if (searchVariable==strg.charAt(i))
.Please help!!
The is problem in your logic: What you actually want is
if (searchVariable==Integer.parseInt(arrayInt[i]))...
When java compares different objects, it checks different aspects, one of them is their type.
For example, the char '1' is different from the integer 1 and therefore '1'==1 will return false.
char c = '1';
System.out.println(c==1); //false
When comparing char to integer you should use parsing or the method Character.getNumericValue(c):
System.out.println(Character.getNumericValue(c)==1); //true
Also note that when java compares char to integer it uses the ascii value of the char, therefore ,char 'a' equals to the integer 97 and '1' equals integer value of 49: (and so on..)
System.out.println(c==49); //true

Trying to write a simple compiler in java (I am using notepad++)

My question is how would I write a simple compiler ,that is like the compilers used in fax machines, that would convert something like aaaavvvvvddddddddddd to 4a5vBd.
Also, I get to "Assume" that any string entered will not contain uppercase letters and no numbers, and that any string will contain less than 61 of any type of character so, I get to assume no one will put in 64 continues a's in my program.
This is as far as I gotten
import java.util.*;
public class Program4
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int n;
char cn;
String word;
String numChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
System.out.println("Hello, please enter a string");
word = scan.nextln();
if(n <= 61)
{
int n = ?;
cn = numChars.charAt(n);
}
}
}
I assume I need to use a loop, but I don't know what I should use to count the repeating letters and then tell how many letters of that type are in a row. Now I am only asking for advice and not so much for code, because I want to do it but, as a beginner my Java "Vocabulary" isn't very big right now.
Any advice/ tips would be greatly appreciated.
Sincerely,
Mr.Trips
Well I am back and it appears my code here likes to only print out 147. No matter what I type in I will always get 147. I have tried to hand trace all my variables, but when I do it I get exactly what I want, and I must have some error in my logic. Any thoughts?
import java.util.*;
public class Program4
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int n = 0;
int s = 0;
char a;
char b;
char c;
String word;
String numChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
System.out.println("Please enter a string");
word = scan.nextLine();
while (n < word.length())
{
a = word.charAt(n);
b = a;
n = n ++;
a = word.charAt(n);
if (a == b)
{
s = (s + 1) ;
}
else if (a != b);
{
c = numChars.charAt(s);
System.out.print(b + c);
s = 0;
c = 0;
break;
}
}
}
}
Thank you again!
Since you don't want code this is logically how to do it. You are right you should loop through the string for each char. Store the last char in a variable and keep a counter variable. Compare current char to last char if it is equal then increment the counter. As soon as it is not equal to the last char then add counter + last char to result string and reset counter variable. Each iteration update last char variable.

Why my code for checking if a number is a palindrom won't work?

My Java code is here:
import java.util.Scanner;
public class task2 {
public static void main(String args[]) {
System.out.print("Input a 3 digit int");
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int isPalindrome = 0;
while (x != 0)
{
isPalindrome = isPalindrome*10 + x % 10;
x /= 10;
}
{
if (x == isPalindrome){
System.out.print ("Yes, this is a palindrome!");
}
else {
System.out.print("No, try again");
}
}
}
}
The code will only recognize a palindrome if the numbers entered are zeroes. I'm having trouble understanding why.
This is because the value of x is getting changed finally.Which is not the original number at the end of the program.
SO take another variable just below x like:
int y = x;
And at the end while using "if" condition use this value of y for comparison rather than using x. It will run perfectly.
int x = scan.nextInt();
int y=x;
if (y == isPalindrome) Add new variable like this.
The problem with you solution is that you modify x in the while loop. Your final check of (x == isPalindrome) will always fail because you will only reach that statement when x is equal to zero.
You need to save the original x value in another variable and use that to check against isPalindrome.
The problem is that in the course of processing the value of x is being changed from what was originally input - it always ends up as 0.
So, you have to preserve the input value, like so:
Scanner scan = new Scanner(System.in);
int original = scan.nextInt();
int x = original;
and then use the original value for the final comparison, like so:
if (original == isPalindrome){
Here's how I'd do it: I'd use the libraries more and write a lot less code.
I'd recommend that you learn the Sun Java coding standards and develop a formatting style. Readability promotes understanding. Style and neatness matter.
package misc;
public class PalindromeChecker {
public static void main(String args[]) {
for (String arg : args) {
System.out.println(String.format("arg '%s' is" + (isPalindrome(Integer.valueOf(arg)) ? "" : " not") + " a palindrome", arg));
}
}
public static boolean isPalindrome(int value) {
String s = Integer.toString(value);
String reversed = new StringBuilder(s).reverse().toString();
return reversed.equals(s);
}
}
When you do the following operation on x:
x /= 10;
you're modifying its value - so it no longer contains the input from:
int x = scan.nextInt();
As Narendra Jadon suggested - you can save the original value into another variable and use it when you try to compare:
if (x == isPalindrome){
Alternative solution that uses "conversion" of the int to String:
public boolean isPalindrom(int n) {
return new StringBuilder("" + n).reverse().toString().equals("" + n);
}

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