Make if == statement with Scanner nextInt - java

I am trying to make a match game where random numbers will show on the console then you have to type back the same numbers. I am having a problem with the if statement where it shows incorrect even when I input the right numbers. Here is my code so far:
package MatchGame;
import java.util.Random;
import java.util.Scanner;
public class match2 {
int a;
int b;
int c;
int d;
String countdown[] = {
"3...",
"2...",
"1..."
};
public match2() throws InterruptedException {
set1();
}
public void set1() throws InterruptedException {
Scanner s = new Scanner(System.in);
System.out.println("press ENTER for your first set...");
s.nextLine();
for (int i = 0; i < countdown.length; i++) {
Thread.sleep(1000);
System.out.println(countdown[i]);
}
a = number();
b = number();
c = number();
d = number();
System.out.print(a);
System.out.print(b);
System.out.print(c);
System.out.print(d);
int set = a + b + c + d;
int guess = s.nextInt();
{
if(set == guess) {
System.out.println("Nice bruh +1");
}
else {
System.out.println("Nope");
}
}
}
public static int number(){
Random r = new Random();
int match = r.nextInt(9) + 1;
//rv = rv + match;
return match;
}
}
Also the variable 'set' doesn't seem to include the variables a, b, c, and d in it.

An easy method would be to store your values and input to two arrays two separate arrays and compare both instead.

Related

I want to convert Vararg Integer to Vararg int?

The below code is working fine using Integer values for my variadic method. But I want to use "int" instead of "Integer".
Here is the code:
package JavaPracticeShuffler;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class MediumLevelExcercisesA {
Scanner number;
Scanner yorn;
public MediumLevelExcercisesA(){
}
static void DisplayNumbers(Integer...a) {
for (int b = 0; b < a.length; b++) {
System.out.print(a[b]);
System.out.print(" ");
}
}
static void SumOfNumbers(Integer...a) {
int total = 0;
for (int b = 0; b < a.length; b++) {
total += a[b];
}
System.out.println(" ");
System.out.println("Sum: " + total);
}
public static void main(String[] args) {
MediumLevelExcercisesA obj01 = new MediumLevelExcercisesA();
List<Integer> lnumber = new ArrayList<Integer>();
boolean numbercounter = true;
while (numbercounter) {
obj01.number = new Scanner(System.in);
System.out.println("Please input a number");
int inputnumber = obj01.number.nextInt();
lnumber.add(inputnumber);
System.out.println("Number/s you've entered so far are the following: " + lnumber);
obj01.yorn = new Scanner(System.in);
System.out.println("Do you want to continue?");
String iyorn = obj01.yorn.nextLine().toUpperCase();
if (iyorn.equals("YES")||iyorn.equals("Y")) {
System.out.println("You've answered yes, program will proceed.");
}
else if (iyorn.equals("NO")||iyorn.equals("N")) {
System.out.println("You've answered no, program ends.");
numbercounter = false;
break;
}
else {
System.out.println("Answer not understood, program continues.");
}
} //end of while loop.
System.out.println("Final review of numbers entered: " + lnumber);
Integer[] intarray = new Integer[lnumber.size()];
intarray = lnumber.toArray(intarray);
MediumLevelExcercisesA.DisplayNumbers(intarray);
MediumLevelExcercisesA.SumOfNumbers(intarray);
}
}
I want to use "int....variable" instead of "Integer...variable" on my methods. I am assuming that I need to convert variable "intarray" to an int.
Please help I'm stuck on that part, thanks.
You can create a int array from your List by utilizing a for loop with autoboxing. Then you can change all the method signatures.
int[] intarray = new int[lnumber.size()];
for(int i = 0; i < intarray.length; i++)
intarray[i] = lnumber.get(i);
You can also use Streams.
int[] intarray = lnumber.stream().mapToInt(Integer::intValue).toArray();
You need to do the below steps to changes your program to from Integer to int...
Change parameter of DisplayNumbers(Integer...a) to DisplayNumbers(int...a)
Again change parameter of SumOfNumbers(Integer...a) to SumOfNumbers(int...a)
After that, you need to do some code changes in the main method. i.e. instead of
Integer[] intarray = new Integer[lnumber.size()];
intarray = lnumber.toArray(intarray);
you need to write
int[] intarray = lnumber.stream().mapToInt(i -> i).toArray();
Please find the complete program:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class MediumLevelExcercisesA {
Scanner number;
Scanner yorn;
public MediumLevelExcercisesA(){
}
static void DisplayNumbers(int[] a) {
for (int b = 0; b < a.length; b++) {
System.out.print(a[b]);
System.out.print(" ");
}
}
static void SumOfNumbers(int...a) {
int total = 0;
for (int b = 0; b < a.length; b++) {
total += a[b];
}
System.out.println(" ");
System.out.println("Sum: " + total);
}
public static void main(String[] args) {
MediumLevelExcercisesA obj01 = new MediumLevelExcercisesA();
List<Integer> lnumber = new ArrayList<Integer>();
boolean numbercounter = true;
while (numbercounter) {
obj01.number = new Scanner(System.in);
System.out.println("Please input a number");
int inputnumber = obj01.number.nextInt();
lnumber.add(inputnumber);
System.out.println("Number/s you've entered so far are the following: " + lnumber);
obj01.yorn = new Scanner(System.in);
System.out.println("Do you want to continue?");
String iyorn = obj01.yorn.nextLine().toUpperCase();
if (iyorn.equals("YES")||iyorn.equals("Y")) {
System.out.println("You've answered yes, program will proceed.");
}
else if (iyorn.equals("NO")||iyorn.equals("N")) {
System.out.println("You've answered no, program ends.");
numbercounter = false;
break;
}
else {
System.out.println("Answer not understood, program continues.");
}
} //end of while loop.
System.out.println("Final review of numbers entered: " + lnumber);
//Remove below two commented line because it is not need further
//Integer[] intarray = new Integer[lnumber.size()];
//intarray = lnumber.toArray(intarray);
// This can be used for if not java 8 compatible
/*int[] intarray = new int[lnumber.size()];
Integer[] temp = lnumber.toArray(new Integer[lnumber.size()]);
for (int n = 0; n < lnumber.size(); ++n) {
intarray[n] = temp[n];
}*/
//Java 8 and above
int[] intarray = lnumber.stream().mapToInt(i -> i).toArray();
MediumLevelExcercisesA.DisplayNumbers(intarray);
MediumLevelExcercisesA.SumOfNumbers(intarray);
}
}

