can't seem to find the syntax mistake in this switch statement. Any help is much appreciated.
Source code:
import java.util.Scanner;
public class SwitchCasing {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
try {
int number = Integer.parseInt(input);
switch(number) {
case 1:
if(number < 0) {
System.out.println("Number is smaller than 0.");
break;
}
case 2:
if(number > 0){
System.out.println("Number is greater than 0.");
break;
}
default:
System.out.println("Number is 0.");
}
} catch(IllegalArgumentException e) {
System.out.println("Please insert a valid number.");
}
sc.close();
}
}
The output is always "Number is 0", no matter what value is entered.
Thanks!
Those case labels aren't for you labeling purposes; they are for Java to compare number so it can execute the case.
It will start execution at the block for case 1: if number is 1. Because 1 isn't less than 0, that block won't produce any output.
It will start execution at the block for case 2: if number is 2. Because 1 isn't less than 0, that block will produce the output "Number is greater than 0.".
Any other number will go to the default case and produce the output "Number is 0.", even though your output is incorrect.
You can't test cases that way with a switch statement. Change it to the equivalent if/else construct.
if(number < 0){
System.out.println("Number is smaller than 0.");
}
else if(number > 0){
System.out.println("Number is greater than 0.");
}
else {
System.out.println("Number is 0.");
}
case 1: means that number equals 1. But since 1 is not less than 0 you'll never see "Number is smaller than 0.", and you won't break. (The break is inside the if (number < 0) part).
case 2: means that number equals 2. You'll enter this case if you enter a 2.
That leaves default for all other values you might enter, which I'm guessing are most of them.
You really don't want a switch in this situation. You should be using an if-else construct, like this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
try{
int number = Integer.parseInt(input);
if(number < 0) {
System.out.println("Number is smaller than 0.");
} else if(number > 0) {
System.out.println("Number is greater than 0.");
} else {
System.out.println("Number is 0.");
}
} catch(IllegalArgumentException e) {
System.out.println("Please insert a valid number.");
} finally {
sc.close();
}
}
As first, do you know you can do int number = sc.nextInt(); you do not need to parse the input and it assures that the user gives you a int.
As for your switch case your break; are inside if statements so when the code reads break it breaks our of the loop containing it. In your case it breaks out of the if/else statement not the switch case.
Hope I could help!
Related
This Code works properly for numbers upto 4 but then prints wrong or sometimes both, "Number is Prime" and "not Prime".
package timepass;
import java.util.Scanner;
public class Timepass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the no :");
int n = sc.nextInt();
if (n==1 || n==0) {
System.out.println("It is not a prime no");
}
else if (n > 1) {
for(int i = 2; i<n; i++) {
if (n % i ==0) {
System.out.println("It is not a prime number");
break;
} else {
System.out.println("It is a prime number");
}
}
}
}
}
There is slight mistake in the logic.
You have to check all the integers from 2 to n-1, if they are factors of n and then make the final verdict.
Have a look at the following implementation:
import java.util.Scanner;
public class Timepass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the no :");
int n = sc.nextInt();
if (n==1 || n==0) {
System.out.println("It is not a prime no");
}
else if (n > 1) {
boolean isPrime = true;
for(int i = 2; i<n; i++) {
if (n % i ==0) {
isPrime = false;
break;
}
}
if(isPrime) {
System.out.println("It is a prime number");
}else{
System.out.println("It is not a prime number");
}
}
}
}
PS: Also search for more efficient logics to check if the number is prime. For example: In the above code, their is no need to iterate from 2 until n-1. You can stop at n/2.
I see the problem.
Hint: a number is prime if there are no factors. Your code is printing "prime" when >>a<< number is not a factor.
Look at the example 5 and your loop.
2: not a factor, print "It is a prime number"
3: not a factor, print "It is a prime number"
4: not a factor, print "It is a prime number"
When can you as a human tell that it is a prime number? Surely not already at 2.
(Actually you can at 3, but your loop condition is inefficient....)
So why do you print already? You should not.
Look at 9:
2: not a factor, print "It is a prime number"
3: is a factor, print "It is not a prime number"; break, stop looping
Again, at 2 you do not know yet but print anyway; at three you know and stop.
The solution is to print in all cases only when leaving the loop. You do so correctly before the break for "not prime". But you print several times for "prime", possibly wrongly and possibly later again for "not prime".
The point to print "prime" is after going through all of the loop without finding a factor.
Make sure that you do not do that printing after leaving the loop with break for "not prime". You can do so by introducing a function which does the prime check and returns a value indicating the result. That function can return where you currently break and after the loop. Then print the result text from the calling code, based on the return value.
You should be using a flag variable in order to check the number whether it is prime or not. The problem with your case is that everytime it check if the number is divisible by i and if this condition becomes false then it goes to the else condition and prints 'not prime' and this is wrong the program should wait for the loop to end and then it should print any result.
So use a flag variable, initialize it false and if the number is divisible by any value of i then make the value of flag true and break out of loop.
After the loop check for flag variable and if the variable is true print not prime else prime .
//you can use flag instead of printing the massage inside the for loop
// if flag is true means the number is not a prime number
boolean flag = false;
for(int i =2; i< n; i++){
if(n % i ==0){
flag = true;
break;
}
}
if (flag) {
System.out.println("It is not a prime number");
} else {
System.out.println("It is a prime number");
}
import java.util.Scanner;
class Timepass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the no :");
int n = sc.nextInt();
if (n==1 || n==0) {
System.out.println("It is not a prime no");
}
else if (n > 1) {
for(int i = 2; i<n; i++) {
if (n % i ==0) {
System.out.println("It is not a prime number");
break;
} else {
System.out.println("It is a prime number");
break;
}
}
}
}
}
I need to write code that asks you to guess a number between 1 and 10 and uses a loop. It has to use the System.in.read() method to take user input. The correct number is 7, and when you guess that it ends. If you guess wrong it tells you to try again. I don't know why my code isn't working right, so I could use some help. The output I get is weird, no matter what number I enter it just says:
Hello! Enter a number between 1 and 10:
(entered number ex. 4)
Your guess is too high
Hello! Enter a number between 1 and 10:
Your guess is too high
Hello! Enter a number between 1 and 10:
I am new to programming so sorry if it isn't indented right or the solution is obvious.
public static void main(String[] args) throws java.io.IOException {
int input;
boolean play = true;
while (play == true) {
System.out.println("Hello! Enter a number between 1 and 10: ");
input = System.in.read();
if (input > 7) {
System.out.println("Your guess is too high");
} else if (input < 7) {
System.out.println("Your guess is too low");
} else if (input == 7) {
System.out.println("Correct! the correct number was: 7");
}
}
}
It should give you a specific result depending on the number, like if it is too high or low, then you can try again and enter a new number until you get the correct answer of 7. If the number isn't 1-10 you should get an error message. Thanks.
You're not changing the play variable, so there is no goin out of the while loop. You would have to change it like this:
else if (input == 7) {
System.out.println("Correct! the correct number was: 7");
play = false;
}
Also you might want to move this line: System.out.println("Hello! Enter a number between 1 and 10: "); before while loop.
This might solve your problem.
public static void main(String[] args) {
int input;
boolean play = true;
Scanner inputNumber = new Scanner(System.in);
while (play) {
System.out.println("Hello! Enter a number between 1 and 10: ");
input = inputNumber.nextInt();
if (input > 7) {
System.out.println("Your guess is too high");
} else if (input < 7) {
System.out.println("Your guess is too low");
} else if (input == 7) {
System.out.println("Correct! the correct number was: 7");
play = false;
}
}
}
I am struggling to correctly loop the code I have written to convert integers to roman numerals.
I have tried implementing a do while loop to run the code starting at "please enter an integer" and ending after my switch statement with the while part being: while(case "y" || "Y" == true )
Any help would be greatly appreciated. I have been searching through previous posts on stack overflow for a couple hours now and haven't been able to find anything that helps.
public class project8
{
/**
* Constructor for objects of class Project4
*/
public static void main(String[] args) {
System.out.println("Welcome to my integer Roman numeral conversion program");
System.out.println("------------------------------------------------------");
System.out.println(" ");
Scanner in = new Scanner (System.in);
System.out.print("Enter an integer in the range 1-3999 (both inclusive): ");
int input = in.nextInt();
if (input < 0 || input > 3999){
System.out.println("Sorry, this number is outside the range.");
System.out.println("Do you want to try again? Press Y for yes and N for no: ");
String userInput = in.next();
switch (userInput) {
case "N":
case "n":
System.exit(0);
break;
case "Y":
case "y":
break;
}
}
else if (input > 0 && input < 3999);
{ System.out.println(Conversion.Convert(input));
}
}
}
1) Your if - else if conditions are redundant. You can use a simple if - else as input can only be in that range or not. else if makes only sence if you had two or more ranges to check, e.g.
if(input > 0 && input < 3999){
...
}
else if (input > 4000 && input < 8000){
...
}
else {
...
}
2) You don't need a switch block instead use the user input in your while condition as you want to continue looping when user input is Y/y, i.e while(userChoice.equals("Y"))
3) Use a do - while loop as you want that your application to run at least on time
public static void main(String[] args) {
System.out.println("Welcome to my integer Roman numeral conversion program");
System.out.println("------------------------------------------------------");
System.out.println(" ");
Scanner in = new Scanner (System.in);
String choice;
do{
System.out.print("Enter an integer in the range 1-3999 (both inclusive): ");
int input = in.nextInt();
if(input > 0 && input < 3999){
System.out.println(Conversion.Convert(input));
}
else{
System.out.println("Sorry, this number is outside the range.");
}
System.out.println("Do you want to try again? Press Y for yes and N for no: ");
choice = in.next();
}while(choice.equals("Y") || choice.equals("y"));
}
I want the program to retry the "try" part of the code every time the input is incorrect and throws an error(which is solved with an exception).
My code looks like this:
try {
System.out.print("Enter a number from 1 to 3: ");
enteredNumber = userInputScanner.nextInt();
makeHumanMove(enteredNumber);
}catch(Exception e){
System.out.println("Incorrect input!");
My "makeHumanMove" function checks, if the number is from 1 to 3.. But if the user inserts a letter, it would throw an error and if it happens, I want the program to ask for another input until the user inserts a correct input.
I've tried while and for loops but I keep messing up. Any ideas?
How's about this code:
while (true) {
try {
System.out.print("Enter a number from 1 to 3: ");
enteredNumber = userInputScanner.nextInt();
makeHumanMove(enteredNumber);
break;
}catch(Exception e){
System.out.println("Incorrect input!");
}
}
Make sure that your makeHumanMove(enteredNumber); throws new Exception();
boolean inputIsCorrect = false;
while(inputIsCorrect == false){
try {
System.out.print("Enter a number from 1 to 3: ");
enteredNumber = userInputScanner.nextInt();
makeHumanMove(enteredNumber);
inputIsCorrect = true;
}catch(Exception e){
System.out.println("Incorrect input!");
}
}
This, of course, assumes that your makeHumanMove method throws an exception.
If I was doing this, I don't think I would be using exceptions. My code would be more like ...
boolean inputIsCorrect = false;
while(inputIsCorrect == false){
System.out.print("Enter a number from 1 to 3: ");
enteredNumber = userInputScanner.nextInt();
inputIsCorrect = makeHumanMove(enteredNumber);
}
I'd change the makeHumanMove return a value that indicates whether the the inout is valid or not, rather than using exceptions. ( Can't remember if scanner.nextInt() throws exception .... )
Use a boolean value outside, set it to true at the end of the try block. Then you can test for it using a while loop.
int enteredNumber;
boolean correctNumber = false;
while (!correctNumber) {
try {
System.out.print("Enter a number from 1 to 3: ");
enteredNumber = userInputScanner.nextInt();
makeHumanMove(enteredNumber);
correctNumber = true;
}catch(Exception e){
System.out.println("Incorrect input!");
}
}
Note that you should not use exceptions at all to report incorrect input. You should test for incorrect input and abort early. You should also consider if makeHumanMove should actually be part of the try/catch block; input validation should not be part of the business logic of your application.
final int number;
System.out.print("Enter a number from 1 to 3: ");
while (true) {
int enteredNumber;
try {
enteredNumber = userInputScanner.nextInt();
} catch (Exception e) {
System.out.print("Not a number, enter a number from 1 to 3: ");
userInputScanner = new Scanner(System.in);
continue;
}
if (enteredNumber < 1 || enteredNumber > 3) {
System.out.print("Incorrect number, enter a number from 1 to 3: ");
continue;
} else {
number = enteredNumber;
break;
}
}
makeHumanMove(number);
I'm trying to create a program that reads a list of 10 integers and asks the user whether they'd like to know if the integers entered are even/odd, prime, or their sign.
I don't see where the mistake is:
import java.io.*;
public class Menu1 {
public static void main(String args[])throws IOException{
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
int array[]=new int[10];
int a=0, i=0;
System.out.println("Welcome, please enter 10 integers:");
try{
for(i=0;i<10;i++){
System.out.println("Enter integer "+(i+1)+":");
array[i]=Integer.parseInt(b.readLine());
}
}catch(NumberFormatException e){
System.err.println("Not an integer! "+e.getMessage());
}
System.out.println("What would you like to know?\n(1) Even/Odd\n(2) Primes\n(3) Sign");
try{
a=Integer.parseInt(b.readLine());
}catch(NumberFormatException e){
System.err.println("Not an integer! "+e.getMessage());
}
switch (a){
case 1:
for(i=0;i<10;i++){
if(array[i]%2==0)
System.out.println(array[i]+" is even");
else
System.out.println(array[i]+" is odd");
}
break;
case 2:
for(int j=0;j<10;j++){
for(i=2;i<array[j];i++){
if(array[j]%i==0)
System.out.println(array[j]+" isn't prime");
else
System.out.println(array[j]+" is prime");
}
}
break;
case 3:
for(i=0;i<10;i++){
if(array[i]>0)
System.out.println(array[i]+" is positive");
else if(array[i]<0)
System.out.println(array[i]+" is negative");
else
System.out.println(array[i]+" has no sign");
}
break;
default:
System.out.println("Invalid Option");
}
}
}
case 1 and case 3 work just fine, case 2 is where the strange output occurs; any help will be greatly appreciated
In your code for case 2:
case 2:
for(int j=0;j<10;j++){
for(i=2;i<array[j];i++){
if(array[j]%i==0)
System.out.println(array[j]+" isn't prime");
else
System.out.println(array[j]+" is prime");
}
}
break;
you have put a System.out.println() statement that will execute for every iteration of the for loop. So, if a given element in your array, array, is 5, your code will print out whether or not your number is divisible by every number from 2 to 5. This probably isn't what you want.
To fix this, there are a few options: for one, you could have a boolean flag that you set when you discover that the number isn't prime, and then check that and print your results after the inner for loop:
case 2:
for(int j=0;j<10;j++){
boolean isPrime = true; // assume it's prime
for(i=2;i<array[j];i++){
if(array[j]%i==0)
isPrime = false;
break; // get out of the inner for loop early
}
if(isPrime)
System.out.println(array[j]+" is prime");
else
System.out.println(array[j]+" isn't prime");
}
break;
This is a function to check if a number is prime or not:
public static boolean isPrimeNumber(int number) {
if (number == 2 || number == 3) {
return true;
}
if (number % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (number % i == 0) {
return false;
}
}
return true;
}
You can call this function for every number you want to check.
Your case2 would be like:
case 2:
for(int j=0;j<10;j++){
if(!isPrimeNumber(array[j]))
System.out.println(array[j]+" isn't prime");
else
System.out.println(array[j]+" is prime");
}
break;
For a programming exercise, the answers given will do just fine. If this were a real application, using very large numbers, the algorithm that checks every possible divisor (or even the slight improvements on this) would be very slow.
Although it's possible to test for primality with certainty much more efficiently than this, in practice it's very, very efficient to check that a (very) large number is almost
certainly prime. This is what gets used in cryptographic applications.
For further details, you could look up Miller-Rabin.
If you want an implementation you can use off-the-shelf, then convert your number to a BigInteger and then use BigInteger.isProbablePrime(int certainty) to determine whether it's probably prime. You can make the "probably" very close to certainty and it'll still be extremely efficient.