I'm having a task to solve in which I have to find the biggest sum between the digits of 3nums integer.
I've decided to do it with "switch case", because I am still a newbie.
But, unfortunately when I run it, it skips directly out after the loop.
Here's my code:
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
int nums = Integer.parseInt(input);
int firstNum, secondNum, thirdNum, sumNums, sumNums2 = 0;
firstNum = Character.getNumericValue(input.charAt(0));
secondNum = Character.getNumericValue(input.charAt(1));
thirdNum = Character.getNumericValue(input.charAt(2));
switch (nums) {
case 1:
sumNums = firstNum + secondNum + thirdNum;
sumNums2 = sumNums;
case 2:
sumNums = firstNum + secondNum * thirdNum;
if (sumNums > sumNums2) {
sumNums2 = sumNums;
}
case 3:
sumNums = firstNum * secondNum + thirdNum;
if (sumNums > sumNums2) {
sumNums2 = sumNums;
}
case 4:
sumNums = firstNum * thirdNum + secondNum;
if (sumNums > sumNums2) {
sumNums2 = sumNums;
}
case 5:
sumNums = firstNum * secondNum * thirdNum;
if (sumNums > sumNums2) {
sumNums2 = sumNums;
break;
}
}
System.out.println(sumNums2);
}
}
Thanks in advance!
The issue is that you are switching on the variable nums, which you are expecting a 3 digit number. Any 3 digit number entered will not match any of your single digit case statements, so it falls out of the switch all together.
It appears that you are intending to have the user first input a singer digit number 1 thru 5 representing an operation to match one of the cases - you never do that.
Also, you should first print out via a System.out.println() statement what input you are asking for before scanning for input.
The code looks odd:
switch (nums) { // 111, 257 wrong input, no match
// suggest to add default, so you can debug the problem
}
Related
My calculator, that I needed to make for my test task to apply for a Java course, is working great. But there's an issue I would like to resolve. If you type in, for example, "5+3" as opposed to "5 + 3", it doesn't work. Can my calculator be smart enough to delimit input without explicit delimiters (like spaces)?
In other words, how do I make my scanner split, for example, an input of 5+32 *2 into five tokens: 5, +, 32, *, and 2? If I don't have to overhaul my entire code, that would be even better!
import java.util.Scanner;
import java.io.IOException;
import java.text.DecimalFormat;
public class Introduction {
private static double firstNum;
private static double secondNum;
private static double result;
private static boolean dontKnow;
private static String firstNumS;
private static String secondNumS;
private static String operationS;
private static final DecimalFormat df = new DecimalFormat("#.##");
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
firstNumS = scanner.next();
operationS = scanner.next();
secondNumS = scanner.next();
if(firstNumS.compareTo(operationS) > 15){
switch(firstNumS){
case "I":
firstNum = 1;
break;
case "II":
firstNum = 2;
break;
case "III":
firstNum = 3;
break;
case "IV":
firstNum = 4;
break;
case "V":
firstNum = 5;
break;
case "VI":
firstNum = 6;
break;
case "VII":
firstNum = 7;
break;
case "VIII":
firstNum = 8;
break;
case "IX":
firstNum = 9;
break;
case "X":
firstNum = 10;
break;
default:
System.out.println("I don't know the first number!");
dontKnow = true; }}
else {
firstNum = Integer.decode(firstNumS);
if(firstNum > 10){
System.out.println("It appears, the first number is too big for me!");
dontKnow = true;
}
}
if(secondNumS.compareTo(operationS) > 15) {
switch(secondNumS){
case "I":
secondNum = 1;
break;
case "II":
secondNum = 2;
break;
case "III":
secondNum = 3;
break;
case "IV":
secondNum = 4;
break;
case "V":
secondNum = 5;
break;
case "VI":
secondNum = 6;
break;
case "VII":
secondNum = 7;
break;
case "VIII":
secondNum = 8;
break;
case "IX":
secondNum = 9;
break;
case "X":
secondNum = 10;
break;
default:
System.out.println("I don't know the second number!");
dontKnow = true; }}
else {
secondNum = Integer.decode(secondNumS);
if(secondNum > 10) {
System.out.println("It appears, the second number is too big for me!");
dontKnow = true; }}
if(operationS.equals("+")) {
result = firstNum + secondNum; }
else if(operationS.equals("-")) {
result = firstNum - secondNum; }
else if(operationS.equals("*")){
result = firstNum * secondNum; }
else if(operationS.equals("/")){
result = firstNum / secondNum; }
else {
System.out.println("I don't know such an operation!");
dontKnow = true; }
if(!(operationS.equals("/") && secondNum == 0)) {
if(!dontKnow) {
if(result / (int)result != 1) {
if(String.valueOf(result).equals(df.format(result))) {
System.out.println("It's " + result + "!"); }
else {
System.out.println("It's approximately " + df.format(result) + "!"); }}
else {
System.out.println("It's " + (int)result + "!"); }}}
else {
if(!dontKnow) {
System.out.println("Gosh! I tried to divide it by zero, as you requested, but my virtual head nearly exploded! I need to recover..."); }
else {
System.out.println("Besides, you can't even divide by zero, I'm so told!"); }}
}
}
Assuming you're using scanner, yes, it could. The scanner operates on the notion that a regexp serves as delimiter: Each match of the regex delimits, and whatever the regexp matches is tossed out (because nobody 'cares' about reading the spaces or the commas or whatever). The scanner then gives you stuff in between the delimiters.
Thus, for you to end up with scanner stream '5', '+', and '3', you want a delimiter that delimits on the space between '5' / '+' and '+' / '3', whilst matching 0 characters otherwise those would be thrown out.
You can do that, using regexp lookahead/lookbehind. You want a digit to the left and an operator to the right, or vice versa:
String test = "53 + 2*35- 8";
Scanner s = new Scanner(test);
s.useDelimiter("\\s+|(?:(?<=\\d)(?=[-+/*]))|(?:(?=\\d)(?<=[-+/*]))");
while (s.hasNext()) {
System.out.println("NEXT: '" + s.next() + "'");
}
To break that convoluted regex open:
A|B|C means: A or B or C. That's the 'outermost' part of this regexp, we're looking for one of 3 distinct things to split on.
\\s+ means: 1 or more whitespace characters. Thus, input "5 20" would be split into 5 and 20. The whitespace is consumed (i.e. tossed out and not part of your tokens).
OR, positive lookbehind ((?<=X) means: Match if, looking backwards, you would see X), and X is \\d here - a digit. We then also have a positive lookahead: (?=X) means: Check for X being here, but don't consume it (or it would be thrown out, remember, the regex describes the delimiter, and the delimiter is thrown out). We look ahead for one of the symbols.
OR, that, but flipped about (first an operator, then a digit).
NB: If you want to avoid the complexity of a regexp, you could just loop through each character, but you'd be building a little state machine, and have to take care of consecutive, non-space separated digits: You need to combine those (10 + 20 is not 1, 0, +, 2, 0 - it's 10 + 20).
NB2: If you also want to support ( and ) you can edit the regex appropriately (They are, essentially, 'operators' and go in the list of operators), however, at some point you're essentially descriving a grammar for a formal language and should start looking into a parser generator. But that's all vastly more complicated than any of this.
first time posting here and I'd like some help , I started learning java some days ago and I tried to make a very simple calculator. Here is the code :
import java.util.Scanner;
public class Calc {
public static void main(String[] args) {
while (true) {
Scanner input = new Scanner(System.in);
double input1, input2;
System.out.println("Type your calculation below");
input1 = input.nextDouble();
String operator = input.next();
input2 = input.nextDouble();
switch (operator) {
case "+":
System.out.println(input1 + input2);
break;
case "-":
System.out.println(input1 - input2);
break;
case "*":
System.out.println(input1 * input2);
break;
case "/":
System.out.println(input1 / input2);
break;
}
}
}
}
When I run this I have to type a number press space and then type the other number like this : 15 + 15. Can I somehow make it so that I don't have to press space every time? So I can type it like this : 15+15.
Also if you have any tips or if you see any mistakes I'd be happy to hear your opinion.
I would recommend using the delimiter for Scanner see below:
Scanner s = new Scanner(foo);
s.useDelimiter(" ");
// do input stuff here
I am trying to write a Decimal & Binary converter in Java. I am trying to use try & catch option for error handling. Such as, if any one input "a" as binary number, it will print "Wrong Input". I have used parse and try-catch for this function. But it is not working. I am trying to find out the problem, but I am failed to find it. Could anyone help me in this code? When I write "1" for binary to decimal conversion, it goes to the end of the code.
The whole code is here:
package binary.with.decimal;
import java.util.Scanner;
public class RiaJava {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int binaryp = 0;
int n;
int base = 2;
int result = 0;
int multiplier = 1;
System.out.println("1.Binary to Decimal \n 2.Decimal to Binary");
System.out.println("Enter Your Option Number:");
n = scan.nextInt();
switch (n) {
case 1:
System.out.println("Input Binary Number:");
String binary = scan.nextLine();
scan.close();
try {
binaryp = Integer.parseInt(binary);
}
catch (NumberFormatException e) {
System.out.println("Wrong Input!!!");
}
while (binaryp > 0) {
int residue = binaryp % base;
binaryp = binaryp / base;
result = result + residue * multiplier;
multiplier = multiplier * 10;
}
System.out.println("Decimal....." + result);
break;
case 2:
System.out.println("Input Decimal Number:");
int decimal = scan.nextInt();
scan.close();
while (decimal > 0) {
int residue = decimal % base;
decimal = decimal / base;
result = result + residue * multiplier;
multiplier = multiplier * 10;
}
System.out.println("Binary....." + result);
break;
default:
System.out.println("you have selected wrong option number");
break;
}
}
}
scan.nextLine() should be scan.next()
nextLine() doesn't wait for user input, but reads the remaining buffer until the next end of line.
i need to make a switch statement that can use the appropriate conversion method. here is my code
public class ExerciseTwo
{
public static void main (Strings[] args)
{
Scanner input = new scanner(system.in);
String[] binary = { "0","1","2","3","4","5","6","7","8"};
for (c = 0; c < array.length; counter++)
binary[] = input.nextInt();
System.out.println("Enter number between 0 and 8");
number = input.nextInt();
system.out.printf("the number", "number_given", "is", "binaryVersion", "binary");
}
}
I'm sorry, but the description wasn't very clear to me. Are you simply trying to convert the input value (between 0 and 8) into a binary format (as in 2 -> 10, 7 -> 111) using a switch statement? If so, this code will work. If not, can you clarify the question for me?
Thanks!
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number between 0 and 8");
int number = input.nextInt();
int binaryRepresentation = -1;
switch (number)
{
case 0:
binaryRepresentation = 0;
break;
case 1:
binaryRepresentation = 1;
break;
case 2:
binaryRepresentation = 10;
break;
case 3:
binaryRepresentation = 11;
break;
case 4:
binaryRepresentation = 100;
break;
case 5:
binaryRepresentation = 101;
break;
case 6:
binaryRepresentation = 110;
break;
case 7:
binaryRepresentation = 111;
break;
case 8:
binaryRepresentation = 1000;
break;
}
System.out.printf("the number " + number + " is " + binaryRepresentation + " in binary (-1 means invalid input)");
}
Do your home work yourself , Look at the http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html switch case definition. If you really want good solution for binary representation then look at API documentation of the Integer class
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html?is-external=true
Using the API doc is one of the first things you need to learn as a Java programmer.
I am having trouble understanding a calculation within my code. I have done one method for addition in this mini calculator I am making. This is purely to practice methods. I created the first method for addition and for some reason when I select the option to add two numbers together and the program goes in to the method and returns an answer it does a multiplication instead of an addition.
The code is below for the whole program:
import java.util.Scanner;
public class Testing {
/**
* #param args
*/
public static void main(String[] args) {
Scanner userReader = new Scanner(System.in);
int number1;
int number2;
int decision;
int result = 0;
System.out.println("Please input your first number");
number1 = userReader.nextInt();
System.out.println("Please input your second number");
number2 = userReader.nextInt();
System.out.println("Please select what you would like to do");
System.out.println("1.Addition");
System.out.println("2.Subtraction");
System.out.println("3.Division");
System.out.println("4.Multiplication");
decision = userReader.nextInt();
switch(decision)
{
case 1 : result = Addition(number1,number2);
case 2 : result = number1 - number2;
case 3 : result = number1 / number2;
case 4 : result = number1 * number2;
}
System.out.println("Your answer is " + result);
}
public static int Addition(int number1, int number2) {
int Additionresult;
Additionresult = number1 + number2;
return Additionresult;
}
}
Best Regards
In addition, it is good practice to add a default so that if the user enters a number other than 1, 2, 3, or 4 you can let the user know they have entered an invalid option.
Example:
switch (decision)
{
case 1:
....;
break;
case 2:
....;
break;
case 3:
....;
break;
case 4:
....;
break;
default:
System.out.println("Invalid option");
break;
}
You forgot the break after each case.