I seems like I cant skip over the while loop as my code does not understand that I typed in the right number.
import java.util.Scanner;
public class HelloWorld1{
static Scanner userInput = new Scanner(System.in);
static int randomNumbe
public static void main(String[] args){
System.out.println(randomNum());
int randomGuess = -1 ;
while(randomGuess != randomNum()){
System.out.println("Guess a number between 0 to 100");
randomGuess = userInput.nextInt();
}
System.out.println("Yes the random number is:" + randomGuess);
}
public static int randomNum(){
randomNumber = (int) (Math.random()*101);
return randomNumber;
}
}
When you call randomNum(), you're getting another random value back. Try:
int expected = randomNum();
System.out.println(expected);
int guess = -1;
while(guess != expected) {
...
}
package randomguess;
import java.util.Scanner;
public class RandomGuess {
/**
* #param args the command line arguments
*/
static int randomNumber = 0;
public static int getRandomInt() {
randomNumber = (int) (Math.random()*101);
return randomNumber;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int guessInt = sc.nextInt();
int randomInt = getRandomInt();
while(guessInt != randomInt) {
System.out.println("Better luck nextTime :D Random number was "+randomInt);
guessInt = sc.nextInt();
randomInt = getRandomInt();
}
System.out.println("Yeah! You are oracle!");
}
}
Here is probably what you want. Let me know if it is.
Related
I started learning JAVA a couple of days ago, so my question might be too basic.
I have created a piece of code which is as follows:
import java.util.Scanner;
public class Que01 {
public static void main(String[] args) {
int principle=acceptInt("Principle");
int roi=acceptInt("Rate Of Interest");
int years=acceptInt("Years");
float si=simpleInterest(principle,roi,years);
System.out.println("Simple Interest for given details is : "+si);
}
static int acceptInt(String s1)
{ System.out.println("Please Enter value for "+s1+" :");
Scanner sc = new Scanner(System.in);
int i= sc.nextInt();
return i;
}
static float simpleInterest(int p,int r, int yr)
{
return p*yr*r/100;
}
}
I want to know where should I write:
sc.close();
Also:
Any other suggestion to code for improvement are Welcome!
You should not close the scanner do not worry about that it will terminated after calculating the simpleInterest. When you run the program and after entering required values it will calculate and return the result and quit.
In you code 1 improvement is you should not create Scanner object again and again there should be only 1 object of Scanner throughout the life cycle.
Below is your updated code -
public class Que01 {
private static Scanner sc = null;
public static void main(String[] args) {
sc = new Scanner(System.in);
int principle=acceptInt("Principle");
int roi=acceptInt("Rate Of Interest");
int years=acceptInt("Years");
float si=simpleInterest(principle,roi,years);
System.out.println("Simple Interest for given details is : "+si);
}
static int acceptInt(String s1)
{ System.out.println("Please Enter value for "+s1+" :");
int i= sc.nextInt();
return i;
}
static float simpleInterest(int p,int r, int yr)
{
return p*yr*r/100;
}
}
Create Scanner on start of the program and use it again and again. thats it
hope this will help you.
Thanks to Vince, I was able to create a good version of my code.
and this is the answer I needed.
public class Que01 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int principle=acceptInt(sc,"Principle");
int roi=acceptInt(sc,"Rate Of Interest");
int years=acceptInt(sc,"Years");
sc.close();
float si=simpleInterest(principle,roi,years);
System.out.println("Simple Interest for given details is : "+si);
}
static int acceptInt(Scanner sc,String s1)
{ System.out.println("Please Enter value for "+s1+" :");
int i= sc.nextInt();
return i;
}
static float simpleInterest(int p,int r, int yr)
{
return p*yr*r/100;
}
}```
import java.util.Scanner;
public class Que01 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int principle = acceptInt("Principle", false, sc);
int roi = acceptInt("Rate Of Interest", false, sc)
int years = acceptInt("Years", true, sc);
float si = simpleInterest(principle, roi, years);
System.out.println("Simple Interest for given details is : " + si);
}
static int acceptInt(String s1, boolean closeScanner, Scanner sc) {
System.out.println("Please Enter value for " + s1 + " :");
int i = sc.nextInt();
if (closeScanner)
sc.close();
return i;
}
static float simpleInterest(int p, int r, int yr) {
return p * yr * r / 100;
}
}
i am not sure if this is a good practice of passing boolean as parameter to decide to close scanner
import java.util.Scanner;
public class Que01 {
Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int principle = acceptInt("Principle");
int roi = acceptInt("Rate Of Interest");
int years = acceptInt("Years");
float si = (p * yr * r/100);
System.out.println("Simple Interest for given details is : " + si);
}
static int acceptInt(String s1) {
System.out.println("Please Enter value for " + s1 + " :");
int i = sc.nextInt();
sc.close();
return i;
}
}
This is what I would say but I'm not an expert. sc.close just saves anything you did with the scanner, eg. writing to a file and saving the file. - thus in this scenario I wouldn't even use it. I also wouldn't use a method to calc the si unless you plan to use it elsewhere as it's just taking up more space
I am suppose to write a java program where I ask user how many math questions they want to answer and generate random questions based on their answer using any loop of choice and keep a count of how many they answered correct. I got it to generate the random math problem, but it only does it once it seems to be skipping the loop. Can anyone help?
import javax.swing.JOptionPane;
import java.util.Random;
import java.util.Scanner;
/**
*
* #author user
*/
public class MathQuiz {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random obj = new Random();
int num1 = obj.nextInt(10);
int num2 = obj.nextInt(10);
int rand = num1 + num2;
String response = JOptionPane.showInputDialog(null,"How many problems would you like to solve?");
int ans = Integer.parseInt(response); // answer from question
String result= null;
int times = input.nextInt();
int counter = 0; //counts total math problems
while (counter != ans){
counter++;
JOptionPane.showInputDialog(num1 + "+" +num2);
if (ans == rand){
result= "Correct";
}else {
result= "Incorrect";
}
} JOptionPane.showMessageDialog(null, );
}
}
Here are the problems in your code:
You are not displaying the result after you compute the value.
Not generating the random numbers every time.
public class MathQuiz {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String response = JOptionPane.showInputDialog(null,"How many problems would you like to solve?");
int noOfTimes = Integer.parseInt(response); // answer from question
String result= null;
for (int counter = 0; counter < noOfTimes; counter++) {
Random obj = new Random();
int num1 = obj.nextInt(10);
int num2 = obj.nextInt(10);
int rand = num1 + num2;
int answer = Integer.parseInt(JOptionPane.showInputDialog(num1 + "+" +num2));
if (answer == rand){
result= "Correct";
}else {
result= "Incorrect";
}
JOptionPane.showMessageDialog(null, result);
}
}
}
The number you get inside of the loop should not be stored in the same variable as the one you use in your while(...) condition. In this case, you used ans. In the example below I have separate variables for the math answer and the number of times to iterate in the loop. Another problem you had is that you were not passing the result message to the showMessageDialog(..) method.
import javax.swing.JOptionPane;
import java.util.Random;
import java.util.Scanner;
public class MathQuiz {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random obj = new Random();
String timesString = JOptionPane.showInputDialog(null,"How many problems would you like to solve?");
int timesInt = Integer.parseInt(timesString); // answer from question
int counter = 0; //counts total math problems
while (counter != timesInt) {
counter++;
int num1 = obj.nextInt(10);
int num2 = obj.nextInt(10);
int rand = num1 + num2;
String answerString = JOptionPane.showInputDialog(num1 + "+" +num2);
int answerInt = Integer.parseInt(answerString);
JOptionPane.showMessageDialog(null, answerInt == rand ? "Correct" : "Incorrect");
}
}
}
I have written a java code to convert decimal number to binary.Its works well but when input is 1024 or more output goes wrong.Ex: if input is 1024 output is 1410065408.
import java.util.Scanner;
public class story {
public static void main(String args[])
{
Scanner scan=new Scanner(System.in);
System.out.println("Enter a positive decimal number");
binary bin=new binary();
System.out.println(bin.calculate(scan.nextInt()));
}
}
public class binary {
public long calculate(int num)
{
int i=1;
long result=0;
while(num>0)
{
result=result+(num%2)*i;
i*=10;
num/=2;
}
return result;
}
}
You are facing this issue because the datatype of i is int which is Overflowing.
The solution is to simply change the datatype of i from int to long.
Here is the corrected code snippet:
public static final class binary {
public long calculate(int num) {
long i = 1; //Note the change at this line
long result = 0;
while (num > 0) {
result = result + (num % 2) * i;
i *= 10;
num /= 2;
}
return result;
}
}
Input:
1024
Output:
10000000000
Error is in type i, it should be long.
CODE:
import java.util.Scanner;
public class story {
public static void main(String args[])
{
Scanner scan=new Scanner(System.in);
System.out.println("Enter a positive decimal number");
System.out.println(calculate(scan.nextInt()));
}
public static long calculate(int num)
{
long i=1;
long result=0;
while(num>0)
{
result=result+(num%2)*i;
i*=10;
num/=2;
}
return result;
}
}
OUTPUT:
Enter a positive decimal number
1026
10000000010
The "i" variable goes past maximum integer value for inputs 1024 and above..
Refer here : Why 10000000*1000 giving 1410065408 in java?
I have to basically make a program that would add a name given a prompt and place it in the array. It should do the same for the age of the person. I have been forced to do this with methods. The only issue i am having is that with the 3rd last line, the name get's asked twice. I don't know how to fix that. Any help is appreciated.
public class Testing1 {
public static int[] ageinput(String names[], int q2){
int holderage[] = new int[q2];
for(int x = 0; x<q2;x++) {``
System.out.println("Please input the age of " + names[x]);
Scanner age = new Scanner(System.in);
int a1 = age.nextInt();
holderage[x] = a1;
}
return holderage;
}
public static String[] nameinput(int q2){
String holdername[] = new String[q2];
for (int x = 0; x<q2;x++) {
System.out.println("Please input the name of the person");
Scanner name = new Scanner(System.in);
String n1 = name.nextLine();
holdername[x]=n1;
}
return holdername;
}
public static void output(String names[], int ages[]){
for(int x = 0; x<names.length;x++){
System.out.println(names[x]+" is "+ages[x]+" years old");
}
}
public static void main(String[] args) {
System.out.println("How many names do you want to input?");
Scanner question = new Scanner(System.in);
int q1 = question.nextInt();
output(nameinput(q1),ageinput(nameinput(q1),q1));
}
}
In output(nameinput(q1),ageinput(nameinput(q1),q1)); you call the method nameinput twice, so the code also will be executed twice.
You could ask the names in nameinput, store them into an array and pass that array to ageinput.
#Aadithya Gowthaman, try this one in your editor.
package com.aamir;
import java.util.Scanner;
public class Testing1 {
public static int[] ageinput(String names[], int q2){
int holderage[] = new int[q2];
for(int x = 0; x<q2;x++) {
System.out.println("Please input the age of " + names[x]);
Scanner age = new Scanner(System.in);
int a1 = age.nextInt();
holderage[x] = a1;
}
return holderage;
}
public static String[] nameinput(int q2){
String holdername[] = new String[q2];
for (int x = 0; x<q2;x++) {
System.out.println("Please input the name of the person");
Scanner name = new Scanner(System.in);
String n1 = name.nextLine();
holdername[x]=n1;
}
return holdername;
}
public static void output(String names[], int ages[]){
for(int x = 0; x<names.length;x++){
System.out.println(names[x]+" is "+ages[x]+" years old");
}
}
public static void main(String[] args) {
System.out.println("How many names do you want to input?");
Scanner question = new Scanner(System.in);
int q1 = question.nextInt();
String [] namesArray = nameinput(q1);
int [] ageArray = ageinput(namesArray, q1);
output(namesArray, ageArray);
}
}
I'm trying to make a quiz type game and for some reason when I add the if statement below it executes the ask method twice. You will get asked the question twice before it returns whether it is correct or not.
import java.util.Scanner;
public class QuizGame
{
private int correct;
private int wrong;
private Scanner inputScan;
private Quiz customQuiz;
public QuizGame()
{
correct=0;
wrong=0;
inputScan = new Scanner(System.in);
}
private void startQuiz()
{
System.out.println("Use custom upper limit? (y/n) ");
String custom = inputScan.next();
if(custom.equalsIgnoreCase("y"))
{
System.out.println("What do you want to be your upper limit?");
int limit = inputScan.nextInt();
customQuiz = new Quiz(limit);
customQuiz.ask();
if(customQuiz.ask())
{
correct +=1;
System.out.println("Correct!");
}
else
{
wrong+=1;
System.out.println("Wrong!");
}
}
}
public static void main(String[] args)
{
QuizGame quiz1 = new QuizGame();
quiz1.startQuiz();
}
}
other class that asks the questions:
import java.util.Random;
import java.util.Scanner;
public class Quiz
{
private Random rGen;
private int num1;
private int num2;
private Scanner getInput;
private int answer;
public Quiz(int n1)
{
rGen = new Random();
num1 = rGen.nextInt(n1);
num2 = rGen.nextInt(n1);
getInput = new Scanner(System.in);
}
public boolean ask()
{
int answer = num1 * num2;
System.out.println("What is " + num1 + " x " + num2);
int userAnswer = getInput.nextInt();
return answer == userAnswer;
}
}
I isolated the problem and it definitely seems to be the if statement: if(customGame.ask()) {} in the driver class, but I don't see why. It's not like if(customGame.ask()) calls the ask method again, it just tests if it returns true? I've also tried with just if(customGame.ask() == true) and still nothing.
Well, you are calling customQuiz.ask() twice :
customQuiz.ask();
if (customQuiz.ask ())
{
correct += 1;
System.out.println ("Correct!");
}
Simply call it just once :
if (customQuiz.ask ())
{
correct +=1;
System.out.println ("Correct!");
}
Or (as suggested by #RobertHarvey) you can put the result of the method in a variable and use it later :
boolean correct = customQuiz.ask ();
if (correct)
{
correct += 1;
System.out.println ("Correct!");
}