Finding Twin Primes with Constructor

Just for fun, i wanted to see whether i could employ a code to display twin primes as practice for learning Constructors. I though i had used a good logic but for some reason i couldnt make it work.
This program is to print all twin primes(primes with 1 gap between them) till a given number as input by the user.
package X;
import java.io.*;
import java.util.*;
class TwinPrimeWithConstructor {
int limit;
public void Twin() {
limit = 0;
}
public static void input() {
Scanner input = new Scanner(System.in);
System.out.println("Enter Limit");
int limit = input.nextInt();
}
public void display() {
for (int k = 1; k <= (limit - 2); k++) {
int a = prime(k);
int b = prime(k + 2);
if (a == 1 && b == 1) {
System.out.println(k + "," + k + 2);
}
}
}
public int prime(int n) {
int c = 0;
int d = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
c = c + 1;
}
}
if (c == 2) {
d = 1;
return d;
} else {
return d;
}
}
void main() {
TwinPrimeWithConstructor ob = new TwinPrimeWithConstructor();
ob.input();
ob.display();
}
}
This program manages to correctly detect primes and asks for input,but does not give any output. Can someone make it clear to me? I'm still learning java so any help would be appreciated.
Also since im new, if you find any bad habits in my code, please feel free to tell me so i can become a better programmer.
You are not getting any output because this.limit is always 0:
int limit = Input.nextInt();
You should assign the input to your instance field rather than to a new local variable. To do this, the input method must not be static:
public void input() {
Scanner input = new Scanner(System.in);
System.out.println("Enter Limit");
limit = input.nextInt();
}

Why won't my program loop correctly?

