how to print number of stars depending on user choose - java

I've been trying practiceIt problems and expand them a little - and I'm stuck.
The code will give results in as many stars as it's necessary, but I do not know how to make user decide the value for n.
I've tried adding to both methods (main/starString) those code lines:
"Scanner input = new.Scanner(System.in);
int n = input.next();" [also input.nextInt]
but the code will note allow any input from console. Not to mention I've got no idea where shoud I add second println command to actually print result from this code...
help me please
import java.util.*;
public class printStars {
public static void main(String[]args) {
System.out.println("choose number and I wil show you 2^number stars");
}
public static String starString(int n) {
if (n < 0) {
throw new IllegalArgumentException();
} else if (n == 0) {
return "*";
} else {
return starString(n - 1) + starString(n - 1);
}
}
}

Do it as follows:
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Choose number and I wil show you 2^number stars: ");
System.out.println(starString(in.nextInt()));
}
public static String starString(int n) {
if (n < 0) {
throw new IllegalArgumentException();
} else if (n == 0) {
return "*";
} else {
return starString(n - 1) + starString(n - 1);
}
}
}
A sample run:
Choose number and I wil show you 2^number stars: 5
********************************

You should also be checking the input before you enter the method. Here is one approach that allows for improper input and reprompts the user to enter the correct value. This way, no exceptions need be caught.
Scanner in = new Scanner(System.in);
String prompt = "Choose number (or a char to end) \nand I will show you 2^number stars: ";
System.out.print(prompt);
while (in.hasNextInt()) {
int n = in.nextInt();
if (n > 0) {
System.out.println(starString(n));
} else {
System.out.print("Input must be greater than 0, try again: ");
continue;
}
System.out.print(prompt);
}
System.out.println("Bye!");
public static String starString(int n) {
if (n == 0) {
return "*";
} else {
return starString(n - 1) + starString(n - 1);
}
}

Related

Suggestions to improve code about primes?

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");
}
}

Java Scanner ignores answer

