Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Given this requirement
Create a code which creates random number and ask user to make 2 guess and then print out the actual number and also state which one of your guess was closest
I am stuck at the last part. Please help.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package selectionexercises;
/**
*
*
* #author jhonpaul
*/
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("I have picked a number between 1 to 100 try to guess it.");
int randomNumber = (int) (Math.random() * 100 + 1);
System.out.println("Enter Your First Guess.");
int guess1;
guess1 = sc.nextInt();
System.out.println("Enter Your Second Guess.");
int guess2;
guess2 = sc.nextInt();
System.out.println("The number was " + randomNumber);
int range;
range = randomNumber;
}
}
Use Math.min(Math.abs(randomNumber-guess1), Math.abs(randomNumber-guess2))
Do something like this:
//Calculate difference and use absolute value (turn negative values into positive if necessary)
int difference1 = Math.abs(randomNumber - guess1)
int difference2 = Math.abs(randomBumber - guess2)
//Compare result
if(difference1<difference2) {
System.out.println("Guess1 was closer");
} else if (difference1>difference2) {
System.out.println("Guess2 was closer");
} else {
System.out.println("Both were equally close!");
}
There are shorter ways than this but scince you are a starter I think this is an understandable and easy to use way.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 months ago.
Improve this question
package Fare;
import java.util.Scanner;
public class fare {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(" Enter Class ");
System.out.println(" a. Senior b. Student c. Regular ");
System.out.println("Enter class : ");
int num = input.nextInt();
if (num = 1) {
double fare = 9 * 0.10;
System.out.println("Your fare will be " + fare + "▒. Thank you.");
}
else if (num = 2 ) {
double fare = 9 * 0.08;
System.out.println("Your fare will be " + fare + "▒. Thank you.");
}
else {
System.out.println("your fare will be 9▒. Thank you.");
}
}
}
Hi i can't seem to understand why there is an error in my if statement stating that it cannot convert int to boolean. I have already checked it and still can find any problem or mybe i just don't know.
You should change if(num=1) to if(num==1) and if else(num=2) to if else(num==2).
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am learning java and I want to create a command-line application that calculates exam percentages based on marks obtained. But the problem is I don't have the idea to set the range of marks obtained while the marks range is between 0 to 100.
Below is the code, I have tried: -
package com.company;
import java.util.*;
public class CbseCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter marks obtained of Physics");
float physics = sc.nextFloat();
System.out.println("Enter marks obtained of Chemistry");
float chemistry = sc.nextFloat();
System.out.println("Enter marks obtained of Math");
float math = sc.nextFloat();
System.out.println("Enter marks obtained of English");
float english = sc.nextFloat();
System.out.println("Enter marks obtained of Computer Science");
float computer = sc.nextFloat();
float total = 500;
float obtained = (physics + chemistry + math + english + computer);
float percentage = (obtained/total)*100;
System.out.println("The percentage obtained is: "+percentage);
sc.close();
}
}
It is not a good idea to try to get Scanner to do that1.
Instead, you should use Scanner to read an int and then test the result that it gives you to check that it is in the correct range. Something like this:
int number;
if (myScanner.hasNextInt()) {
number = myScanner.nextInt();
if (number < 0 || number > 100) {
// handle case where the number is out of range
}
} else {
// handle case where the input is not an integer
}
I will leave it to you to figure out how to map the above onto your application's requirements.
1 - The standard Scanner class doesn't provide a method that reads a number in a given range (and rejects numbers outside of that range). You could conceivably extend the Scanner class with this functionality, but it would be difficult. There are simpler solutions.
I would suggest you to write a function to get a valid input as below :-
public int getValidInput(Scanner in, int range) {
while (in.hasNext()) {
if (in.hasNextInt()) {
int val = in.nextInt();
if (val >= 0 && val < range) { // <-- from "0" to "range".
return val;
}
} else {
in.next();
}
}
return -1;
}
This function is ensuring that the input is given as an integer only and it lies in the range o to range. You can change it as per your requirement.
Consider this method:
static int getMark(String course){
int mark = 0;
boolean valid = true;
Scanner sc = new Scanner(System.in);
System.out.println("Enter marks obtained of " + course + ": ");
while(valid){
mark = sc.nextInt();
if(mark < 0 || mark > 100){
System.out.println("Mark must be between 0-100");
} else {
valid = true;
}
}
sc.close();
return mark;
}
This way you can get two birds with one stone, leaving the resulting code as this:
public static void main(String[] args){
int physics = getMark("Physics");
int chemistry = getMark("Chemistry");
int math = getMark("Math");
int english = getMark("English");
int computer = getMark("Computer Science");
float total = 500;
float obtained = (physics + chemistry + math + english + computer);
float percentage = (obtained / total) * 100;
System.out.println("The percentage obtained is: " + percentage);
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
My code does not currently compile, I know that it is due to a lack of a return for my constructor- but if I could please get some help (as I have a version that I have already tried to fix), it would greatly be appreciated.
I have 2 files, one that has a constructor, and one that accesses that constructor. I should also note, that all of the help I found online said that I have to use an if else statement, but that leads to more errors.
My code for the main file:
import java.util.Scanner;//importing scanner
public class QuestionTwo {
public static void main(String[] args) {
int numberofDays;//these two lines define variables
int sharePoints;
Scanner keyboard = new Scanner(System.in);//activating scanner
System.out.print("Number of days in the period: ");//asking question
numberofDays = keyboard.nextInt();//obtaining input by defining a variable as a keyboard input
System.out.print("Share points on the first day: ");//asking another question
sharePoints = keyboard.nextInt();//obtaining input by defining a variable as a keyboard input
while (numberofDays < 10 || numberofDays > 20)
{
System.out.println("The number of days doesn’t meet the required criteria, enter it again");
System.out.print("Number of days in the period: ");
numberofDays = keyboard.nextInt();
}
SharePattern share = new SharePattern(numberofDays, sharePoints);
SharePattern.outPutTablePrinter(numberofDays, sharePoints);
//above two lines print day and share points, as well as the first line
of text (as it does not change)
}
}
Here is the code for the constructor (the one with the return error):
public class SharePattern {
private static int days;
private static int share;
public SharePattern(int numberofDays, int sharePoints)//constructor
{
numberofDays=days;
sharePoints=share;
}
public static int outPutTablePrinter(int numberofDays,int sharePoints){
for (int i = 2; i <= days; i++) {
if (days % 2 == 0)
if (i <= days / 2) {
share = share + 50;
} else {
share = share - 25;
} else {
if (i <= days / 2 + 1) {
share = share + 50;
} else {
share = share - 25;
}
}
}
System.out.println("The share points on the final day would be: "+share);
}
}
}
Any help would be appreciated, as I've been working on this problem all day and finally got finished when I came upon this problem.
First, you have an else {} else, which isn't valid
Not really clear which you're trying to accomplish..
Option 1
Remove the constructor and the static fields. You never use share variable.
Make your outPutTablePrinter method use the parameters you passed to it. And that method doesn't return anything. It's printing a value. Make it public static void
Option 2
If you want to keep the constructor, you need to flip the order of those equal statements and remove the static keyword.
Still make the method void
public class SharePattern {
private int days;
private int share;
public SharePattern(int numberofDays, int sharePoints){
days = numberofDays;
share = sharePoints;
}
public void outPutTablePrinter() {
And in the main method, you must use share.outPutTablePrinter()
It was actually extremely simple (sorry for my incompetence once again):
I should have put
return (sharePoints);
where i previously had nothing
This is what i suggest you if i understand correctly your code
SharePattern.class
private static int days;
private static int share;
public SharePattern(int numberofDays, int sharePoints)//constructor
{
days=numberofDays;
share=sharePoints;
}
public static void outPutTablePrinter(){
for (int i = 2; i <= days; i++) {
if (days % 2 == 0)
if (i <= days / 2) {
share = share + 50;
} else {
share = share - 25;
}
else
if (i <= days / 2 + 1) {
share = share + 50;
} else {
share = share - 25;
}
}
System.out.println("The share points on the final day would be: "+share);
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
import java.util.Scanner;
public class Recursion
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter n to start: ");
int n = in.nextInt();
System.out.println("Sum of numbers from 1 to " + n + ": " +new Recursion().sumUpTo(n));
}
}
/**
* Computes the sum of a range of numbers
*
* #param n an integer
* #return the sum of n range
*/
public int sumUpTo(int num){
if (num == 0)
{
return 0;
}
else{
return (num + sumUpTo(num-1))
}
}
This should be a very simple method, I know, but I can't seem to get it to compile. I keep getting "class, interface, or enum expected" on the public int sumUpTo(int num) line. This is the method that performs the actual computations. Any help would be greatly appreciated.
A couple things :
Your method is declared outside of the class
Missing semicolon on the line with your recursive call
You should be new to Object Oriented Programming. In Java a function(method) must be inside(belong) to a class. You either put public int sumUpTo(int num) inside public class Recursion or you can create another class and put it in there. But remember there should be only one public class inside a file.
In Java, everything must be inside of a class. Simply move your method to within the curly braces of the class and it should work.
The error class, interface, or enum expected is quite self-explained! It encountered code that wasn't inside of a class, inteface, or enum, and it wasn't expecting that, because that shouldn't happen!
In case you need to see what I mean:
public class Recursion {
public static void main (String[] args) {
// your code here...
}
// Where your method should have gone.
}
Also, welcome to Stack Overflow. Please remember to accept an answer if it answers your question.
Move your sumUpTo method inside the class.
import java.util.Scanner;
public class Recursion
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter n to start: ");
int n = in.nextInt();
System.out.println("Sum of numbers from 1 to " + n + ": " +new Recursion().sumUpTo(n));
}
/**
* Computes the sum of a range of numbers
*
* #param n an integer
* #return the sum of n range
*/
public int sumUpTo(int num){
if (num == 0)
{
return 0;
}
else{
return (num + sumUpTo(num-1));
}
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am supposed to build a slot machine that has 3 display windows, each window has 6 options that could display.
I am confused what "test expression" to use after the term switch? and then how to get the program to compare the 6 cases or options (cherry, orange, plum, bell, melon, bar) to see if they match and offer a return of what they won.
import java.util.Random;
import java.util.Scanner;
public class SlotMachine
{
//This is the main method
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
Random random = new Random();
String cont = "y" or "Y";
char answer;
int money = 0;
int totalEntered = 0;
int a;
int n;
int amountWon = 0;
int dbl = money * 2;
int trpl = money * 3;
while (cont.equals("y"))OR (cont.equals("Y"))
{
a = random.nextInt(6);
n = random.nextInt(991) +10;
totalEntered += money;
System.out.println("How much money would you like to bet? ");
money = keyboard.nextInt();
switch (TestExpression????)
{
case 0:
System.out.println("Cherry");
break;
case 1:
System.out.println("Orange");
break;
case 2:
System.out.println("Plum");
break;
case 3:
System.out.println("Bell");
break;
case 4:
System.out.println("Melon");
break;
default:
System.out.println("Bar");
}
if ()
{
System.out.println("You have won $0");
}
else if ()
{
System.out.println("Congratulations, you have won $" + dbl);
amountWon += dbl;
}
else if ()
{
System.out.println("Congratulations, you have won $" + trpl);
amountWon += trpl;
}
System.out.println("Continue? Enter y = yes");
cont = keyboard.nextLine();
}
}
}
Put a there. Whatever a is it jumps to that case in the switch statement. Ex: if a is 2 it jumps to case 2 so would print "Plum"
Could I also recommend using an Enum in this case?
enum SlotOptions {
CHERRY,
ORANGE,
PLUM,
BELL,
MELON,
BAR;
}
It looks like the swithc expression is the "actual" slow machine, so you want to put a random int there. Something along the lines of switch(a).
Why? Think about how a slot machine works and then look at your code. The slot machine randomly picks a symbol for each spot (ie 1 fruit). In your code you have a case for each fruit. What is happening is you are representing each case with a number. So to determine which case, you need to pick a number. What number do you pick? Since its a slot machine you pick a random number. That is why you have a=random.nextInt();.
You don't put a test expression in a switch-statement. You put an integer value. In this case, it seems like you want a there.