I'm new to programming and I'm making a guessing game where the program randomly generates a number between 1 and 10, the user then is asked to guess what the number is, the user should be able to keep guessing until he guesses correctly and the system asks them if they want to play again,
In my code I've printed the number that the system has randomly generated so that it is quicker to complete the game whilst testing. When I try and execute the program and enter the number that the system has generated the message that they are correct and asking if they want to play again does not come up.
Any help would be greatly appreciated!
Thank you in advance,
(Also, anything wrong with this question just tell me, it's my first time asking on here)
Here is my code,
import java.util.Scanner;
import java.util.Random;
public class GuessingGame1 {
public static int randomizer() {
Random rand = new Random();
int num = rand.nextInt(10)+1;
System.out.println(num);
int count = 0;
return num;
}
public static int userInput() {
System.out.println("I've thought of a number between 1 and 10");
System.out.println("Enter your guess...");
Scanner scan = new Scanner(System.in);
int guess = scan.nextInt();
return guess;
}
public static String compare() {
int count = 0;
String result = null;
if (userInput() == randomizer()) {
System.out.println("You guessed it - I was thinking of " + randomizer());
count++;
result = "It took you " + count + " guesses.";
return result;
}
else if (userInput() > randomizer()) {
result = "Lower!";
count++;
return result;
}
else if (userInput() < randomizer()) {
result = "Higher";
count++;
}
return result;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scanLine = new Scanner(System.in);
String playAgain = "";
do {
randomizer();
do {
userInput();
compare
} while (userInput() != randomizer());
System.out.println("Play again? Yes/No");
playAgain = scanLine.nextLine();
} while (playAgain.equalsIgnoreCase("yes") || playAgain.equalsIgnoreCase("y"));
}
}
The problem is that you call twice to Randomizer!
call randomizer once as parameter to compare and return boolean from compare for a match.
You must change your methods something like this
public static String compare(int a,int b) {
int count = 0;
String result = null;
if (a == b) {
System.out.println("You guessed it - I was thinking of " + b);
count++;
result = "It took you " + count + " guesses.";
return result;
}
else if (a > b) {
result = "Lower!";
count++;
return result;
}
else if (a < b) {
result = "Higher";
count++;
}
return result;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scanLine = new Scanner(System.in);
String playAgain = "";
int a;
int b;
do {
do {
a=userInput();
b= randomizer();
System.out.println(compare(a,b));
} while (a != b);
System.out.println("Play again? Yes/No");
playAgain = scanLine.nextLine();
} while (playAgain.equalsIgnoreCase("yes") || playAgain.equalsIgnoreCase("y"));
}
}
you have left the () in compare and the count will always be zero as it is been initialized when the compare function is called.

How to determine why a Java program is not accepting 7 console inputs?