Hi it's my first post here and I have a problem:
I have a program in which, at some point, asks the user if he wants to share the stars, and if he supposedly does, the program goes back to collecting them and after some time comes back to the question if he wants to share them again.
The problem is that, when the user comes back to that point, the program ignores whatever answer u give to it and goes to the "else answer block".
It looks like this:
"Do you want to share your stars?
yes
Please answer with yes or no"
Code:
import java.util.Random;
import java.util.Scanner;
public class App {
static Scanner skan = new Scanner(System.in);
static int starCount = 0;
static Random random = new Random();
public static void main(String[] args) {
starReaching();
}
static void starReaching() {
boolean starCollected = false;
int i = 0;
int j = random.nextInt(101);
while (i < j) {
i++;
System.out.println("Stars are out of reach");
}
if (i > j || i == j) {
starCollected = true;
}
if (starCollected == true) {
starCollector();
}
}
static void starCollector() {
System.out.println("You caught a star !");
starCount++;
if (starCount == 10) {
System.out.println("You have 10 stars ! :)");
System.out.println("Do you want to share your stars?");
String line = skan.nextLine();
if (line.equals("yes")) {
skan.reset();
starGiver();
} else if (line.equals("no")) {
wishMaker();
} else {
System.out.println("Please answer with yes or no");
System.exit(0);
}
} else {
starReaching();
}
}
static void starGiver() {
System.out.println("How many do you want to share?");
int starsToShare = skan.nextInt();
if (starsToShare < 10 || starsToShare == 10 && starsToShare > 0) {
starCount = starCount - starsToShare;
System.out.println("Stars shared !");
System.out.println("You now have " + starCount + " stars");
System.out.println("Go collect them again!");
starReaching();
} else if (starsToShare > 10) {
System.out.println("You don't have enough stars to share that much!");
starGiver();
} else {
System.out.println("That's not a valid option");
starGiver();
}
}
static void wishMaker() {
}
}
Every time you call skan.nextLine() you read a new line and advance the scanner's pointer, and this is the reason your code is failing: you're calling this too often.
Instead of
if (skan.nextLine().equals("yes")) {
skan.reset();
starGiver();
} else if (skan.nextLine().equals("no")) {
wishMaker();
} else {
do:
String line = scan.nextLine(); // read from Scanner **once** only
if (line.equals("yes")) {
skan.reset();
starGiver();
} else if (line.equals("no")) {
wishMaker();
} else {
Okay i've found the little bugger, i was using skan.nextInt without using skan.nextLine after that, thank you for the quick help, much love

How to make the code run reversly? from Roman number to decimal number

I already wrote a code that convert from decimal number to roman number, however, i want it to do opposite way so how can i make it possible? (This is my previous code: http://pastebin.com/QFKi0xJh ) thank you! and here is my code right now.
I am just a beginner so my code is look little bit basic, please apology for that.
public static void main(String[] args) {
// Fill in the body
Scanner in= new Scanner(System.in);
String user = promptUserForNumeral(in);
while (user.length()!=0) {
int numb= convertNumeralToNumber(user);
System.out.println("The numeral "+user+ " is the decimal number "+numb);
user = promptUserForNumeral(in);
}
}
private static String promptUserForNumeral(Scanner inScanner) {
// Fill in the body
System.out.println("Enter a roman numeral (Q to quit): ");
String i = inScanner.nextLine();
while (i.length()>=0) {
if (i.length()==0) {
System.out.println("ERROR! You must enter a non-empty line!");
System.out.println("Enter a roman numeral (Q to quit): ");
i = inScanner.nextLine();
}
else if ( i.length()==1 && i.charAt(0)=='q' || i.charAt(0)=='Q') {
System.out.println("Goodbye!");
System.exit(0);
}
}
return i;
}
private static int convertNumeralToNumber(String numeral) {
// Fill in the body
int n=0;
if (numeral.equalsIgnoreCase("m")) {
n-=1000;
}
else if (numeral.equalsIgnoreCase("d")) {
n=500;
}
else if (numeral.equalsIgnoreCase("c")) {
n=100;
}
else if (numeral.equalsIgnoreCase("l")) {
n=50;
}
else if (numeral.equalsIgnoreCase("x")) {
n=10;
}
else if (numeral.equalsIgnoreCase("v")) {
n=5;
}
else if (numeral.equalsIgnoreCase("i")) {
n=1;
}
return n;
}

How to reject inputs that are non digit characters?

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");
}

Number guesser program throwing exceptions Java

I am trying to add exceptions to a program i've already wrote. I need to write exceptions when the user tries to cheat on a number guess program for the higher and lower methods as well as add a try/catch on the game to display the error. I almost have it written correctly but and exception is thrown right before the last possible outcome. Attached is the class file i wrote along with the program to run the game.
Here is my class for the number guesser logic
public class NumberGuesser {
private int min, max, midpoint, origMin, origMax;
public NumberGuesser()
{
min = 1;
max = 100;
}
public NumberGuesser(int lowerBound, int upperBound)
{
min = lowerBound;
max = upperBound;
origMin = lowerBound;
origMax = upperBound;
}
public void setMin(int value)
{
min = value;
}
public void setMax(int value)
{
max = value;
}
public int getMin()
{
return min;
}
public int getMax()
{
return max;
}
public void higher()
{
min = getCurrentGuess() + 1;
if (min == max)
{
throw new IllegalStateException("No more possible outcomes");
}
}
public void lower()
{
max = getCurrentGuess() -1;
if (max == min)
{
throw new IllegalStateException("No more possible outcomes");
}
}
public int getCurrentGuess()
{
midpoint = (max + min) /2;
return midpoint;
}
public void reset()
{
min = origMin;
max = origMax;
}
}
Here is the program that runs the game.
import java.util.*;
public class GuessingProgram {
public static void main(String[] args) {
do
{
playOneGame();
}
while (shouldPlayAgain());
}
public static void playOneGame()
{
char input = 0;
Scanner keyboard = new Scanner(System.in);
NumberGuesser game = new NumberGuesser(1,100);
System.out.println("NUMBER GUESSER GAME");
System.out.println("-------------------");
System.out.println("Think of a number between 1 and 100");
while (input != 'c')
{
try
{
System.out.print("Is your number " + game.getCurrentGuess() + "?" +
" (h/l/c): ");
input = keyboard.next().charAt(0);
if (input == 'h' || input == 'H')
game.higher();
else if (input == 'l' || input == 'L')
game.lower();
else if (input == 'c' || input == 'C')
game.reset();
}
catch(IllegalStateException e)
{
System.out.println("Invalid input, You are cheating!!!");
}
}
}
public static boolean shouldPlayAgain()
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Great! Do you want to play again? (y/n): ");
String input = keyboard.nextLine();
if (input.equalsIgnoreCase("y"))
return true;
else
return false;
}
}
Here is my output and the number its supposed to guess is 77
NUMBER GUESSER GAME
Think of a number between 1 and 100
Is your number 50? (h/l/c): h
Is your number 75? (h/l/c): h
Is your number 88? (h/l/c): l
Is your number 81? (h/l/c): l
Is your number 78? (h/l/c): l
Is your number 76? (h/l/c): h
Invalid input, You are cheating!!!
Is your number 77? (h/l/c):
If min and max reach the same value, that means you've found the correct value. I think you want to throw illegalStateException if you say the number is higher/lower after you found the correct value, it is, max < min.

Categories

Resources