I wanted to write a small quiz with an int calculation, but I can not get it to run.
import java.util.Scanner;
public class Quiz {
public static void main(String[]args) {
Scanner scan = new Scanner(System.in);
int a = 4;
int b = 4;
String in;
in= scan.nextLine();
System.out.println("What is 4+4?");
if (in.equals (a+b)) {
System.out.println("Correct");
}else {
System.out.println("Wrong");
}
}
}
You can use scan.nextInt(); to accept int values,
Scanner scan = new Scanner(System.in);
int a = 4;
int b = 4;
int in= scan.nextInt();
System.out.println("What is 4+4?");
if (in == (a+b)) {
System.out.println("Correct");
}else {
System.out.println("Wrong");
}
First of all why would you add two numbers when you can keep one number in a variable as the expected result. The input expects a String so you can either change it to int or say String.valueOf(expected result)
int in= scan.nextInt();
Scanner scan = new Scanner(System.in);
final int a = 8;
System.out.println("What is 4+4?");
String in= scan.nextLine();
if (in.equals(String.valueOf(a))) {
System.out.println("Correct");
}else {
System.out.println("Wrong");
}
}
}
Although others suggest using Scanner#nextInt I wouldn't recommend it. It has some kind of nonintuitive behavior and causes harm when used by programmers who are new to Java when trying to read first number, the operator and the second number.
As the OP is already familiar with Scanner#nextLine I would suggest the following approach:
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
String b = sc.nextLine();
int first = Integer.parseInt(a);
int second = Integer.parseInt(b);
int result = first+second;
To design such quiz, I would suggest going a bit further:
public static void main(String[] args) {
Random random = new Random();
Scanner sc = new Scanner(System.in);
int a = random.nextInt(100);
int b = random.nextInt(100);
System.out.println(String.format("What is the result of %d + %d", a, b));
String answer = sc.nextLine();
try {
int result = Integer.parseInt(answer);
if (result == a+b) {
System.out.println("Correct");
} else {
System.out.println("Wrong");
}
} catch (NumberFormatException e) {
System.out.println(answer + " - is not a valid number");
}
}
You need to convert the String value of the the scanner to an int, you can use scan.nextInt() as well but this can lead to problems later with the scanner not progressing to the next line after the int. You also need to order it correctly otherwise it'll ask for input before the question is asked. See below, hope it helps.
import java.util.Scanner;
public class Quiz {
public static void main(String[]args) {
Scanner scan = new Scanner(System.in);
int a = 4;
int b = 4;
int in;
System.out.println("What is 4+4?");
in = Integer.valueOf(scan.nextLine());
if (in == (a+b)) {
System.out.println("Correct");
}else {
System.out.println("Wrong");
}
}
}
String in = scan.nextLine();
if (in.equals(String.valueOf(a+b))) {
System.out.println("Correct");
}else {
System.out.println("Wrong");
}
Or use Integer.toString(a+b) or "" + (a + b)
Or change Integer in = scan.nextInt()
Related
I am trying to calculate the percentage of valid inputs of words.
I'm stuck and every method I've tried doesn't work. I was starting learning java two months ago,so i am new in this and i am not shure if I have done the right code.
Could someone give me some advice on how to word it.Thanks in Advance
public class Subject3
{
public static void main (String[]args) {
Scanner scan = new Scanner(System.in);
//Creating scanner object
boolean valid = true;
int numOfStrings=0;
do {
valid = true;
System.out.print("How many strings?: ");
try{
numOfStrings = Integer.parseInt(scan.nextLine());
}catch (NumberFormatException e){
System.out.println("Not a word");
valid = false;
}
}while (!valid);
String[] stringPali = new String [numOfStrings];
String input;
for (int i=1; i<numOfStrings+1 ; i++) {
do {
valid = true;
System.out.print("Enter string no." +i );
System.out.print(":");
input = scan.nextLine();
if (!input.matches("[A-Za-z0-9]+")){
System.out.println("Not a word");
}
}while (!valid);
}
System.out.println("Results");
System.out.println("Total number of strings: "+ numOfStrings);
System.out.println("Percentage of words:" +(percentage)("%"));
System.out.println("Words starting with capital letter: "+("%"));
}
}
System.out.println("Not a word"); this meesage is wrong. it should be not a number.
You created an array stringPali but never used it? why?
loops starting with 1 is confusing. But it's up to you.
You should first add the words to the array finally you can count.
You need the full user input to calculate percentage. So no point of counting valid strings while user is still entering input. Do it at the end.
You can use regex to match the strings that only contain letters and the strings that start with a capital letter.
import java.util.Scanner;
public class ExampleCase {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//Creating scanner object
boolean valid = true;
int numOfStrings = 0;
do {
valid = true;
System.out.print("How many strings?: ");
try {
numOfStrings = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
System.out.println("Not a number");
valid = false;
}
} while (!valid);
String[] stringPali = new String[numOfStrings];
for (int i = 0; i < numOfStrings; i++) {
System.out.print("Enter string no." + i);
System.out.print(":");
String input = scan.nextLine();
stringPali[i] = input;
}
System.out.println("Results");
System.out.println("Total number of strings: " + numOfStrings);
int validStringCount = countStrings(stringPali, "^[a-zA-Z]*$");
double percentage = (double) validStringCount / numOfStrings;
System.out.println(String.format("Percentage of words: %f%%", percentage));
int startWithCapitalCount = countStrings(stringPali, "^[A-Z].*");
percentage = (double) startWithCapitalCount / numOfStrings;
System.out.println(String.format("Words starting with capital letter: %f%%", percentage));
}
private static Integer countStrings(String[] stringPali, String pattern) {
int count = 0;
for (String str : stringPali) {
if (str.matches(pattern)) {
count++;
}
}
return count;
}
}
Im struggling with that code.
how can I use string with yes/no on that question: n1>n2, n1<n2.
the operators also need to change.
import java.util.Scanner;
import java.util.Random;
public class s {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Random r = new Random();
int n1 = r.nextInt(10) + 1;
int n2 = r.nextInt(10) + 1;
int max = Math.max(n1, n2);
System.out.println("What is higher: "+n1+" or "+n2+" ");
int result = s.nextInt();
if(result==max)
System.out.println("Well done");
else
System.out.println("Wrong answer");
}
}
I tried a way to not use a lot of IF’S by splitting the two possible cases and not having many repeated coding lines.
By avoiding this situation, I started creating: random numbers, the random operator “>” or “<” and a boolean variable which value depends on the answer of the user.
Then I defined a variable called “reality” that will provide the correct answer, referring to which number is bigger or smaller than the other.
Finally, the program verifies if the answer of the user is the same to the reality printing the expected answer.
public static void main(String[] args) {
int bol_op= (int) Math.random()>0.5?1:0;
String operator= bol_op==1?">":"<";
int num1=(int) (Math.random()*100+1);
int num2=(int) (Math.random()*222+1);
String str_num1=num1+"";
String str_num2=num2+"";
Scanner sc= new Scanner(System.in);
System.out.println("********Logic Program**********");
System.out.println("Question: "+str_num1+operator+str_num2);
System.out.print("Answer (yes/no): ");
String answer =sc.nextLine().toLowerCase();
boolean value=false;
if(answer.equals("yes")){
value=true;
}
boolean reality=num1>num2?true:false;
if(bol_op==0){
reality=num1<num2?true:false;
}
if(reality==value){
System.out.println("Well done");
}
else{
System.out.println("Wrong answer");
}
}
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.
my teacher asked us to create an additive prime program for my computer science class. I have created all my void methods, and believe to have all the math logic figured out. However, when I try to pass arguments into the instances of my methods within my main method, It gives me an error saying:
it can not find the variable in this case variable 'x'
package additiveprimes;
import java.util.Arrays;
import java.util.Scanner;
/**
*
* #author talarik048
*/
public class AdditivePrimes {
public static void main(String[] args){
AdditivePrimes additivePrime = new AdditivePrimes();
additivePrime.userInput(x);
additivePrime.isPrime(x);
additivePrime.numArray(x);
}
public void userInput(String x){
Scanner sc = new Scanner(System.in);
try{
System.out.println("Please enter a number: ");
x = sc.nextLine();
} catch(NumberFormatException e){
System.out.println("Error, try again: ");
x = sc.nextLine();
}
}
public void isPrime(String x){
this.userInput(x);
boolean prime = true;
int y = Integer.parseInt(x);
for(int i = 0; i < y; i++){
if(y % i == 0){
prime = false;
break;
}
if(prime){
System.out.println("Your number is prime...");
} else {
System.out.println("Your number is not prime...");
}
}
}
public void numArray(String x){
this.userInput(x);
String[] strArray = x.split("\\s+");
boolean prime = true;
int[] numbArray = new int[strArray.length];
for(int j = 0; j < strArray.length; j++){
try{
numbArray[j] = Integer.parseInt(strArray[j]);
} catch(NumberFormatException e){
System.out.println("ERROR");
}
for(int i = 0; i < numbArray.length; i++){
int sum = (Arrays.stream(numbArray).sum());
if(sum % i == 0){
prime = false;
break;
}
if(prime){
System.out.println("Your number is an additive prime...");
} else {
System.out.println("Your number is not an additive prime...");
}
}
}
}
}
I think you wanted to RETURN a value from userInput:
public static void main(String[] args){
AdditivePrimes additivePrime = new AdditivePrimes();
String x = additivePrime.userInput();
additivePrime.isPrime(x);
additivePrime.numArray(x);
}
public String userInput(){
Scanner sc = new Scanner(System.in);
String x = null;
try{
System.out.println("Please enter a number: ");
x = sc.nextLine();
} catch(Exception e){// see OH GOD SPIDERS comment
System.out.println("Error, try again: ");
x = sc.nextLine();//this is not a good way for a retry
}
return x;
}
Alternatively you could make x a field.
Your methods accept a string as an argument, but you have not passed any. You need to initialize x in main.
public static void main(String[] args){
AdditivePrimes additivePrime = new AdditivePrimes();
String x= "55";
additivePrime.userInput(x);
additivePrime.isPrime(x);
additivePrime.numArray(x);
}
Note
Although the above code fixes your current issue. It doesn't seem to be the correct way to use this class. You should probably be calling .userInput() method and getting the userInput then passing it to your other methods.
You could probably change your overall class to
public static void main(String[] args){
AdditivePrimes additivePrime = new AdditivePrimes();
String x = additivePrime.userInput();
additivePrime.isPrime(x);
additivePrime.numArray(x);
}
public String userInput(){
Scanner sc = new Scanner(System.in);
String x = null;
try{
System.out.println("Please enter a number: ");
x = sc.nextLine();
} catch(NumberFormatException e){
System.out.println("Error, try again: ");
x = sc.nextLine();
}
return x;
}
You have not defined x as anything before using it. Try defining x. In this case since your arguments are strings, I recommend...
String x = new String();
I'm new to java and this forum. I wrote a code for a simple calculator. It's working. But how can I repeat the main method if I (let's say) put "=" instead of "(+, -, *, /)"? Should I use a loop, or something else? Thanks in advance!
import java.util.Scanner;
public class SimCal {
public static int add(int a, int b) {
return a + b;
}
public static int sub(int a, int b) {
return a - b;
}
public static int mul(int a, int b) {
return a * b;
}
public static int div(int a, int b) {
return a / b;
}
public static void main(String[] args) {
Scanner scan1 = new Scanner(System.in);
System.out.println("What do you want to do (+, -, *, /)? ");
String input1 = scan1.nextLine();
if (!input1.equals("+") && !input1.equals("-") && !input1.equals("*") && !input1.equals("/")) { // if wrong input given
System.out.println("You must Enter a valid operator");
} else {
Scanner scan2 = new Scanner(System.in);
System.out.println("Enter first number: ");
int input2 = scan2.nextInt();
Scanner scan3 = new Scanner(System.in);
System.out.println("Enter second number: ");
int input3 = scan3.nextInt();
if (input1.equals("+")) {
System.out.println(add(input2, input3));
} else if (input1.equals("/")) {
System.out.println(div(input2, input3));
} else if (input1.equals("-")) {
System.out.println(sub(input2, input3));
} else {
System.out.println(mul(input2, input3));
}
scan1.close();
scan2.close();
scan3.close();
}
}
}
I am a bit unsure of what you are asking, but I understood it that you want to be able to repeat the calculator without having to run it again. This can be achieved by using a boolean and a while block.
Here is an example:
import java.util.Scanner;
public class SimCal {
public static int add (int a, int b){
return a+b;
}
public static int sub (int a, int b){
return a-b;
}
public static int mul (int a, int b){
return a*b;
}
public static int div (int a, int b){
return a/b;
}
public static boolean done = false;
public static void main(String[] args){
Scanner scan1 = new Scanner(System.in);
Scanner scan2 = new Scanner(System.in);
Scanner scan3 = new Scanner(System.in);
while (!done) {
System.out.println("What do you want to do (+, -, *, /, quit)? ");
String input1 = scan1.nextLine();
if (!input1.equals("+") && !input1.equals("-") && !input1.equals("*") && !input1.equals("/") && !input1.equals("quit"))
{ //if wrong input given
System.out.println("You must Enter a valid operator");
}
else if (input1.equals("quit"))
{
done = true;
scan1.close();
scan2.close();
scan3.close();
}
else
{
System.out.println("Enter first number: ");
int input2 = scan2.nextInt();
System.out.println("Enter second number: ");
int input3 = scan3.nextInt();
if (input1.equals("+"))
{
System.out.println(add(input2, input3));
}
else if (input1.equals("/"))
{
System.out.println(div(input2, input3));
}
else if (input1.equals("-"))
{
System.out.println(sub(input2, input3));
}
else
{
System.out.println(mul(input2, input3));
}
}
}
}
}
I hope this is helpful. Like Andy Turner mentioned, you should try to not use multiple scanners.
EDIT: I forgot to close 2 scanners. Also, switch cases can be a better way of doing this, like mentioned by Saurav Sahu.