I have an application where you are supposed to enter 7 integers and then the application is supposed to tell you how many occurrences each number is put in.
Example: if I have 5 6 7 8 8 5 8, then it is supposed to come back that I have two 5's, one 6, one 7, and three 8's. All I'm getting out of it, however; is the first number i put in, in this case 5, and then it occurs 7 times. How do I fix this problem?
import java.util.Scanner;
public class U7A1_NumberCount {
public static void main(String[] args) {
final int MAX_INPUT_LENGTH = 7;
int[] inputArray = new int[MAX_INPUT_LENGTH];
System.out.print("Please, enter seven integers: ");
Scanner input = new Scanner(System.in);
int max = 0;
int nums = input.nextInt();
for(int n = 0; n < MAX_INPUT_LENGTH; n++) {
if(inputArray[n] > max) {
max = inputArray[n];
}
}
int[] count = new int[max + 1];
for(int n = 0; n < MAX_INPUT_LENGTH; n++) {
count[(inputArray[n])]++;
}
for(int n = 0; n < count.length; n++) {
if(count[n] > 0) {
System.out.println("The number " + nums + " occurs " + count[n] + " times.");
}
}
}
}
For input of the numbers, I would use something that can take many integers on a single line split by some delimiter. So basically, if the comma is the delimiter,
Scanner scan = new Scanner(System.in);
// some prompt here
List<Integer> intList = Stream.of(scan.nextLine().split(','))
.map(String::trim)
.map(Integer::new)
.collect(Collectors.toList());
Obviously, some more error handling could be useful (e.g. skipping things which cannot be parsed to an integer). You could also change your delimiter to be anything which is not a digit.
Then I would create a HashBag (for example, I will be using the implementation in Apache Commons Collections) and print the results with the bag's toString.
HashBag bag = new HashBag(intList);
System.out.println(bag.toString());
Or you could iterate through the HashBag to get and print the information you want.
Implementation of a HashBag-like object would be trivial: make a class backed with a HashMap<Object, Integer> and use some kind of adding method to call an Object#equals and if true, increment the value, and if false, create a new key with value 1.
Java is object oriented language, so use classess and objects to simplify your code. I would do it like that:
public class CountNumbers {
private Map<Integer,Integer> numbers = new HashMap<>();
public void addNumber(Integer number){
Integer howMany =numbers.get(number);
if( null != howMany){
howMany++;
}else{
howMany=1;
}
numbers.put(number,howMany);
}
public Map<Integer,Integer> getNumbers(){
return numbers;
}
}
public class Majn {
final static int MAX_INPUT_LENGTH = 7;
public static void main(String[] args) {
CountNumbers countNumbers = new CountNumbers();
System.out.print("Please, enter seven integers: ");
Scanner input = new Scanner(System.in);
for(int i = 0; i< MAX_INPUT_LENGTH; i++) {
int nums = input.nextInt();
countNumbers.addNumber(nums);
}
for(Integer number: countNumbers.getNumbers().keySet()){
System.out.format("The number %d occurs %d\n", number, countNumbers.getNumbers().get(number));
}
}
}
is the first number i put in, in this case 5, and then it occurs 7 times. How do I fix this problem?
You created an array to hold 7 integers, but you didn't utilise it. You only assigned value to another variable:
int nums = input.nextInt();
If you want to input all 7 inputs into the array, you can prompt the user n times:
for(int i=0; i<inputArray.length; i++)
inputArray[i] = input.nextInt(); //requires user to press enter 7 times
first at all, if you do not understand your code make it more readable ... this avoids a lot of problems simply in the beginning.
according to clean code of robert c. martin try to write down the code as you think about it. (https://de.wikipedia.org/wiki/Clean_Code)
here is one very reduced example to make it not to complicate
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class U7A1_NumberCount {
private static class NumberCount {
public NumberCount(final int number, final int amount) {
this.number = number;
this.amount = amount;
}
int amount;
int number;
}
public static void main(final String[] args) {
final int MAX_INPUT_LENGTH = 7;
final int[] userInput = readUserInput(MAX_INPUT_LENGTH);
final List<NumberCount> count = getNumberCount(userInput);
printResult(count);
}
private static NumberCount countSingleNumber(final int nr, final int[] userInput) {
int amount = 0;
for (int i = 0; i < userInput.length; i++) {
if (userInput[i] == nr) {
amount++;
}
}
return new NumberCount(nr, amount);
}
private static List<NumberCount> getNumberCount(final int[] userInput) {
final List<NumberCount> result = new LinkedList<>();
for (int i = 0; i < userInput.length; i++) {
final int nr = userInput[i];
if (isNumberNotConsideredYet(result, nr)) {
final NumberCount count = countSingleNumber(nr, userInput);
result.add(count);
}
}
return result;
}
private static int getUsersChoice(final Scanner scanner) {
System.out.print("Please, enter a number: ");
return scanner.nextInt();
}
private static boolean isNumberNotConsideredYet(final List<NumberCount> result, final int nr) {
return result.stream().noneMatch(count -> count.number == nr);
}
private static void printResult(final List<NumberCount> count) {
for (final NumberCount nr : count) {
System.out.println("The number " + nr.number + " occurs " + nr.amount + " times.");
}
}
private static int[] readUserInput(final int inputAmout) {
final Scanner scanner = new Scanner(System.in);
final int[] userInput = new int[inputAmout];
for (int i = 0; i < userInput.length; i++) {
userInput[i] = getUsersChoice(scanner);
}
scanner.close();
return userInput;
}
}

decimal to binary in java

I'm having trouble in getting the binary. I do not know what's wrong. The binary number always ends up in gibberish. Also some parts like the new int[31] thing was from HW but I can't get around to make print the actual binary.
public class DectoBinary {
public static void main(String[]args) {
Scanner CONSOLE = new Scanner(System.in);
System.out.print("Please enter a nonnegative integer: ");
int value = CONSOLE.nextInt();
while (value < 0) {
System.out.print("number outside range.");
System.out.print
("Please enter a nonnegative interger more than 0: ");
value = CONSOLE.nextInt();
}
int[] intArray = new int[31];
decimalToBinary(value, intArray);
System.out.println(value + "" + intArray);
}
public static int[] decimalToBinary(int value, int[]intArray) {
int i = 0;
while (value != 0) {
if (value % 2 == 1)
intArray[i] = 1;
else
intArray[i] = 0;
value /= 2;
i++;
}
return intArray;
}
}
I think the error is on this line:
System.out.println(value + "" + intArray);
You cannot print an array of integers like this: you should either convert it to string, or write a loop that prints the array digit by digit:
for (int i : inrArray) {
System.out.print(intArray[i]);
}
System.out.println();
You do not need to pass in the output array as well: you can create it inside the function.
public static int[] decimalToBinary(int value) {
int count = 1;
int tmp = value;
while (tmp != 0) {
tmp /= 2;
count++;
}
int[] intArray = new int[count];
// Do the conversion here...
return intArray;
}
You can simply use Integer.toBinaryString(int).
Actually the is a very simple way to get binary numbers in java using BigInteger
public String dectoBin(int num){
String s = ""+num;
BigInteger bi = new BigInteger(s);
String bin = bi.toString(2);
return bin
}
BigInteger.toString(2) returns the number stored on the numerical base specified inside the parenthesis. Is a very easy way to get arround this problems.
System.out.println(value + "" + intArray);
the 'intArray' is a arrays's address, so, if you want to get actual binary you can use Arrays.toString(intArray)
As dasblinkenlight you need to print the array item by item. If you want a nice alternative, you can use a recursive printing of value mod 2 (modulo 2 gives you 1 or 0)
/** print directly*/
public static void decimalToBinary(int value) {
if(value > 1){
System.out.print(decimalToBinary(value/2) + "" + (value%2));
/**recursion with implicit cast to string*/
} else {
System.out.print( (value==0)?"":"1");
}
}
It works with any Base
Well actually to print the array, because all the slots in the array are initialized at 0 you need to detect where the first one begins, so.
you need to replace
System.out.println(value + "" + intArray);
with something like this;
System.out.println(vale + " ");
boolean sw = false;
for(int i=0;i<intArray.length;i++){
if(!sw)
sw = (intArray[i]==1);//This will detect when the first 1 appears
if(sw)
System.out.println(intArray[1]); //This will print when the sw changes to true everything that comes after
}
Here is a program to convert Decimal nos. into Binary.
import java.util.Scanner;
public class decimalToBinary {
static int howManyTerms (int n) {
int term = 0;
while (n != 0) {
term ++;
n /= 2;
}
return term;
}
static String revArrayofBin2Str (int[] Array) {
String ret = "";
for (int i = Array.length-1; i >= 0; i--)
ret += Integer.toString(Array[i]);
return ret;
}
public static void main (String[] args) {
Scanner sc=new Scanner (System.in);
System.out.print ("Enter any no.: ");
int num = sc.nextInt();
int[] bin = new int[howManyTerms (num)];
int dup = num, el = -1;
while (dup != 0) {
int rem = dup % 2;
bin [++el] = rem;
dup /= 2;
}
String d2b = revArrayofBin2Str(bin);
System.out.println("Binary of " + num + " is: " + d2b);
}
}
This is simple java code for decimal to binary using only primitive type int, hopefully it should help beginners.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class DtoB {
public static void main(String[] args) {
try { // for Exception handling of taking input from user.
System.out.println("Please enter a number");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
int x = Integer.parseInt(input);
int bin = 0;
int p = 1;
while (x > 0) {
int r = x % 2;
bin = (r * p) + bin;
x = x / 2;
p *= 10;
}
System.out.println("Binary of " + input + " is = " + bin);
} catch (Exception e) {
System.out.println("Please enter a valid decimal number.");
System.exit(1);
e.printStackTrace();
}
}
}

Categories