I've got 2 integer values, e.g. a = 10 and b = 20.
Now i want to substract them: a - b, but as a result i don't want to have negative values, so in this example i want the result 0 and a new integer variable with the rest (10 here).
Two more examples:
Input: a=40, b=20; Expected Output:20
input: a=25 b=50 Expected Output: 0 and a new int var = 25
How to do this in java without external libraries?
From what I understand, you want a variable to be holding the result if the result is greater than or equal to 0. Otherwise, that variable should hold 0 and another variable will hold a positive value of the result.
If this is the case, consider the following code snippet:
int result = a -b;
int otherVariable = 0;
if (result < 0) {
otherVariable = -result;
result = 0;
}
int aMinusB = a-b;
int output = Math.max(aMinusB,0);
int rest = aMinusB < 0 ? Math.abs(aMinusB) : 0;
https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html
There are two ways to solve this problem: -
First: -
If you don't want to create a method to return this value and only to display it, then you can do it by printing out the results of if-else block in the code below within the function itself.
Second: -
If you want to use the result somewhere else, go for an object based approach: -
// Main class
public class SubtractWithRest {
public static void main(String[] args) {
SubtractResultWithRest subtractResultWithRest = new SubtractResultWithRest();
subtraction(10, 20, subtractResultWithRest);
System.out.println("Result: " + subtractResultWithRest.getResult());
System.out.println("Rest: " + subtractResultWithRest.getRest());
}
private static void subtraction(int num1, int num2, SubtractResultWithRest subtractResultWithRest) {
if (num2 > num1) {
subtractResultWithRest.setResult(0);
subtractResultWithRest.setRest(num2 - num1);
} else {
subtractResultWithRest.setResult(num1 - num2);
}
}
}
// Object class
public class SubtractResultWithRest {
private int result;
private int rest = 0;
public int getResult() {
return result;
}
public void setResult(int result) {
this.result = result;
}
public int getRest() {
return rest;
}
public void setRest(int rest) {
this.rest = rest;
}
}
Related
I have to implement the following function in Java: public int stringToNumber(String input) without using Integer or any other class or method that parses the string. I have to loop over the characters of the string.
I attempted created a class that uses a loop to convert String to Integer.
Now, I am trying to figure out how I can return 0 if the string contains anything other than digits and an initial "-" for negative numbers.
Also I am trying to return 0 if the number is too large or too small for an int (Integer.MIN_SIZE to Integer.MAX_SIZE or -2^31 to 2^31 - 1).
Below is the code that I have so far.... Any help would be greatly appreciated
public class StringToNumber {
public static void main(String[] args) {
StringToNumber stn = new StringToNumber();
for (String arg : args) {
int number = stn.stringToNumber(arg);
System.out.format("Input number: %s, parsed number: %d %n", arg, number);
}
}
public int stringToNumber(String stn) {
int number = 0, factor = 1;
for (int n = stn.length()-1; n >= 0; n--) {
number += (stn.charAt(n) - '0') * factor;
factor *= 10;
}
return number;
}
}
Check if below code is working for you
public int stringToNumber(String stn) {
int number = 0, factor = 1;
int negative = 0;
if(stn.charAt(0)=='-') {
negative =1;
}
for (int n = negative; n < stn.length(); n++) {
int digit = stn.charAt(n)-'0';
if(digit<0 || digit>9)
return 0;
if((negative==0) && (Integer.MAX_VALUE-digit)/10 <number)
return 0;
else if ((negative==1) && (Integer.MAX_VALUE-digit+1)/10 <number)
return 0;
number = number*10+ (stn.charAt(n)-'0');
}
if(negative == 1) {
return -1*number;
}
return number;
}
Perhaps the best way to handle this would be to use Integer#parseInt(), which takes a string input and either returns an integer result or throws an exception if the input cannot be coerced to an integer:
public int stringToNumber(String stn) {
int result;
try {
result = Integer.parseInt(stn);
}
catch (NumberFormatException e) {
System.out.println("String input cannot be converted to integer: " + stn);
result = 0; // return 0 as the failure value
}
return result;
}
I have to make a program which works like this. first it gets a number from input and then it gets (number) * strings.
for example:
2
a b
or
3
x1 x2 x3
then in the output it prints something like this:
Math.max(a, b)
or
Math.max(x1, Math.max(x2, x3))
I want to make Math.max method syntax with this code. I hope you understood!
Another Sample Input & output:
Input =
4
a b c d
Output =
Math.max(a, Math.max(b, Math.max(c, d)))
can someone help me?
The code I've wrote for it, can you suggest me some changes to make it better?
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
String[] r = new String[n];
for (int i = 0; i < n; i++) {
r[i] = input.next();
}
printmax(r);
}
public static int i = 0 , j = 0;
public static boolean last = false;
public static void printmax(String [] r){
if (last == true) {
System.out.print(r[r.length - 1]);
while (j < r.length - 1){ System.out.print(")");
j++;
}
}
if (r.length == 2) System.out.print("Math.max(" +r[0] + ", " + r[1] + ")");
if (r.length > 2) {
while (i < r.length -1) {
if (i == r.length -2) last = true;
System.out.print("Math.max(" + r[i] + ", ");
i++;
printmax(r);
}
}
}
}
You can use the following code to achieve the above, here m calling maxElement() function recursively to achieve somthing like this Math.max(a, Math.max(b, Math.max(c, d)))
public static void main(String args[]){
int length = 2; //here read the input from scanner
String[] array = {"a", "b"}; //here read this input from scanner
String max = maxElement(array,0,length);
System.out.println(max);
}
public static String maxElement(String[] start, int index, int length) {
if (index<length-1) {
return "Math.max(" + start[index] + ", " + maxElement(start, index+1, length)+ ")";
} else {
return start[length-1];
}
}
Output:
Math.max(a, b)
You need to do something like this.
First you define a function maxElement which takes your variable array as a parameter.
public static maxElement(String[] variables) {
return maxElementBis(variables,0);
}
Then you call a second function : maxElementBis which takes an additional argument which represents the index of the variable we are processing.
public static String maxElementBis(String[] variables, int index) {
if (variables.length < 2)
return "not enought variables";
if (variables.length - index == 2)
return "Math.max("+ variables[index]+","+variables[index + 1]+")";
return "Math.max("+ variables[index]+","+maxElementBis(variables,index + 1)+")";
}
If the array contains less than two variables you cannot do what you want.
If you only have two variables left, this is your stop condition and you can directly return Math.max(v1,v2).
Otherwise you recursively call your function maxElementBis.
the code below is meant to count each time character 'x' occurs in a string but it only counts once ..
I do not want to use a loop.
public class recursionJava
{
public static void main(String args[])
{
String names = "xxhixx";
int result = number(names);
System.out.println("number of x: " + result);
}
public static int number (String name)
{
int index = 0, result = 0;
if(name.charAt(index) == 'x')
{
result++;
}
else
{
result = result;
}
index++;
if (name.trim().length() != 0)
{
number(name);
}
return result;
}
}
You could do a replacement/removal of the character and then compare the length of the resulting string:
String names = "xxhixx";
int numX = names.length() - names.replace("x", "").length(); // numX == 4
If you don't want to use a loop, you can use recursion:
public static int number (String name)
{
if (name.length () == 0)
return 0;
int count = name.charAt(0)=='x' ? 1 : 0;
return count + number(name.substring(1));
}
As of Java 8 you can use streams:
"xxhixx".chars().filter(c -> ((char)c)=='x').count()
Previous recursive answer (from Eran) is correct, although it has quadratic complexity in new java versions (substring copies string internally). It can be linear one:
public static int number(String names, int position) {
if (position >= names.length()) {
return 0;
}
int count = number(names, position + 1);
if ('x' == names.charAt(position)) {
count++;
}
return count;
}
Your code does not work because of two things:
Every time you're calling your recursive method number(), you're setting your variables index and result back to zero. So, the program will always be stuck on the first letter and also reset the record of the number of x's it has found so far.
Also, name.trim() is pretty much useless here, because this method only removes whitespace characters such as space, tab etc.
You can solve both of these problems by
making index and result global variables and
using index to check whether or not you have reached the end of the String.
So in the end, a slightly modified (and working) Version of your code would look like this:
public class recursionJava {
private static int index = 0;
private static int result = 0;
public static void main(String[] args) {
String names = "xxhixx";
int result = number(names);
System.out.println("number of x: " + result);
}
public static int number (String name){
if(name.charAt(index) == 'x')
result++;
index++;
if(name.length() - index > 0)
number(name);
return result;
}
}
You can use StringUtils.countMatches
StringUtils.countMatches(name, "x");
i wrote the following codes
my aim is to get the lowst value of doble[] absOfSub but it gives the following exception
at line compared= Double.compare(d2, d1);
Exception in thread "main" java.lang.StackOverflowError
why overflow and how to fix it?
EDIT
public class TestThe {
static double[] absOfSub = new double[5];
private static int index=0;
private static int compare(int currentIdx, int minIdx) {
if(index < absOfSub.length) {
if(absOfSub[currentIdx] < absOfSub[minIdx]) {
compare(currentIdx + 1, currentIdx);
} else {
compare(currentIdx + 1, minIdx);
}
}
return minIdx;
}
public static void main(String[] args) {
absOfSub[0]=1000;
absOfSub[1]=810;
absOfSub[2]=108;
absOfSub[3]=130;
absOfSub[4]=110;
double result;
int inndex= compare(0,1);
System.out.println(absOfSub[inndex]);
}
}
How about this simple and elegant solution?
static double min(double... ds) {
double min = Double.POSITIVE_INFINITY;
for (double d : ds) min = Math.min(min, d);
return min;
}
public static void main(String[] args) {
System.out.println(min(-5.2, 0, -10.1, 3));
}
Recursive solution (not recommended!):
static double minRecur(double... ds) {
return minRecur(ds, 0, Double.POSITIVE_INFINITY);
}
static double minRecur(double[] ds, int i, double runningMin) {
return (i < 0 || i >= ds.length)?
runningMin : minRecur(ds, i + 1, Math.min(runningMin, ds[i]));
}
You don't change the value of index inside your method. So this recursive method call won't stop at all.
You never manipulate the value of the index variable. You see another reason why people should try to limit the number of static variables they use. Let me try to help you:
public class TestThe {
private static double[] absOfSub = new double[5];
private static void compare(int currentIdx, int minIdx) {
if(currentIdx < absOfSub.length) {
if(absOfSub[currentIdx] < absOfSub[minIdx]) {
return compare(currentIdx + 1, currentIdx);
} else {
return compare(currentIdx + 1, minIdx);
}
} else {
return minIdx;
}
}
public static void main(String[] args) {
absOfSub[0] = 10;
absOfSub[1] = 810;
absOfSub[2] = 108;
absOfSub[3] = 130;
absOfSub[4] = 110;
System.out.println("The minimum value is: " + absOfSub[compare(0, 0)]);
}
}
EDIT Some more notes:
always specify the attribute accessor as private, when this is the intention
always format your code
when you write recursion, make sure you always change something for every consequent call and that it gets you closer to the ending condition.
double primitive type itself defines a comparison operator, no need to use Double.compare in your case.
You don't actually change the index variable, so the recursion will never end. But there is a lot more wrong with this.
An easy generic way to find the minimal value in an array, without using recursion:
int min = Integer.MAX_VALUE;
for( int i = 0; i < array.length; i++ ) {
// Math.min returns the lower value of the two arguments given
min = Math.min( min, array[i] );
}
return min;
This could be easily adapted to fit your needs.
Index in each routine is having either 0 or 1 or 2 as the value.
First my call back to increment I know is not correct. I am not sure what to do. I need increment to use temp when it hits that case that requires that call back. I can't change increment to pass a parameter into it because the graders test script wont allow for it. The second problem is that it wont increment any input. For instance if you just call increment on the number 23 it just returns 23. The test script for the grader looks something like this:
public class TestBigNaturalSimple {
public static void main(String[] args) {
BigNatural b1 = new BigNatural(); // default constructor
BigNatural b2 = new BigNatural(23); // one-argument int constructor
BigNatural b3 = new BigNatural("346"); // one-argument String constructor
BigNatural b4 = new BigNatural(b2); // one-argument BigNatural
// constructor
b1.increment();
b3.decrement();
System.out.println(b1.toString()); // should print out 1
System.out.println(b4.toString()); // should print out 23
}
}
My code is:
public class BigNatural {
private String num;
public BigNatural(String input) {
num = input;
}
public BigNatural(BigNatural input) {
num = input.toString();
}
public BigNatural(Integer input) {
num = input.toString();
}
public BigNatural() {
Integer i = 0;
num = i.toString();
}
public void increment() {
Integer first = 0;
Character ch = num.charAt(num.length()-1);
Integer last = Character.digit(ch, 10);
if (num.length() > 1)
{
if (last < 9) {
last++;
}
else
{
if (num.length() >= 2)
{
last = 0;
String temp = new String(num.substring(0, num.length()-2));
increment();
}
else
{
last++;
}
}
}
else
{
if (last < 9)
{
last++;
}
else
{
last = 0;
first = 1;
}
}
String t = last.toString();
if (first > 0)
{
String x = first.toString();
num.concat(x);
}
num.concat(t);
}
public void decrement() {
Character ch = num.charAt(num.length()-1);
Integer last = Character.digit(ch, 10);
if(num.length() > 1)
{
if(last == 0)
{
String temp = new String(num.substring(0, num.length()-2));
decrement();
}
else
{
last--;
}
}
else
{
if(last > 0)
{
last--;
}
else
{
last = 0;
}
}
String t = last.toString();
num.concat(t);
}
public String toString() {
return num;
}
}
That has to be the most complicated way to increment a number I have ever seen. ;) I assume you have to do it that way.
From what I can see you don't change num anywhere. I would expect this to be obvious if you used a debugger. ;)
Try using num = num.concat(t) if you expect num to change.
Note: String is immutable so you cannot change it, you can only replace it.
EDIT: Here is a version provided for your own interest. Your professor will know you didn't write this, so don't copy it. ;)
public void increment() {
num = increment(num);
}
private static String increment(String s) {
if (s.length() <= 0) return "1";
char ch = s.charAt(s.length() - 1);
String top = s.substring(0, s.length() - 1);
return ch < '9' ? top + ++ch : increment(top) + '0';
}
Strings are immutable in Java. Hence, the code
num.concat(t);
in your increment method will not do what you expect.
First, apply the rule don't repeat yourself:
to increment is to add 1
to decrement is to add -1
Thus you simply need to write on function that takes a number as input and add it to your BigNatural:
public void increment() {
add(1);
}
public void decrement() {
add(-1);
}
private void add(int i) {
// Your homework here ...
// You will have only one function to debug and correct, not 2
}
Second: as pointed in other answers, num.concat(t); does not do what you expect, you'll need num = num.concat(t);. Always refer to the Java documentation when you use a function you don't know. If you don't have an editor that allows you to debug your programs, I strongly suggest you get one: Eclipse for instance but other editors might be better as learning tool. The added benefit is that the tools will format the code for you, warn you about lots of mistakes, ...