I have a Switch statement within a loop where I am trying to print a random math operation in an equation multiple times. The whole code is quite long, so I'm hoping this is enough to answer my question.
I know for certain that the fifth case '%' does not work.
Here is my output
num1 = random.nextInt(max + 1 - min) + min;
num2 = random.nextInt(max + 1 - min) + min;
char op = switch (getOper(year)) {
case 1 -> '+';
case 2 -> '-';
case 3 -> '*';
case 4 -> '/';
case 5 -> '%';
default -> ' ';
};
//prints out the questions
System.out.print(num1 + " " + op + " " + num2 + " = ");
private int getOper(int year){
//sets the operatorBounds variable to zero
int operatorBounds = 1;
//creates a new random object
Random bounds = new Random();
int oper = 0;
//determines how many operations are available to each year level
if (year == 1 || year == 2){
operatorBounds = 2;
oper = bounds.nextInt(operatorBounds);
} else if (year == 3 || year == 4 || year == 5){
operatorBounds = 4;
oper = bounds.nextInt(operatorBounds);
} else if (year == 6 || year == 7){
operatorBounds = 5;
oper = bounds.nextInt(operatorBounds);
}
return oper;
}
This is the output I'm receiving:
6674 2640 = 1560 + -5740 = 1274 6126 =
The spaces are where the operator is supposed to be
If anyone can help I'd really appreciate it!
Related
I'm currently coding a program that converts a number to its word format, and thus far, I've written a code that only accepts no larger than the max value of an integer (2.14 billion). I was wondering how I would scale up the program's capability to accepting larger numbers.
(Edited): I've converted all my int values to long datatypes. I was able to scale the limitation up from 2.14 to 999 billion, though shouldn't be the max value of a long datatype is 9 quintillion?
The converter code:
public class Converter {
public static WordList wordFormat = new WordList();
public static final void converter(long value) {
long valueSize = String.valueOf(value).length();
String[] output = new String[(int) valueSize];
long outputSize = output.length;
long tracker = 1;
long commasCTR = 0;
long preValHolder = 0;
// Returns "Zero" if value = 0
if (value == 0) {
System.out.println("Zero");
return;
};
// Self-made Conversion Method
for (long valHolder = value, placeVal = 0; placeVal <= outputSize - 1; placeVal++, tracker++) {
long remainder = valHolder % 10;
long nextDigit = valHolder / 10 % 10;
valHolder = valHolder / 10;
// Num to Word Conditional Statements
switch ((int) tracker) {
case 1:
if (placeVal == 0) {
output[(int) placeVal] = WordList.wordFormat[0][(int) remainder]; // Ones
} else {
output[(int) placeVal] = WordList.wordFormat[0][(int) remainder].concat(" " + WordList.commas[(int) commasCTR]); // Commas
commasCTR++;
}
break;
case 2:
if (remainder == 1) { // Teens
output[(int) placeVal] = WordList.wordFormat[1][(int) preValHolder + 1];
if (placeVal < 3) output[(int) placeVal - 1] = " ";
else output[(int) placeVal - 1] = WordList.commas[(int) commasCTR - 1];
} else if (placeVal > 3 && preValHolder == 0 && remainder == 0 && nextDigit == 0) { // Comma Zero Value Handler
output[(int) placeVal - 1] = " ";
output[(int) placeVal] = WordList.wordFormat[2][(int) remainder];
} else {
output[(int) placeVal] = WordList.wordFormat[2][(int) remainder]; // Decades
}
break;
case 3:
output[(int) placeVal] = WordList.wordFormat[3][(int) remainder]; // Hundredths
break;
}
// Re-assigning Values
if (tracker == 3) tracker = 0;
preValHolder = remainder;
}
for (long i = outputSize - 1; i >= 0; i--) {
if (output[(int) i] == " ") continue;
System.out.print(output[(int) i].trim() + " ");
}
return;
}
}
}```
I think you could use BigInteger https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html
Hey' all so im figuring out how to multiply bigintegers without importing them and I have it almost all. The only thing that isnt working is when multiplying with -digit the output is still +. any help appreciated. ie. -20*4=80
Scanner scan = new Scanner(System.in);
System.out.println("Type the first number:");
String x = scan.nextLine();
System.out.println("Type the second number:");
String y = scan.nextLine();
if (x.charAt(0) == '-' && y.charAt(0) != '-') {
x = x.substring(1);
}
else if (x.charAt(0) != '-' && y.charAt(0) == '-') {
y = y.substring(1);
}
else if (x.charAt(0) == '-' && y.charAt(0) == '-') {
x = x.substring(1);
y = y.substring(1);
}
String s1 = new StringBuffer(x).reverse().toString();
String s2 = new StringBuffer(y).reverse().toString();
int[] m = new int[s1.length() + s2.length()];
for (int i=0; i<s1.length(); i++) {
for (int j=0; j<s2.length(); j++) {
m[i+j] = m[i+j] + (s1.charAt(i) - '0') * (s2.charAt(j) - '0');
}
}
String product = new String();
for (int i=0; i<m.length; i++) {
int digit = m[i] % 10;
int carry = m[i] / 10;
if (i+1 < m.length) {
m[i+1] = m[i+1] + carry;
}
product = digit + product;
}
while (product.length() > 1 && product.charAt(0) == '0') {
product = product.substring(1);
}
if (x.charAt(0) == '-' && y.charAt(0) != '-') {
product = new StringBuffer(product).insert(0, '-').toString();
}
else if (x.charAt(0) != '-' && y.charAt(0) == '-') {
product = new StringBuffer(product).insert(0, '-').toString();
}
else if (x.charAt(0) == '-' && y.charAt(0) == '-') {
product = product;
}
System.out.println("The multiplication of\n" + x + " \nand\n" + y + " " + "\nis\n" + product);
scan.close();
}
}
You're removing the negative symbol from the numbers here:
if (x.charAt(0) == '-' && y.charAt(0) != '-') {
x = x.substring(1);
}
else if (x.charAt(0) != '-' && y.charAt(0) == '-') {
y = y.substring(1);
}
So after those lines your x and y variables no longer contain the negative symbol.
So when you're checking it near the end here:
if (x.charAt(0) == '-' && y.charAt(0) != '-') {
product = new StringBuffer(product).insert(0, '-').toString();
}
else if (x.charAt(0) != '-' && y.charAt(0) == '-') {
product = new StringBuffer(product).insert(0, '-').toString();
}
else if (x.charAt(0) == '-' && y.charAt(0) == '-') {
product = product;
}
It will never get into any of the conditions.
One good way to debug this on your end is to set a breakpoint within the condition you think it should drop into and see if it's hit. Or breakpoint before the conditions and examine the variables to ensure they are what you expect them to be. You could also throw some println statements in there temporarily just to say "I got into this conditional".
The adjustment I'd recommend making is holding onto whether each number was negative before stripping the negative so you can use that in your logic later on.
Here's the adjustment which should accomplish what you want. I used Integers instead of bools to make the check for whether to apply the negative symbol later easier (i.e. isFirstNumberNegative + isSecondNumberNegative == 1)
Scanner scan = new Scanner(System.in);
System.out.println("Type the first number:");
String x = scan.nextLine();
System.out.println("Type the second number:");
String y = scan.nextLine();
// hold onto which numbers are negative
Integer isFirstNumberNegative = x.charAt(0) == '-' ? 1 : 0;
Integer isSecondNumberNegative = y.charAt(0) == '-' ? 1 : 0;
// strip the negative symbols from the numbers which are negative
if (isFirstNumberNegative > 0) {
x = x.substring(1);
}
if (isSecondNumberNegative > 0) {
y = y.substring(1);
}
String s1 = new StringBuffer(x).reverse().toString();
String s2 = new StringBuffer(y).reverse().toString();
int[] m = new int[s1.length() + s2.length()];
for (int i=0; i<s1.length(); i++) {
for (int j=0; j<s2.length(); j++) {
m[i+j] = m[i+j] + (s1.charAt(i) - '0') * (s2.charAt(j) - '0');
}
}
String product = new String();
for (int i=0; i<m.length; i++) {
int digit = m[i] % 10;
int carry = m[i] / 10;
if (i+1 < m.length) {
m[i+1] = m[i+1] + carry;
}
product = digit + product;
}
while (product.length() > 1 && product.charAt(0) == '0') {
product = product.substring(1);
}
// if only one number is negative put a negative symbol in front
// if both numbers are negative this condition won't hold true because it will be == 2
// if both numbers are positive this condition won't hold true because it wil be == 0
if (isFirstNumberNegative + isSecondNumberNegative == 1) {
product = new StringBuffer(product).insert(0, '-').toString();
}
System.out.println("The multiplication of\n" + x + " \nand\n" + y + " " + "\nis\n" + product);
scan.close();
Just remove the symbols from the numbers and save them. Then later, use them to determine if a negative is required. An exclusive or test for - is all that is necessary for a negative result.
You can create a record (or a class) to return the numbers and resulting sign, ready for processing.
record Numb(String sign,String num1, String num2) {}
String n1 = "-2123";
String n2 = "+2343";
Numb n = prepNums(n1,n2);
System.out.println(n.sign + ", " + n.num1 + " " + n.num);
Prints
-, 2123, 2343
After multiplying, just prepend the sign to the result. Note that the default positive sign is no sign.
And here is the method that processes the strings and returns
them and the resultant sign for multiplication.
public static Numb prepNums(String n1, String n2) {
boolean sign1 = false;
boolean sign2 = false;
char firstChar = n1.charAt(0);
if (!Character.isDigit(firstChar)) {
sign1 = firstChar == '-';
n1 = n1.substring(1); // remove sign
}
firstChar = n2.charAt(0);
if (!Character.isDigit(firstChar)) {
sign2 = firstChar == '-';
n2 = n2.substring(1); // remove sign
}
return new Numb( (sign1 ^ sign2) ? "-" : "", n1, n2);
}
just speaking in a generic concept sense - the square root of largest safe unsigned int,
4^3^3/2-1
is approx 94906265.6242. So right off the bat you know you don't have 8-full decimal digits width to work with unless you add in special tricks.
All those fancy algorithms they talk about - they frequently waste your time by having to first convert from decimal to binary, do the math, then re-convert it back out.
I just split mine into chunks of 7-digits wide, so the the maximum multiply result per op is capped at just shy of 10^14
- for 7 9's squaring each other, approx. 46.50699304-binary bits
- for 8 9's squaring ………. is approx. 53.15084949 bits
for whatever slowness one might believe in simpleton grade school multiply, you more than gain back the savings by avoiding a bidirectional base-conversion.
I am currently working on a project for college which requires you to create a basic shopping menu. I am currently totaling my math by multiplying quantity of items by cost, but the total stays at zero. I created separate integers that store the cost of the item(ex: int hat = 32) and separate integers for quantity.( ex: quanHat = 0). For some reason, the quantity of items stays at zero even though I added a ++. anyone help me with this?
I have tried converting the integer to a string and back, but it does not seem to do anything.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Pirate Trading Post v3");
System.out.println("----------------------");
int eight = 8;
int hat = 32;
int patch = 2;
int sword = 20;
int map = 100;
int shirt = 150;
int test = -1;
int quanEight = 0;
int quanHat = 0;
int quanPatch = 0;
int quanSword = 0;
int quanMap = 0;
int quanShirt = 0;
int total = ( quanEight * eight) + ( quanHat * hat) + ( quanPatch * patch) + ( quanSword * sword) + ( quanShirt * shirt) + ( quanMap * map);
while (test != 0){
System.out.println("Enter Item Code, ? or Q: ");
String code = input.next();
char ch = code.charAt(0);
ch = Character.toUpperCase(ch);
if (ch == '?'){
System.out.println("Valid Item codes are: 8 I H M S T.");
System.out.println("Q to quit.");
}
else if (ch == 'Q'){
test++;
System.out.println("Pirate Trading Post");
System.out.println(quanEight + " Genuine Piece Of Eight " + quanHat + " Pirate Hat " + quanPatch + " Eye Patch " + quanSword + " Sword " + quanMap + " Treasure Map " + quanShirt + " T-Shirt ");
System.out.println("Total: " + total + " bits");
}
else if (ch == '8'){
quanEight ++;
}
else if (ch == 'I'){
quanHat++;
}
else if (ch == 'H'){
quanPatch++;
}
else if (ch == 'M'){
quanSword++;
}
else if (ch == 'S'){
quanMap++;
}
else if (ch == 'T'){
quanShirt++;
}
}
The expected output should be cost of item multiplied by quantity, but the quantity will not store the value. I am thinking the value is not stored because it is a string, but I am not sure.
When the code calculated total , quanHat was 0. And so total was assigned the value 0.
During the while loop when quanHat is incremented, its value increments by 1.
But since total is not being updated or recalculated, it still shows 0.
you need to recalculate total in the if block of else if (ch == 'Q')
I need to make this java code repeat based on the user input, and I cannot make it repeat using the code that I do have so far. I am not supposed to use any other imports besides the scanner and use class main. This is because we are using the https://repl.it/languages/java10 as our compiler because we are an elementary class. When I run the code, it is supposed to ask ten random addition and subtraction and should ask if the user wants to continue or not. When entering 1 for continue, it should ask another ten questions. however, upon running this code, it stops after the first question.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println("Answer the following questions.");
Scanner in = new Scanner(System.in);
int A = 0;
int N = 10;
int n = 0;
int H = 0;
boolean p = true;
while (p){
int R1 = (int)(Math.random() * 50 + 1);
int R2 = (int)(Math.random() * 999 + 1);
int R3 = (int)(Math.random() * 999 + 1);
if(R1>25){
System.out.println( "" + R2 + " + " + R3);
A = in.nextInt();
if (A == (R2 + R3))
System.out.println("Correct");
else
System.out.println("Incorrect");
}
if(R1<25){
System.out.println( "" + R2 + " - " + R3);
A = in.nextInt();
if (A == (R2 - R3))
System.out.println("Correct");
else
System.out.println("Incorrect");}
N--;
if (N==0)
p = false;
continue;
}System.out.println("Do you want ot continue? Put 1 for yes, 2 for no.");
H = in.nextInt();
if (H==1)
p=true;
else
p=false;
while (N>0);
}
}
That's why you put the question System.out.println("Do you want ot continue? Put 1 for yes, 2 for no."); out of the while.
I recommend use do while instead of while. So you just need to put the question inside of loop do while.
System.out.println("Answer the following questions.");
Scanner in = new Scanner(System.in);
int A = 0;
int N = 10;
int H = 0;
boolean p = true;
do{
int R1 = (int) (Math.random() * 50 + 1);
int R2 = (int) (Math.random() * 999 + 1);
int R3 = (int) (Math.random() * 999 + 1);
if (R1 > 25) {
System.out.println("" + R2 + " + " + R3);
A = in.nextInt();
if (A == (R2 + R3)) {
System.out.println("Correct");
} else {
System.out.println("Incorrect");
}
}
if (R1 < 25) {
System.out.println("" + R2 + " - " + R3);
A = in.nextInt();
if (A == (R2 - R3)) {
System.out.println("Correct");
} else {
System.out.println("Incorrect");
}
}
N--;
System.out.println("Do you want ot continue? Put 1 for yes, 2 for no.");
H = in.nextInt();
if (H == 1) {
p = true;
} else {
p = false;
}
if (N == 0) {
p = false;
System.out.println("You have reached your max attempts.")
}
}while (N > 0 && p);
I need help to display my hundred and teens number in words. For example if I enter 116. My program will output One hundred and Six, instead of One hundred and sixteen. All the other numbers that I input work except for the teens numbers.
I would change 4 things in your code:
First:
Use int instead of double for your input
int numInput = Integer.parseInt(br.readLine());//user inputs number
Second:
In order to get the appropriate digit placements in int use:
int hundredsDigit = (numInput % 1000) / 100;
int tensDigit = (numInput % 100) / 10;
int onesDigit = numInput % 10;
instead of:
double hundredsDigit=Math.floor((numInput%1000)/100);
double tensDigit = Math.floor((numInput % 100) / 10);
double onesDigit = numInput % 10;
Third:
The else condition for the 110-119 range must be before the 100-999 (which technically should be 120-999)
Fourth:
Your teens method is taking the original numInput as parameter.
What you need to take is the onesDigit to determine which "teen" it is
So it should be a call like:
teens(onesDigit);
This call must be changed in the [10-19] condition and the [110-119] condition
And your teens new method should look like:
public static void teens(int onesDigit) {
if (onesDigit == 0) {
System.out.print("Ten ");
}
if (onesDigit == 1) {
System.out.print("Eleven ");
}
if (onesDigit == 2) {
System.out.print("Twelve ");
}
if (onesDigit == 3) {
System.out.print("Thirteen ");
}
if (onesDigit == 4) {
System.out.print("Fourteen ");
}
if (onesDigit == 5) {
System.out.print("Fifteen ");
}
if (onesDigit == 6) {
System.out.print("Sixteen ");
}
if (onesDigit == 7) {
System.out.print("Seventeen ");
}
if (onesDigit == 8) {
System.out.print("Eighteen ");
}
if (onesDigit == 9) {
System.out.print("Nineteen ");
}
}//closes teens method
That happens because you check if the number is in the range [100, 999] before checking that it is in the range [100, 119], change the order of the ifs and it will work just fine.
Start from smallest number to highest when comparing.
First condition:
if((numInput>=10)&&(numInput<=19)){
Second:
else if((numInput>=20)&&(numInput<=99)){
Third:
else if((numInput>100)&&(numInput<=119)){
Fourth:
else if((numInput>=100)&&(numInput<=999)){
You should put the
else if((numInput>100)&&(numInput<=119))
clause before the more inclusive
else if((numInput>=100)&&(numInput<=999))
What's happening here is that the larger range is searched first, and your tens function doesn't output anything for 1.
Your else if
else if((numInput>100)&&(numInput<=119)){
hundreds(hundredsDigit);
System.out.print(" ");
teens(numInput);
}
must be placed one level higher... Since the
else if((numInput>=100)&&(numInput<=999)){
hundreds(hundredsDigit);
System.out.print(" ");
tens(tensDigit);
System.out.print(" ");
ones(onesDigit);
}
will also fulfill the condition, the "116" you entered will never get there...
Just in case you wan't this, I did not write this:
public static String intToText(int n) {
if (n < 0)
return "Minus " + intToText(-n);
else if (n == 0)
return "Zero";
else if (n <= 19)
return oneToNineteen[n - 1] + " ";
else if (n <= 99)
return twentyToNinety[n / 10 - 2] + " " + intToText(n % 10);
else if (n <= 199)
return "One Hundred " + intToText(n % 100);
else if (n <= 999)
return intToText(n / 100) + "Hundred " + intToText(n % 100);
else if (n <= 1999)
return "One Thousand " + intToText(n % 1000);
else if (n <= 999999)
return intToText(n / 1000) + "Thousand " + intToText(n % 1000);
else if (n <= 1999999)
return "One Million " + intToText(n % 1000000);
else if (n <= 999999999)
return intToText(n / 1000000) + "Million " + intToText(n % 1000000);
else if (n <= 1999999999)
return "One Billion " + intToText(n % 1000000000);
else
return intToText(n / 1000000000) + "Billion " + intToText(n % 1000000000);
}
This was fun. It has the following issues:
-Only deals with integers. No longs, doubles etc.
-Doesn't deal with the single case of zero.
-Fails at Integer.MIN_VALUE because of the number = number * -1
Otherwise, it seems to work. The motivation was that I can't stand huge blocks of "if-else" code.
public class NumbersToWords {
private static final Map<Integer,String> NUM_TO_WORD = new HashMap<Integer, String>();
private static final List<Integer> KEYS = new ArrayList<Integer>(30);
static {
NUM_TO_WORD.put(0,"zero");
NUM_TO_WORD.put(1,"one");
NUM_TO_WORD.put(2,"two");
NUM_TO_WORD.put(3,"three");
NUM_TO_WORD.put(4,"four");
NUM_TO_WORD.put(5,"five");
NUM_TO_WORD.put(6,"six");
NUM_TO_WORD.put(7,"seven");
NUM_TO_WORD.put(8,"eight");
NUM_TO_WORD.put(9,"nine");
NUM_TO_WORD.put(10,"ten");
NUM_TO_WORD.put(11,"eleven");
NUM_TO_WORD.put(12,"twelve");
NUM_TO_WORD.put(13,"thirteen");
NUM_TO_WORD.put(14,"fourteen");
NUM_TO_WORD.put(15,"fifteen");
NUM_TO_WORD.put(16,"sixteen");
NUM_TO_WORD.put(17,"seventeen");
NUM_TO_WORD.put(18,"eighteen");
NUM_TO_WORD.put(19,"nineteen");
NUM_TO_WORD.put(20,"twenty");
NUM_TO_WORD.put(30,"thirty");
NUM_TO_WORD.put(40,"forty");
NUM_TO_WORD.put(50,"fifty");
NUM_TO_WORD.put(60,"sixty");
NUM_TO_WORD.put(70,"seventy");
NUM_TO_WORD.put(80,"eighty");
NUM_TO_WORD.put(90,"ninety");
NUM_TO_WORD.put(100,"hundred");
NUM_TO_WORD.put(1000,"thousand");
NUM_TO_WORD.put(1000000,"million");
NUM_TO_WORD.put(1000000000,"billion");
KEYS.addAll(NUM_TO_WORD.keySet());
Collections.sort(KEYS);
}
public static void main(String[] args){
int[] testValues = {24,4,543755,12,10000,123000,123,Integer.MAX_VALUE, -456};
NumbersToWords ntw = new NumbersToWords();
for(int i : testValues){
System.out.println(i + " -> " + ntw.getWords(i));
}
}
/* called recursively */
public String getWords(int number){
boolean isNegative = number < 0;
if(isNegative){
number = number * -1;
}
if(number < 100){
return getWordLessThanHundred(number);
}
StringBuilder words = new StringBuilder(50);
int key = getKey(number);
if(isNegative){
words.append("negative ");
}
words.append(getWords(number/key))
.append(" ").append(NUM_TO_WORD.get(key)) // get the largest placeholder word
.append(" ").append(getWords(number % key)); // get the rest
return words.toString();
}
private String getWordLessThanHundred(int number){
if(number == 0){
return "";
}
if(number < 21){
return NUM_TO_WORD.get(number);
}
int key = getKey(number);
return NUM_TO_WORD.get(key) + " " + NUM_TO_WORD.get(number - key);
}
private int getKey(int number){
for(int i = 0; i<KEYS.size();i++){
int value = KEYS.get(i);
if(i > 0 && number < value){
return KEYS.get(i - 1);
}else if(number == value){
return value;
}
}
return KEYS.get(KEYS.size() - 1);
}
}