I'm writing code to let users guess the number. Thay have only two chance to got all
If user put wrong input (Beyond 1-4),
they can do it again. In this case, the user must answer 2 and 4 to get all.
System.out.println("you have only two chance to get all");
int guessnum[] = new int[2];;
for (int i = 0; i < guessnum.length; i++) {
System.out.print((i+1)+" Enter number 1-4 : ");
int num = sc.nextInt();
if (num == 1) {
System.out.println("not here");
}
else if (num == 2) {
System.out.println("wow!! you got it");
}
else if (num == 3) {
System.out.println("not here");
}
else if (num == 4) {
System.out.println("wow!! you got it");
}
else {
System.out.println("number must be 1-4 only, try again");
//how to repeat in same loop
}
}
Use the break statement
else if (num == 2) {
System.out.println("wow!! you got it");
break;
}
for (int i = 0; i < guessnum.length; i++) {
int count = 1;
System.out.print((i+1)+" Enter number 1-4 : ");
int num = sc.nextInt();
if (num == 1) {
System.out.println("not here");
}
else if (num == 2) {
System.out.println("wow!! you got it");
}
else if (num == 3) {
System.out.println("not here");
}
else if (num == 4) {
System.out.println("wow!! you got it");
} else {
if (i != 2) {
System.out.println("number must be 1-4 only, try again,and change another number");
} else {
break;
}
//do again in same loop
}
i++;
}
you can try this
Here is all my code, in two chance the user needs to put 2 and 4 to win.
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("you have only two chance to get all");
int guessnum[] = new int[2];
int x=0;
for (int i = 0; i < guessnum.length; i++) {
System.out.print((i+1)+" Enter number 1-4 : ");
int num = sc.nextInt();
if (num == 1) {
System.out.println("not here");
}
else if (num == 2) {
System.out.println("wow!! you got it");
x++;
}
else if (num == 3) {
System.out.println("not here");
}
else if (num == 4) {
System.out.println("wow!! you got it");
x++;
}
else {
System.out.println("number must be 1-4 only, try again");
--i;
}
}
if (x == 0)
System.out.println("\nyou don't get anything");
if (x == 1)
System.out.println("\nyou got 1 only");
if (x == 2)
System.out.println("\ncongrat!!!! you got all");
}
}
If you wanna use for loop you can write something like this --i; in the last else block after System.out.println("number must be 1-3 only, try again");
So, this code will solve your problem:
System.out.println("you have only two chance to get all");
int guessnum[] = new int[2];;
for (int i = 0; i < guessnum.length; i++) {
System.out.print((i+1)+" Enter number 1-4 : ");
int num = sc.nextInt();
if (num == 1) {
System.out.println("not here");
}
else if (num == 2) {
System.out.println("wow!! you got it");
}
else if (num == 3) {
System.out.println("not here");
}
else if (num == 4) {
System.out.println("wow!! you got it");
}
else {
System.out.println("number must be 1-4 only, try again");
--i;
}
}
UPDATE
In my answer above I just said, how to repeat for loop with minimal changes to the original code. As was asked in the title. But #JayPrakash said that it wasn't perfect answer and vote it down. Ok, lets try to find the perfect one:
public static void main(String[] args) {
guess(2, 1, 4, new int[]{2, 4});
}
/**
*
* #param tries tries count
* #param from from range, inclusive
* #param to to range inclusive
* #param puzzled array with puzzled values
* #return array, which contains only puzzled answers from a user
*/
public static int[] guess(int tries, int from, int to, int[] puzzled) {
if (puzzled == null || puzzled.length < 1) throw new IllegalArgumentException("puzzled");
if (Math.abs(from - to) < 1) throw new IllegalArgumentException("range");
if (tries < 1 || Math.abs(from - to) < tries - 1) throw new IllegalArgumentException("tries"); //`tries - 1` because `to` is inclusive
if (from > to) {
int tmp = from; from = to; to = tmp;
}
Scanner sc = new Scanner(System.in);
int answers[] = new int[tries], //all previous user answers
result[] = new int[tries];
System.out.printf("You have only %d chances to get all\n", tries);
int i = 0, j = 0;
while (i < tries && j < puzzled.length) { // `j < puzzled.length` break if all puzzled answers is found
System.out.printf("%d Enter number %d-%d: ", (i + 1), from, to);
int number = sc.nextInt();
if (number < from || number > to) {
System.out.printf("Number must be in %d-%d range only, try again\n", from, to);
continue;
}
if (contains(answers, number, i)) {
System.out.printf("Number %d is used before\n", number);
continue;
}
answers[i++] = number;
if (contains(puzzled, number)) {
System.out.println("Wow!! you got it");
result[j++] = number;
} else {
System.out.println("Not here");
}
}
if (j == puzzled.length)
System.out.println("You got all");
else
System.out.printf("You got %d only\n", j);
return Arrays.copyOfRange(result, 0, j);
}
private static boolean contains(int[] array, int value) {
return contains(array, value, array.length);
}
private static boolean contains(int[] array, int value, int lookTo) {
for (int i = 0; i < lookTo; i++)
if (array[i] == value)
return true;
return false;
}
int i = 1;
Scanner sc = new Scanner(System.in);
do {
System.out.println("you have only two chance to get all");
System.out.print((i) + " Enter number 1-4 : ");
int num = sc.nextInt();
switch (num) {
case 1:
System.out.println("not here");
break;
case 2:
System.out.println("wow!! you got it");
goItOrNot = false;
break;
case 3:
System.out.println("not here");
break;
case 4:
System.out.println("wow!! you got it");
break;
default:
System.out.println("number must be 1-4 only, try again");
break;
}
i++;
}
} while (i < 3);
Related
Screenshot of error message
Getting this error when I run my code, note that it finds a problem at line 37, but I cannot figure out what it is. Running the first iteration of the scanner method (for input 1) worked fine, and yielded the proper output, but none of the consecutive ones have, and I've been stuck on that issue. Code is below:
import java.io.FileNotFoundException;
import java.io.File;
import java.util.Scanner;
public class Assignment2 {
public static void main(String[] args) {
int largest= 0;
int largestEven = 0;
int countOfAllPositive = 0;
int sumOfAll = 0;
try {
Scanner input1 = new Scanner(new File("input1.txt"));
while (input1.hasNextInt()) {
if (input1.nextInt() == 0)
{ break;
} else if (input1.nextInt() < largest)
{ largest = input1.nextInt();
} else if (input1.nextInt() > 0)
{ largestEven += input1.nextInt();
} else if (input1.nextInt() % 2 == 0)
{ countOfAllPositive += input1.nextInt();
} else if (input1.nextInt() < 0)
{ sumOfAll++;
}
}
Scanner input2 = new Scanner(new File("input2.txt"));
while (input2.hasNextInt()) {
if (input2.nextInt() == 0)
{ break;
} else if (input2.nextInt() < largest)
{ largest = input2.nextInt();
} else if (input2.nextInt() > 0)
{ largestEven += input2.nextInt();
} else if (input2.nextInt() % 2 == 0)
{ countOfAllPositive += input2.nextInt();
} else if (input2.nextInt() < 0)
{ sumOfAll++;
}
}
Scanner input3 = new Scanner(new File("input3.txt"));
while (input3.hasNextInt()) {
if (input3.nextInt() == 0)
{ break;
} else if (input3.nextInt() < largest)
{ largest = input3.nextInt();
} else if (input3.nextInt() > 0)
{ largestEven += input3.nextInt();
} else if (input3.nextInt() % 2 == 0)
{ countOfAllPositive += input3.nextInt();
} else if (input3.nextInt() < 0)
{ sumOfAll++;
}
}
Scanner input4 = new Scanner(new File("input4.txt"));
while (input4.hasNextInt()) {
if (input4.nextInt() == 0)
{ break;
} else if (input4.nextInt() < largest)
{ largest = input4.nextInt();
} else if (input4.nextInt() > 0)
{ largestEven += input4.nextInt();
} else if (input4.nextInt() % 2 == 0)
{ countOfAllPositive += input4.nextInt();
} else if (input4.nextInt() < 0)
{ sumOfAll++;
}
}
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace(); }
System.out.println("The largest integer in the sequence is " + largest);
System.out.println("The largest even integer in the sequence is " + largestEven);
System.out.println("The count of all positive integers in the sequence is " + countOfAllPositive);
System.out.println("The sum of all integers is " + sumOfAll);
}
}
The exception NoSuchElementException in your case is caused by trying to use nextInt() on a file/input that has no more int's left to read, see the Javadoc:
Thrown by various accessor methods to indicate that the element being
requested does not exist.
The reason you get the issue is because every time you call nextInt() in actually uses up an int and moves onto the next one.
So instead of this where you call nextInt() over and over in the if/else if:
if (input1.nextInt() == 0) //Gets the next int
{ break;
} else if (input1.nextInt() < largest) //Gets the next int (different from the previous)
{ largest = input1.nextInt(); //Gets the next int (different from the previous)
... //And so on
You need to do call nextInt() once and assign it to a value then use that value:
//Store the int as a value
int value = input1.nextInt();
//Use the value instead of calling "nextInt()" again
if (value == 0)
{ break;
} else if (value < largest)
{ largest = value;
...
I wrote a code about primes and would hear your opinion or any suggestions how i can improve my code. I'm a beginner in Java.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean a;
System.out.println("Please enter a number: ");
int zahl = s.nextInt();
if(zahl <= 0) {
System.out.println("Please enter a positive number without zero.");
return;
}
a = true;
for (int i = 2; i < zahl; i++) {
if (zahl % i == 0) {
a = false;
}
}
if (a == true) {
System.out.println("Is Prim");
}
if (a==false){
System.out.println("Not a prim");
}
}
The easiest thing to do is the following
Instead of
for (int i = 2; i < zahl; i++) {
if (zahl % i == 0) {
a = false;
}
}
change the for loop the
for (int i = 2; i < Math.sqrt(zahl); i++)
If no numbers up to the square root divide zahl, then no numbers beyond the square root will divide it either (they would have been the result of earlier divisions).
Also, for outputing the answer you could do:
System.out.println(zahl + " is " + ((a) ? "prime"
: "not prime"));
That's using the ternary operator ?:
some hints :
You do
System.out.println("Please enter a positive number without zero.");
return;
the println suggests the user can enter a new value, but no, in that case better to say the number was invalid so you exit
When you do a = false; it is useless to continue, no chance for a to be back true
It is useless to try to divide by more than sqrt the number
It is necessary to try to divide by 2 but not by an other even number, so add 2 to i rather than 1
If if (a == true) false it is useless to check if (a==false)
Your code is good. I have made three small improvements:
The input asks at once (and not only after a bad input) for a
positive int.
The input is repeated until correct.
The for loop runs only up to sqrt(zahl) which is sufficient.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean a;
int zahl = 0;
while (zahl <= 0) {
System.out.println("Please enter a positive int without zero.");
zahl = s.nextInt();
}
a = true;
for (int i = 2; i <= Math.sqrt(zahl); i++) {
if (zahl % i == 0) {
a = false;
break;
}
}
if (a == true) {
System.out.println("Is Prim");
} else {
System.out.println("Not a prim");
}
}
I'm working on this simple task called "Guess my number" and Im trying to implement my code so when user guesses the right number the application displays "Congratulations " and allow the user to choose whether to play again or not. I think a do while loop will do it, but Im still not sure how to implement that. Any ideas?. Thank you in advanced!
Here's my code that runs just fine.
Random random = new Random();
while (true)
{
int randomNumber = random.Next(1, 5);
int counter = 1;
while (true)
{
Console.Write("Guess a number between 1 and 5");
int input = Convert.ToInt32(Console.ReadLine());
if (input < randomNumber)
{
Console.WriteLine("Too low, try again.");
++counter;
continue;
}
else if (input > randomNumber)
{
Console.WriteLine("Too high, try again.");
++counter;
continue;
}
else
{
Console.WriteLine("Congratulations. You guessed the number!");
break;
}
}
}
You can add a boolean flag to set inside your outermost loop to break if the user says "No":
Random random = new Random();
while (true)
{
int randomNumber = random.Next(1, 5);
int counter = 1;
bool retry = true;
while (true)
{
Console.Write("Guess a number between 1 and 5");
int input = Convert.ToInt32(Console.ReadLine());
if (input < randomNumber)
{
Console.WriteLine("Too low, try again.");
++counter;
continue;
}
else if (input > randomNumber)
{
Console.WriteLine("Too high, try again.");
++counter;
continue;
}
else
{
Console.WriteLine("Congratulations. You guessed the number!");
Console.WriteLine("Would you like to retry? y/n");
string answer = Console.ReadLine();
if (answer != "y")
{
retry = false;
}
break;
}
}
if (!retry) break;
}
and for the do-while version:
bool retry = true;
Random random = new Random();
do
{
int randomNumber = random.Next(1, 5);
int counter = 1;
while (true)
{
Console.Write("Guess a number between 1 and 5");
int input = Convert.ToInt32(Console.ReadLine());
if (input < randomNumber)
{
Console.WriteLine("Too low, try again.");
++counter;
continue;
}
else if (input > randomNumber)
{
Console.WriteLine("Too high, try again.");
++counter;
continue;
}
else
{
Console.WriteLine("Congratulations. You guessed the number!");
Console.WriteLine("Would you like to retry? y/n");
string answer = Console.ReadLine();
if (answer != "y")
{
retry = false;
}
break;
}
}
} while (retry);
Implementing a do.. while loop in your code is easy no much difference
Random random = new Random();
do
{
int randomNumber = random.Next(1, 5);
int counter = 1;
do
{
Console.Write("Guess a number between 1 and 5");
int input = Convert.ToInt32(Console.ReadLine());
if (input < randomNumber)
{
Console.WriteLine("Too low, try again.");
++counter;
continue;
}
else if (input > randomNumber)
{
Console.WriteLine("Too high, try again.");
++counter;
continue;
}
else
{
Console.WriteLine("Congratulations. You guessed the number!");
break;
}
}while (true);
}while (true);
Hope that helps...
How can I add a statement that allows me to check if the credit card number inputted by the user is a palindrome? I am checking for the appropriate length already so how can i Input the new palindrome checker into this code:
import java.util.Scanner;
public class DT18 {
public static void main(String[] args) {
String number;
Boolean debug = false;
if (args.length == 0) { // no command line
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a Credit Card number to validate.");
number = keyboard.next();
} else { // command line input
number = args[0];
}
if (debug) System.out.println("String Length " + number.length());
if (number.length() < 10) {
System.out.println("Not Valid");
}
int sum = 0;
int oddDigit = 0;
for (int i = number.length() - 1; i >= 0; i--) {
if (debug) System.out.println("i = " + i);
if ((Character.getNumericValue(number.charAt(i)) < 0) || (Character.getNumericValue(number.charAt(i)) > 9)) {
System.out.println("Not Valid");
break;
}
if (i % 2 == 0) { //Even Digit
sum += Character.getNumericValue(number.charAt(i));
} else { //Odd Digit
oddDigit = (2 * Character.getNumericValue(number.charAt(i)));
if (oddDigit > 9) oddDigit = (oddDigit % 10) + 1;
sum += oddDigit;
}
if (debug) System.out.println(sum);
}
if (sum % 10 == 0) {
System.out.println("Valid");
} else {
System.out.println("Not Valid");
}
}
}
From an answer I once gave here:
public boolean isPalindrom(int n) {
return new StringBuilder("" + n).reverse().toString().equals("" + n);
}
This post should give you for loop logic:
http://www.programmingsimplified.com/java/source-code/java-program-check-palindrome
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
You can write a simple function to check if a string is a palindrome or not.
private static boolean checkPalindrome(String input) {
int i = 0, j = input.length() - 1;
for (; i < j; i++) {
if (i == j) {
return true;
}
if (input.charAt(i) == input.charAt(j)) {
j--;
}
else
return false;
}
return true;
}
This is a crude method; you may want to modify it according to your requirement, but it will get the job done in most of the cases.
I've looked over the other answers and all of them have bad performance and working with String instead of just using the given number. So I'll add the version without conversion to String:
public static boolean isPalindrome(int n) {
int[] digits = new int[length(n)];
for (int i = 0; n != 0; ++i) {
digits[i] = n % 10;
n /= 10;
}
for (int i = 0; i < digits.length / 2; ++i) {
if (digits[i] != digits[digits.length - i - 1]) {
return false;
}
}
return true;
}
public static int length(int n) {
int len = 0;
while (n != 0) {
++len;
n /= 10;
}
return len;
}
Not sure, if that's the best implementation, but I got rid of Strings :-)
My professor assigned to write a prime number "finder". Where the number you input will display if it's a prime or even number, then display the next prime number. He wants us to give an error message when the wrong input is keyed in. I figured the negative integer portion is simple, but I cannot figure out the character input. Or if the character is not a digit. How would i block non numeric inputs?
Also, the system is supposed to exit at three CONSECUTIVE erroneous inputs. How would I reset the counter? The way i have written the program, if the user makes two errors but the next ones are acceptable, then make another error. (thus not being consecutive.) the program closes.
This is my first programing course so I'm not to savvy in it. Any help would be greatly appreciated.
Also, i have to use scanner, and the two methods.
/**
*
* #param n
* #return
*/
public static boolean isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static int nextPrime(int n) {
n++;
isPrime(n);
while (isPrime(n) == false) {
n++;
isPrime(n);
}
int prime = n;
return prime;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int answer = 2;
int counter = 1;
boolean playAgain = false;
Scanner input = new Scanner(System.in);
Scanner reader = new Scanner(System.in);
Scanner in = new Scanner(System.in);
do {
//ask for input
System.out.print("\nEnter the integer value-> ");
//input answer
int n = input.nextInt();
{
//decide is negative
while ( n < 0){
//count counter
counter++;
//give error message
System.out.println("\nInvalid Input! Stike!");
//ask for input
System.out.print("\nEnter the integer value-> ");
//input answer
n = input.nextInt();
//decide is character
// if ( n != '.'){
//count counter
// counter++;
//give error message
// System.out.println("\nInvalid Input! Strike!");
// }
//decide if count three errors
if (counter == 3){
//display three errors message
System.out.println("Three Strikes! You're Out!");
//close program
System.exit(0);
}
}
//decide if prime
if (isPrime(n)) {
//display prime answer
System.out.println(n + " Is Prime");
//decide if even
} else {
//display even answer
System.out.println(n + " Is Even");
}
//counter input
n++;
//while input is false
while (isPrime(n) == false) {
n++;
}
//display next prime
System.out.println(n + " Next prime");
{
//ask if you want to continue
System.out.println("\nPlay Again?\n\nEnter 1)Yes or 2)No ");
//input answer
answer = in.nextInt();
//if answer is 1)yes
if (answer == 1) {
playAgain = true;
//display play again and next input
System.out.println("\nPlay Again!");
}
//if answer is no
if (answer == 2) {
playAgain = false;
System.out.println("\nGoodbye!");
//close program
System.exit(0);
}
}
}
} while (playAgain != false);
}
}
import java.util.Scanner;
public class SOQ5B
{
public static boolean isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static int nextPrime(int n) {
n++;
isPrime(n);
while (isPrime(n) == false) {
n++;
isPrime(n);
}
int prime = n;
return prime;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int answer;
int counter = 0;
int n;
boolean playAgain = true;
boolean isNum;
boolean isNum2;
boolean continuePermitted = true;
Scanner input = new Scanner(System.in);
String s;
do {
//ask for input
System.out.print("\nEnter the integer value-> ");
s = input.nextLine();
isNum = true;
for(int i = 0; i < s.length(); i++)
{
if(!(s.charAt(i) >= '0' && s.charAt(i) <= '9'))
{
isNum = false;
}
}
if(isNum)
{
counter = 0;
n = Integer.parseInt(s);
//decide if prime
if (isPrime(n)) {
//display prime answer
System.out.println(n + " Is Prime");
//decide if even
}
else {
//display even answer
System.out.println(n + " Is Even");
}
//counter input
n++;
//while input is false
while (isPrime(n) == false) {
n++;
}
//display next prime
System.out.println(n + " Next prime");
do
{
continuePermitted = true;
//ask if you want to continue
System.out.println("\nPlay Again?\n\nEnter 1)Yes or 2)No ");
//input answer
s = input.nextLine();
isNum2 = true;
for(int i = 0; i < s.length(); i++)
{
if(!(s.charAt(i) >= '0' && s.charAt(i) <= '9'))
{
isNum2 = false;
}
}
if(isNum2)
{
answer = Integer.parseInt(s);
//if answer is 1)yes
if (answer == 1) {
playAgain = true;
//display play again and next input
System.out.println("\nPlay Again!");
}
//if answer is no
if (answer == 2) {
playAgain = false;
System.out.println("\nGoodbye!");
//close program
System.exit(0);
}
}
else
{
System.out.println("Incorrect response.");
continuePermitted = false;
//if answering the yes or no question incorrectly is part of the 3 strikes
//then uncomment the following lines of code
/*
counter++;
}
if(counter >= 3)
{
System.out.println("3 strikes you out");
System.exit(0);
*/
}
}while(!continuePermitted);
}
else
{
System.out.print("\nIncorrect input. Number must be a positive integer.\n");
counter++;
}
if(counter>=3)
{
System.out.println("3 strikes and you're out!");
System.exit(0);
}
} while (playAgain != false);
}
}
In the future, I recommend you research your questions on the internet before bringing the question here. There were several other places that could've easily answered your question.
Now as for your actual question, notice how I changed your code at the line that says s = input.nextLine()? What I did there is checked to see if each digit in the string was any number between and including 0-9. Not only was I able to check if they were all numbers, but I was also able to see if they were all positive too as you would have to put a - in order for it to be negative. Along with that, you also have a boolean that only works when the input is a positive number. If not, it checks 3 times to make sure your program doesn't mess up. Furthermore, I even commented out another section that allows the 3 strikes to include if answering the yes no question counts as a strike. If there any other questions, just ask and I will edit my answer.
You are trying to take input using Scanner class with
int n = input.nextInt();
If you enter a character in place of number here you will get java.util.InputMismatchException
What you can do is something like
try {
int n = input.nextInt();
} catch (InputMismatchException e) {
//handle the error scenario where the input is a character
System.out.println("Enter Valid Input");
}