I'm attempting a code abbey problem and i'm very stuck. My goal for the program is to take in numbers with a math operation before the number and to do that math operation such as:
5
+ 3
* 7
+ 10
* 2
* 3
+ 1
% 11
answer:
1
I feel as if i'm very close but cannot seem to get the answer I want to also add my answers up every single time.
import java.util.Scanner;
public class ModularCalculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter Initial Number:");
int iN = in.nextInt();
int sum = 0;
for (int i = 0; i <= 1000000; i++) {
String a = in.next();
int b = in.nextInt();
if (a.equalsIgnoreCase("+")) {
System.out.println(b + iN);
} else if (a.equalsIgnoreCase("*")) {
System.out.println(b * iN);
} else {
System.out.println(b % iN);
sum = b + iN;
}
}
}
}
Your issue is that your not doing proper algebra. Remember the order of operations. In your particular case, we can simplify it to only use the operations that you have, which are: Multiply, Modulo, Addition. Technically, Modulo isn't really standardized in where it is ordered, but I think most languages have Modulo as the same as Multiply/Divide, so a safe bet is to order it that way.
Since this is for a homework assignment clearly, I'm not going to fix your code for you. I will tell you though, that is definitely your issue. Think about how you would go about solving this...hint hint...don't read a token at a time...try reading more than that...
this will not work correctly ! because you are not working right , for example :
the answer of 1+2*3 equals to 7
but your program will return 9 as answer
i think you must learn about postfix and prefix and how to use stack to achieve this goal , here is a link for study :
http://www.cs.man.ac.uk/~pjj/cs212/fix.html
The problem you were having was that you weren't storing the value from last calculation properly. Al I did was just storing last calculated value in "iN".
Scanner in = new Scanner(System.in);
System.out.println("Enter Initial Number:");
int iN = in.nextInt();
int sum = 0;
for (int i = 0; i <= 1000000; i++) {
String a = in.next();
int b = in.nextInt();
if (a.equalsIgnoreCase("+")) {
iN = b + iN;
} else if (a.equalsIgnoreCase("*")) {
iN = b * iN;
} else {
iN = b % iN;
sum = b + iN;
}
System.out.println(iN);
}
Related
I've just written some code to form some statistics in java:
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
byte[] weekEval = new byte[18];
String weekMatch = "";
byte order = -1;
while (++order < 18) {
byte tmpRes = 10;
byte count = 5;
if (sc.hasNextByte())
weekMatch += sc.nextByte();
Scanner scInScope = new Scanner(weekMatch);
weekMatch = scInScope.findInLine("Week \\d+");
if (weekMatch == null) {
System.err.println("Illegal Argument");
sc.close();
System.exit(-1);
}
String orderMatch = "Week " + (order + 1);
if (!orderMatch.equals(weekMatch)) {
System.err.println("Illegal argument");
sc.close();
System.exit(-1);
}
weekMatch = "";
for (byte readData = 0; readData < 5; ++readData) {
if (sc.hasNext())
weekMatch += sc.next();
else {
System.err.println("Illegal argument");
sc.close();
scInScope.close();
System.exit(-1);
}
weekMatch += ' ';
}
scInScope = new Scanner(weekMatch);
weekMatch = scInScope.findInLine("\\d \\d \\d \\d \\d");
if (weekMatch == null) {
System.err.println("Illegal Argument");
sc.close();
System.exit(-1);
}
scInScope = new Scanner(weekMatch);
while (count-- > 0) {
tmpRes = scInScope.nextByte();
if (weekEval[order] > tmpRes)
weekEval[order] = tmpRes;
}
}
for (int i = 0; i < 18 && weekEval[i] != 10; ++i) {
System.out.print("Week " + (i + 1) + ' ');
while (weekEval[i]-- > 0)
System.out.printf("=");
System.out.println(">");
}
sc.close();
It works, but I need to complete task without arrays. Ok, I have String at least, right? Wrong. Any String concatenation within a loop is forbidden. The only string method I'm allowed to use is string.equals. There are also system.out, system.err and scanner(System.in). I ran out of ideas, what trick i can use...
Well, at first, I want to apologize for not posting subject and so unclear question. So the task is next:
Customer evaluates this progress as a minimal grade for five tests within each week. Each test can be graded between 1 and 9.
The maximum number of weeks for the analysis is 18. Once the program has obtained information for each week, it displays the graph on the console to show minimum grades for a specific week.
And we keep assuming that 42 is the input data limit.
The exact guaranteed number of tests in a week is 5.
However, the order of weekly data input is not guaranteed, so Week 1’s data can be entered after Week 2’s data. If data input order is wrong, IllegalArgument message shall be displayed, and the program shall be shut down with -1 code.
The problem was in the very-very confusing notes
Note:
• There are many options for storing information, and arrays are just one of them. Apply another method for storing data about student tests without the use of arrays.
• String concatenation often results in unexpected program behavior. If there are many iterations of a concatenation operation in a cycle for a single variable, an application may slow down significantly. That is why we should not use string concatenation inside a loop to generate a result.
In before, '->' stands for the user input. So, overall, it should be looked like:
-> Week 1
-> 4 5 2 4 2
-> Week 2
-> 7 7 7 7 6
-> Week 3
-> 4 3 4 9 8
-> Week 4
-> 9 9 4 6 7
-> 42
Week 1 ==>
Week 2 ======>
Week 3 ===>
Week 4 ====>
The core trick hides in java.utils.scanner and some very handy regex formulas. The final solution is below
import java.util.Scanner;
public class Program {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
byte roll = 0;
long multModif = 1;
long result = 0;
sc.useDelimiter("\\u000A");
while (roll < 18) {
byte tool = 0;
if (sc.hasNext("(42)|(Week(\\s)(\\d))")) {
sc.useDelimiter("\\s+");
String verify = sc.next();
if (verify.equals("42"))
break ;
tool = sc.nextByte();
sc.useDelimiter("\\u000A");
}
else {
System.err.println("Illegal Argument");
sc.close();
System.exit(-1);
}
if (tool != ++roll) {
System.err.println("Illegal Argument");
sc.close();
System.exit(-1);
}
tool = 10;
if (sc.hasNext("(\\d)(\\s)(\\d)(\\s)(\\d)(\\s)(\\d)(\\s)(\\d)")) {
sc.useDelimiter("\\s+");
for (byte i = 0; i < 5; ++i) {
byte toolTmp = sc.nextByte();
if (tool > toolTmp)
tool = toolTmp;
}
sc.useDelimiter("\\u000A");
} else {
System.err.println("Illegal Argument");
sc.close();
System.exit(-1);
}
result += tool * multModif;
multModif *= 10;
}
for (byte i = 0; i < roll; ++i) {
byte weekRes;
weekRes = (byte)(result % 10);
result /= 10;
System.out.print("Week ");
System.out.print(i + 1);
System.out.print(' ');
for (byte j = 0; j < weekRes; ++j)
System.out.print('=');
System.out.println('>');
}
}
}
I made it through some tests, but, frankly to say, not 100% sured about accuracy of my solution, but it works and satisfies noted mentioned above. That you guys for assistance, and big sorry for so confusing question...
//to display second smallest number out of three
import java.util.*;
public class Prog
{
public static void main(String[] args)
{
Scanner in = new Scanner (System.in);
int a,b,c,d,e;
System.out.println("Enter three numbers");
a = in.nextInt();
b = in.nextInt();
c = in.nextInt();
d = Math.min(a, b);
e = Math.max(d,c);
System.out.println(+e);
}
}
I have made this code but I want that when the user inputs the numbers they are unequal, how can I do so with this program?
This is according to your question and comments in the question that you will have only 3 inputs and you want to find 2nd smallest and you have to use min and max only.
If it is not the case update the question for the correct answer to your intended question.
int d=a+b+c;
int e=Math.max(a,Math.max(b,c));
int f=Math.min(a,Math.min(b,c));
System.out.println(d-(e+f));
What you have is close, but in order to ensure you get 3 unique numbers and that you accurately return the middle number, I'd suggest using something like the following.
public static void main(String[] args) {
List<Integer> enteredValues = getEnteredValues();
if (enteredValues.size() != 3) {
// something went terribly wrong, but just to be safe
} else {
int a = enteredValues.get(0);
int b = enteredValues.get(1);
int c = enteredValues.get(2);
int min = Math.min(a, Math.min(b, c));
int max = Math.max(a, Math.max(b, c));
if (a > min && a < max) {
// a is mid
} else if (b > min && b < max) {
// b is mid
} else {
// c is mid
}
}
private static List<Integer> getEnteredValues() {
Scanner in = new Scanner(System.in);
List<Integer> enteredValues = new LinkedList<>();
System.out.println("Enter 3 unique numbers");
while (enteredValues.size() < 3) {
Integer enteredValue = in.nextInt();
if (enteredValues.contains(enteredValue)) {
// probably prompt them to enter another number
} else {
enteredValues.add(enteredValue);
}
}
return enteredValues;
}
So what this does is first get the 3 numbers from the user. It'll force them to enter 3 unique numbers by only adding their input to the collection if it's unique.
After it fetches the numbers from the user, it'll use Math.min and Math.max to get the min and max between all 3 numbers. Then, it's just a simple if/else tree to figure out which one lies in between the calculated min/max.
I hope this helps!
Given two numbers a and b, find kth digit from right of a^b?
Link for the problem:
http://www.practice.geeksforgeeks.org/problem-page.php?pid=302
MyApproach:
I took 4 numbers as Input.First was the number of test cases.Then,Input was numbers a b and k respectively(Seperated by space).I calculated a^b and then from right searched each number till the time kth digit is not equal to the count.If I get them equal I returned the remainder expected.
Below is the Code:
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();
for(int i=1;i<=T;i++)
{
int count=1;
int a=sc.nextInt();
System.out.print(" ");
int b=sc.nextInt();
System.out.print(" ");
int k=sc.nextInt();
long result=(long) Math.pow(a,b);
if(k!=count)
{
while(k!=count)
{
count++;
int remainder=(int) (result%10);
result=result/10;
}
}
result=result%10;
System.out.println(result);
}
}
GeeksId Output:
Wrong !! Here your code Failed
Input:
7 6 3
And its Correct output is:
6
Eclipse ID:
Input:
7 6 3
Output
6
Wny I am getting Failed on geeksId?Is my solution do not produce correct output?
It seems like you did not follow the direction of the problem. The problem gives you a few constraints. you do not do a check for those. You should add the code to check that, so it will make sure you do not run into any exceptions.
I wanted to point out that you can just convert the Math.pow(a,b) result to string, and print the length - k char using the charAt function. This will make it very easy. and gets rid of the loops.
Code for that part is:
String tempString = String.valueOf(result);
System.out.println(tempString.charAt(tempString.length() - k));
Hope this puts you in the right direction.
Can also be done this way without much String operations and not expecting the intermediate output a^b to store in long data type,
private void handle() {
Scanner scanner = new Scanner(System.in);
int T = scanner.nextInt();
for(int i = 0; i < T; i++) {
findKthDigit(scanner);
}
scanner.close();
}
private void findKthDigit(Scanner scanner) {
int a = scanner.nextInt();
int b = scanner.nextInt();
int k = scanner.nextInt();
System.out.println((int)((Math.pow(a, b) % Math.pow(10, k))
/ Math.pow(10, k-1)));
}
As requested, your program is modified to make it work in GFG system,
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();
for(int i=1;i<=T;i++)
{
int count=1;
int a=sc.nextInt();
//System.out.print(" ");
int b=sc.nextInt();
// System.out.print(" ");
int k=sc.nextInt();
long result=(long) Math.pow(a,b);
if(k!=count)
{
while(k!=count)
{
count++;
int remainder=(int) (result%10);
result=result/10;
}
}
result=result%10;
System.out.println(result);
}
}
Hope this helps to understand. (however, you need to check other related exceptions for a good programming practice)
I want to check whether a length of an input text is divisible by 2.
so it will be like
if my text length is 3, the result will be 1.5 and it will display not divisible by 2 and
if my text length is 6, the result will be 3.0 and it will display divisible by 2
but my codes will display the output "not divisible by 2" regardless what is the text length.
what have I done wrong?
import java.util.Scanner;
public class Test1 {
public static void main (String[]args)
{
String a =null;
int l = 0;
double result = 0.0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter your string\n");
a = scan.nextLine();
l = a.length();
result = (double)l/2.0;
System.out.println(result);
if((double)result % 2 != .0) {
System.out.println("not divisiable by 2");
}
else {
System.out.println("divisiable by 2");
}
}
}
The mod operation is your friend but only with integers...
if (integer % divisibleBy == 0) { do stuff; }
Edit: I also found this page that does a really good job outlining the various uses mod the mod operator and explains why your double mod doesn't work like you expect.
Edit: Also more review of your code; it looks like you divide by 2 and then do mod by 2. So 6/2 = 3 and 3 is not even. Wonder if your code would work if you used 8 -> 8/2 = 4 and 4%2 = 0.
Check the length of the text, then do a modulo to it.
Modulo , an operation which checks if a number will have a remainder if its divided by another number
yourNumber%5 == 0
where yourNumber is the lenght of your String. Take it from here.
First, length() returns an int, and it's simpler to work with integers, so why are you casting the length to double? The % (modulo) operator is meant to work with integers, not doubles; remember, double numbers are floating-point numbers, so there's always room for numerical error if you use them.
Second, you don't need to use so many variables; keep it simple:
a = scan.nextLine();
if(a.length() % 2 == 0)
System.out.println("Length of string is divisible by 2");
else
System.out.println("Length of string is not divisible by 2");
Easier to read (and write), don't you think?
import java.util.Scanner;
public class Test1 {
public static void main (String[]args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter your string\n");
String str = scan.nextLine();
int length = str.length();
if(length % 2 !=0) {
System.out.println("not divisible by 2");
}
else {
System.out.println("divisible by 2");
}
}
}
There were a lot of problems with your code:
You are using a double to store the result for some reason, when it should've been an int
Your variable names are not descriptive of what they are for.
There is no need to initialize variables to a default value only to overwrite them with new values.
haha i hate these little mistakes. i do them all the time. Just switch both to %
String a =null;
int l = 0;
double result = 0.0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter your string\n");
a = scan.nextLine();
l = a.length();
//this is your problem
result = (double)l%2.0;
//this is your problem
System.out.println(result);
if((double)result % 2 != .0) {
System.out.println("not divisiable by 2");
}
else {
System.out.println("divisiable by 2");
}
So i have to write a program for homework where it takes a binary number and prints out its the decimal form. I've tried and and i just can't really get it. Like im printing out what it's doing every time in the loop and it looks like im getting the wrong value when i multiply the inputed data by the 2^i. If someone could help, that would be amazing
import java.util.Scanner;
public class Homework {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner userinput = new Scanner(System.in);
System.out.println("Enter a binary number (only 1's or 0's): ");
String binary_number = userinput.next();
int value = 0;
int square_value = 0;
for (int i = 0; i < binary_number.length(); i++) {
char binary_place_holder = binary_number.charAt(i);
square_value = (int) Math.pow(2, i);
if (binary_place_holder == '1') {
value = (square_value*binary_place_holder+value);
}
System.out.println(binary_place_holder+ " " + square_value + " " + value);
}
System.out.print(binary_number + " == " + value);
}
}
The way you determine the exponent is wrong: The exponent is not i.
You need to realize that you are looking at the string from left to right side so from the highest bit.
This means the first character's exponent is 2^string_length-1.
Second character's exponent is 2^string_length-2 and so on.
Therefore as the index i becomes larger, i.e. as we are scanning the input left to right, the exponent value becomes smaller.
So the exponent is:
int exponent = binary_number.length() - 1 - i;
Note: You can of course do things in reverse and start from the end of the input string and determine the exponent that way, I just wanted to do less changes to your code.
Also, you should add a check to make sure the input is a valid binary number. You can write your own function to do it but a simpler solution is to use regex matching:
binary_number.matches("[01]+")
This will return true if the string binary_number contains only '0' and '1' characters, and false otherwise.
Applying all these changes to your code:
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner userinput = new Scanner(System.in);
System.out.println("Enter a binary number (only 1's or 0's): ");
String binary_number = userinput.next();
if(!binary_number.matches("[01]+")) {
System.err.println("\nPlease enter a valid binary number");
} else {
int value = 0;
for (int i = 0; i < binary_number.length(); i++) {
if (binary_number.charAt(i) == '1') {
int exponent = binary_number.length() - 1 - i;
value += (int) Math.pow(2, exponent);
}
}
System.out.print(binary_number + " == " + value);
}
}
This might be considered cheating but you could go all like
System.out.println(Integer.parseInt(binary_number, 2));