EDIT for a little bit more clearance:
I think what the code should do is: "If I put 0 as first on the "scanner", the text "you cant count the ones" should pop up.
But if I have typed some other numbers into scanner first, it should "break;" the program and print ONLY out the calculations that are at the bottom. Not the "you cant count the ones".
I seem to get one part of the two working, but not the both.
I've tried moving the if-sentences around, and moving System.out.println's around.
public static void main(String[] args) {
Scanner lukija = new Scanner(System.in);
int yksi = 0;
int numero = 0;
while (true) {
int luku = Integer.valueOf(lukija.nextLine());
if (luku == 0) {
System.out.println("you cant count the ones");
break;
}
if (luku == 1) {
yksi = yksi + 1;
} else if (luku != 0) {
numero = numero + 1;
}
}
System.out.println(1.0 * yksi / (numero + yksi));
}
I'm assuming you don't want to break when you first type 0 and only display the message "you cant count the ones". Then you can use a flag like this and put the break inside the else part,
public static void main(String[] args) {
Scanner lukija = new Scanner(System.in);
int yksi = 0;
int numero = 0;
boolean flag = true;
while (true) {
int luku = Integer.valueOf(lukija.nextLine());
if (luku == 0) {
if (flag) {
System.out.println("you cant count the ones");
} else {
break;
}
}
flag = false;
if (luku == 1) {
yksi = yksi + 1;
} else if (luku != 0) {
numero = numero + 1;
}
}
System.out.println(1.0 * yksi / (numero + yksi));
}
Related
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 trying to add spaces and a counter between consecutive runs in a simple java coin toss program.
I want this output: HHHHTHTTTTTTTHTTTHHHTTTTHTTHHHTTTTHHTHHHHHTTTTTTHT
to look print like this: HHHH4 T1 H1 TTTTTTT7 H1 TTT3 HHH3 TTTT4 H1 TT2 HHH3 TTTT4 HH2 T1 HHHHH5 TTTTTT6 H1 T1
I am not sure how to position the conditions in the loop so that spaces and a counter are printed between the consecutive 'T's and 'H's. Do I need to use a different kind of loop? I have tried rearranging the loop and using break; and continue; but haven't gotten the result to print correctly.
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.print("How many times do you want to flip the coin? ");
int timesFlipped = scnr.nextInt();
Random randomNum = new Random();
for (int i=0; i < timesFlipped; i++) {
int currentflip = randomNum.nextInt(2);
int previousFlip = 0;
int tailsCount = 0;
int headsCount = 0;
if (currentflip == 0) {
System.out.print("H");
previousFlip = 0;
headsCount++;
}
else if (currentflip == 1) {
System.out.print("T");
previousFlip = 1;
tailsCount++;
}
if (previousFlip == 0 && currentflip == 1) {
System.out.print(headsCount + " ");
headsCount = 0;
}
else if (previousFlip == 1 && currentflip == 0) {
System.out.print(tailsCount + " ");
tailsCount = 0;
}
}
}
You can just store the last flip and a counter like
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.print("How many times do you want to flip the coin? ");
int timesFlipped = scnr.nextInt();
Random randomNum = new Random();
int counter = 1;
int previousFlip = randomNum.nextInt(2);
printFlip(previousFlip);
for (int i=1; i < timesFlipped; i++) {
int currentflip = randomNum.nextInt(2);
if (currentflip == previousFlip) {
counter++;
} else {
System.out.print(counter + " ");
counter = 1;
previousFlip = currentflip;
}
printFlip(currentflip);
}
System.out.print(counter);
}
private static void printFlip(int currentflip) {
if (currentflip == 0) {
System.out.print("H");
}
else if (currentflip == 1) {
System.out.print("T");
}
}
Via a single method:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.print("How many times do you want to flip the coin? ");
int timesFlipped = scnr.nextInt();
if (timesFlipped <= 0)
return;
Random randomNum = new Random();
boolean isHeads = false;
int sequence = 0;
for (int i = 0; i < timesFlipped; i++) {
boolean prevFlip = isHeads;
isHeads = randomNum.nextBoolean();
if (i > 0 && isHeads != prevFlip) {
System.out.print(sequence + " ");
sequence = 0;
}
sequence++;
System.out.print(isHeads ? "H" : "T");
}
System.out.println(sequence);
}
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);
im fairly new to Java and just cant figure out why my program is not working. Anything anyone can do to help would be appreciated!
public class LabOne {
public static void main(String[] args) {
System.out.println("Please input a number: \n");
int inputReceive = 44;
int nextPrime = inputReceive;
int n = 5;
boolean isprime=true;
do {
if(inputReceive <= 1)
isprime = false;
else if(inputReceive <= 3){
System.out.printf("%d \n",isprime);
return;
}else if( inputReceive % 2 == 0 || inputReceive % 3 == 0)
isprime = false;
while ((n*n)<inputReceive){
if (inputReceive % n == 0 || inputReceive % (n + 2) == 0)
isprime = false;
n = n+6;
isprime = true;
}
nextPrime++;
}while(isprime = false);
System.out.printf("Next prime number is %d",nextPrime);
}
}
output given would be 45 and thats not correct.
A few problems:
while(isprime = false);
That's assignment, not equality testing. Since you're assigning false, this won't loop.
n = n+6;
isprime = true;
You do this unconditionally.
Expansion to follow.
Ignoring things already pointed out, you perform all of your checks on inputRecieve and never update it. You only unconditionally update nextPrime and moreover never check its primeness. Here is how I would do it:
public static boolean isPrime(int x){
boolean result = true;
for(int i = 2; i<=Math.sqrt(x); i++){
if((x % i) == 0){
result = false;
}
}
return result;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please insert a number:");
int inputRecieve = sc.nextInt();
boolean notPrime = true;
while(notPrime){
if(isPrime(++inputRecieve))
notPrime = false;
}
System.out.println("Next prime number is: " + inputRecieve);
}
I am creating a Hangman Game in Java and it almost works perfectly. So I have two problems. The first being that:
When the user inputs a letter and the word has repeated letters, how can I make it print both instances of the letter.
I have created a while loop however this loop does not output the Modified word until after the next go. If that makes sense?
The second problem:
I need to be able to prevent the user from entering the same letter twice
I have attempted Lists and arrays and hash sets. All sorts but none seem to work.
My code is below:
There may be other threads with same questions but none seem to help as I cannot implement it into this person's code.
import java.util.Scanner;
import java.util.Arrays;
public class Hangman{
public static void main(String []args){
Scanner Input = new Scanner(System.in);
String[] CollectionOfWords = {"","gravity","banana","gate","processor","momentum","earth","star","light","television","pan","cupboard"};
int radmNumber = (int) Math.ceil (Math.random() * CollectionOfWords.length);
int counter = 10;
String radmWord = CollectionOfWords[radmNumber];
char[] genRadmLetter = radmWord.toCharArray();
char[] genRadmLetter2 = radmWord.toCharArray();
for (int x = 0; x<genRadmLetter.length; x++){
genRadmLetter[x]='?';
}
System.out.println(String.valueOf(genRadmLetter));
System.out.println("Hello. Guess a letter.");
char guessedLetter = Input.next().charAt(0);
int RW = radmWord.indexOf(guessedLetter);
if (RW >= 0 ){
genRadmLetter[RW] = guessedLetter;
System.out.println(genRadmLetter);
}
if (RW == -1){
System.out.println("Wrong letter, try again.");
counter = counter - 1;
System.out.println("Lives left: " + counter);
}
while (counter != 0) {
System.out.println("Guess a letter.");
guessedLetter = Input.next().charAt(0);
RW = radmWord.indexOf(guessedLetter);
if (RW >= 0 ){
genRadmLetter[RW] = guessedLetter;
System.out.println(genRadmLetter);
}
if (RW == -1){
System.out.println("Wrong letter, try again.");
counter = counter - 1;
System.out.println("Lives left: " + counter);
} else {
System.out.println(genRadmLetter);
while (RW >= 0 ){
genRadmLetter[RW] = guessedLetter;
RW = radmWord.indexOf(guessedLetter, RW+1);
}
}
boolean result = Arrays.equals(genRadmLetter, genRadmLetter2);
if (result == true){
break;
}
if (counter == 0){
break;
}
}
if (counter == 0){
System.out.println("You lose. The word was: " + radmWord);
}
else {
System.out.println("Well done, you have guessed the word.");
System.out.println("Your final score is: " + counter);
}
}
}
Instead of using...
int RW = radmWord.indexOf(guessedLetter);
To determine if the entered value matches a character, which will only return the first index, you should, instead, use a loop of some kind to check every character
boolean found = false;
for (int rw = 0; rw < genRadmLetter2.length; rw++) {
if (genRadmLetter2[rw] == guessedLetter) {
genRadmLetter[rw] = guessedLetter;
found = true;
}
}
Now, because you're relying on the value of RW to determine if a match was found or not, I changed it so that the boolean found flag can used instead, for example...
if (!found) {
System.out.println("Wrong letter, try again.");
counter = counter - 1;
System.out.println("Lives left: " + counter);
}
You also have duplicate sets of code, which can be reduced to a single do-while loop instead, which will make it easier to read and make changes, for example...
do {
//...
} while (counter != 0);
To your second problem, a Set of some kind would be the simplest solution...
Set<Character> guesses = new HashSet<Character>();
//...
char guessedLetter = Input.next().charAt(0);
if (guesses.contains(guessedLetter)) {
System.out.println("You've used this guess, guess again");
} else {
guesses.add(guessedLetter);
For example...
And because it's not always easy to translate code snippets ... this is my test code...
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Hangman {
public static void main(String[] args) {
Scanner Input = new Scanner(System.in);
String[] CollectionOfWords = {"", "gravity", "banana", "gate", "processor", "momentum", "earth", "star", "light", "television", "pan", "cupboard"};
int radmNumber = (int) Math.ceil(Math.random() * CollectionOfWords.length);
int counter = 10;
String radmWord = "banana"; //CollectionOfWords[radmNumber];
char[] genRadmLetter = radmWord.toCharArray();
char[] genRadmLetter2 = radmWord.toCharArray();
for (int x = 0; x < genRadmLetter.length; x++) {
genRadmLetter[x] = '?';
}
Set<Character> guesses = new HashSet<Character>();
do {
System.out.println("Guess a letter.");
System.out.println(String.valueOf(genRadmLetter));
System.out.println("Hello. Guess a letter.");
char guessedLetter = Input.next().charAt(0);
if (guesses.contains(guessedLetter)) {
System.out.println("You've used this guess, guess again");
} else {
guesses.add(guessedLetter);
boolean found = false;
for (int rw = 0; rw < genRadmLetter2.length; rw++) {
if (genRadmLetter2[rw] == guessedLetter) {
genRadmLetter[rw] = guessedLetter;
found = true;
}
}
if (!found) {
System.out.println("Wrong letter, try again.");
counter = counter - 1;
System.out.println("Lives left: " + counter);
}
}
boolean result = Arrays.equals(genRadmLetter, genRadmLetter2);
if (result == true) {
break;
}
if (counter == 0) {
break;
}
} while (counter != 0);
if (counter == 0) {
System.out.println("You lose. The word was: " + radmWord);
} else {
System.out.println("Well done, you have guessed the word.");
System.out.println("Your final score is: " + counter);
}
}
}
There are multiple issues with the code:
the typical beginners problem of length vs. max element number
unnecessary duplicate code
a logic issue with the output
as for 1.:
you are using this:
int radmNumber = (int) Math.ceil (Math.random() * CollectionOfWords.length)
if you use
int radmNumber = (int) Math.ceil (Math.random() * CollectionOfWords.length-1)
you can start the arrey without a empty string and it wont randomly crash
on to 2.
you wont need to duplicate the input code if you use this:
System.out.println(String.valueOf(genRadmLetter));
System.out.print("Hello.");
char guessedLetter;
int RW;
while (counter != 0)
{
System.out.println("Guess a letter.");
...
and finally 3.(your main question)
you do the output before changing it. so this fixes your problem:
...
else
{
while (RW >= 0)
{
genRadmLetter[RW] = guessedLetter;
RW = radmWord.indexOf(guessedLetter, RW + 1);
}
System.out.println(genRadmLetter);
}
So simply move the output behind the while.
I made a little helper clas that could help you...
static class GuessString {
private char[] mask;
private String solution;
private boolean lastGuessResult;
GuessString(String word) {
this.solution = word;
this.mask=word.toCharArray();
Arrays.fill(mask, '?'); // Build a mask like: ??????
}
public String guess(char guess) {
char c = Character.toLowerCase(guess); // case insensitive
int i = solution.indexOf(c);
lastGuessResult = i != -1; // -1 means "not found)
if (lastGuessResult)
while (i != -1) { // this will loop till c is replaced everywhere.
mask[i] = c;
i = solution.indexOf(c, i+1);
}
return new String(mask); // return the updated mask.
}
public boolean lastGuessIsRight() {
return lastGuessResult;
}
public String getCurrent() {
return new String(mask);
}
public boolean isSolved() {
return getCurrent().equals(solution);
}
}