Input and Output in Java - java

I have been asked to create a simple input output code for a training exercise in a new job using Java. I am a complete novice with Java so therefore I have hit a bit of a wall. This is my current code...
import java.util.*;
public class Task3
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
{
int Number1;
int Number2;
int Number3;
int Sum;
Number1= console.nextInt();
Number2= console.nextInt();
Number3= console.nextInt();
Volume = Number1 * Number2 + Number3 ;
}
System.out.printIn("Answer:" + Sum ) ;
}
}
Effectively I want this code to read 3 numbers as input from the user and then produce the sum of Number1 x Number2 + Number3 as output. I'm sure there are a few ways to do this but the way I have started above is the way we have been asked to do it. Any help would be much appreciated as I am keen to learn more about this and where I am having trouble... Thanks in advance, John

Check this:
import java.util.*;
public class MyJavaProgram
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int number1 = console.nextInt();
int number2 = console.nextInt();
int number3 = console.nextInt();
System.out.println("Volume = "+ ((number1 * number2) + number3));
}
}
Changes from your code:
Removed a set of brackets which were creating a local scope where Sum was defined, yet you were trying to use Sum outside of that local scope
Variable defined as Sum but then referred to as Volume; I assume this was a copy & paste error.

Just for adding three numbers. Program should be
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(System.in);
int num1= s.nextInt();
int num2= s.nextInt();
int num3= s.nextInt();
System.out.println("Sum= "+ (num1+ num2+num3));
// or play any game with those variables here
}
You are adding extra {} and variables without any use.Get rid off those.

Related

How can I use char/String as an aswer for yes or no on math question(n1>2, n1<n2)

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");
}
}

Java methods interacting with each other

I am currently learning Java and following some online tutorials. One of the assignments is to compute the body age of a person by getting their various scores, getting the average of these scores and then applying a formula to it to get the total. I can do it with one big class, but the assignment then asks to go further and split everything into different classes. My program currently looks like this:
import java.util.Scanner;
public class fit2 {
public static void main(String[] args) {
int average, bodyAge;
average = average2();
System.out.println(average);
bodyAge = fitAge();
System.out.println(bodyAge);
}
public static int fs() {
int fs;
System.out.println("Enter first number: ");
Scanner bucky = new Scanner(System.in);
fs = bucky.nextInt();
return fs;
}
public static int ss() {
int ss;
System.out.println("Enter second number: ");
Scanner bucky = new Scanner(System.in);
ss = bucky.nextInt();
return ss;
}
public static int average2() {
int first, second, average;
first = fs();
second = ss();
average = (first + second) / 2;
return average;
}
public static int fitAge() {
int fitAge, average;
average = average2();
fitAge = average * 8 / 5 + 10;
return fitAge;
}
}
My idea was to have different methods for each part of the program - two methods to get the users scores and then pass these into a averageing method, which would then pass it into a final method which would apply the formula, then passing it back it into the Main class, which would print that age out as well as the Average age.
I read somewhere that you shouldnt get user input in classes but get it in main and pass it into the average class using parameters -- can anyone advise on this?
Thanks.
Try something like this (as suggested by my comment on the question):
import java.util.Scanner;
public class fit2 {
public static void main(String[] args) {
System.out.println("Enter first number: ");
Scanner bucky = new Scanner(System.in);
int fs = bucky.nextInt();
System.out.println("Enter second number: ");
bucky = new Scanner(System.in);
int ss = bucky.nextInt();
int average = average2(fs, ss);
int bodyAge = fitAge(average);
System.out.println(average);
System.out.println(bodyAge);
}
public static int average2(int first, int second) {
int average;
average = (first + second) / 2;
return average;
}
public static int fitAge(int average) {
int fitAge;
fitAge = average * 8 / 5 + 10;
return fitAge;
}
}
I believe I understand your question - you are unsure of where to place user input in your program.
In a small program like this, it may be wise to place user input in the main() method, solely because you gather user input, delegate input to methods that perform computation on the data that is "under the hood" of the program, and then return the value back to the user.
In your specific instance, this seems like a wise decision, as your program is small and a standard console-based application. This may not always be the case in the future, depending on the program you are writing.
Realistically, it doesn't matter all too much if it runs as intended, but for simplicity sake (remember KISS) putting user input in your main() method is probably a good idea.

Guess My number exercice 5-7 in think Java

i'm learning Java with the book think Java : how to think like a computer scientist ? and there is no exercise answers in the book, usually i end up finding similar exercices on different websites but not for this one because i have precise instructions. Can you please tell me if it's correct.
I think the problem is solved, the job is done, but is there an easier way to do it ?
Thanks a lot
Exercise 5-7.
Now that we have conditional statements, we can get back to the “Guess My Number” game from Exercise 3-4.
You should already have a program that chooses a random number, prompts the user to guess it, and displays the difference between the guess and the chosen number.
Adding a small amount of code at a time, and testing as you go, modify the program so it tells the user whether the guess is too high or too low, and then prompts the user for another guess.
The program should continue until the user gets it right. Hint: Use two methods,
and make one of them recursive.
import java.util.Random;
import java.util.Scanner;
public class GuessStarter {
public static void Lower(int number,int number2) {
Scanner in = new Scanner(System.in);
System.out.print("Too Low , try again ");
number2 = in.nextInt();
if (number2==number) {
System.out.println("You're right");}
else if (number2>number)
Higher(number,number2);
else
Lower(number,number2); }
public static void Higher(int number,int number2) {
Scanner in = new Scanner(System.in);
System.out.print("Too high , try again ");
number2 = in.nextInt();
if (number2==number) {
System.out.println("You're right");}
else if (number2>number)
Higher(number,number2);
else
Lower(number,number2); }
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random random = new Random();
int number = random.nextInt(100) + 1;
int number2;
System.out.print("Type a number: ");
number2 = in.nextInt();
if (number2==number) {
System.out.println("You're right");}
else if (number2>number)
Higher(number,number2);
else
Lower(number,number2);}
}
Don't know if it'll be useful now or not, but, as I was solving the same solution, thought of letting it know if someone finds it useful:
import java.util.Random;
import java.util.Scanner;
/**
* Created by RajU on 27-Jun-17.
*/
public class GuessNumber2 {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
message("I'm thinking of a number between 1 and 10 (including both).\n" +
"Can you guess what it is?\n" +
"Type a number: ");
int userNumber = input.nextInt();
tryAgain(userNumber, calculateRandom(10));
}
public static int calculateRandom(int n) {
Random random = new Random();
return random.nextInt(n) + 1;
}
public static void tryAgain(int userNumber, int generateRandom) {
if (userNumber == generateRandom) {
message("You're absolutely right!");
} else {
if (userNumber > generateRandom) {
message("Think of a lesser number: ");
} else {
message("Think of a greater number: ");
}
userNumber = input.nextInt();
tryAgain(userNumber, generateRandom);
}
}
public static void message(String m) {
System.out.print(m);
}
}
I just completed this exercise. It's pretty interesting to see some different approaches! Here's my take on it:
import java.util.Random;
import java.util.Scanner;
public class GuessGameLevelUp {
/*
* A guessing game where you try to guess a random number between and including 1 and 100.
* This version allows you to continue guessing until you get the right answer.
* When you're off, a hint will let yet know whether your most recent guess was too high or low.
*/
public static void main (String [] args) {
//Generates a random number for the game
Random random = new Random();
int answer = random.nextInt(100) +1;
//Introduces the game and gives a prompt
System.out.println("I'm thinking of a number between and including "
+ "1 and 100, can you guess which?");
System.out.print("Take a guess: ");
//Enables guess value input and parrots guess
Scanner in = new Scanner(System.in);
int guess;
guess = in.nextInt();
System.out.println("Your guess is: "+guess);
//Stacks a new class to determine the outcome of the game
tooHighTooLow(answer, guess);
}
public static void tooHighTooLow(int a, int g) {
//Triggers and parrots guess if correct
if (a==g) {
System.out.print("Correct! The number I was thinking of was: "+g);
//Triggers "Too Low" prompt and uses recursive to offer another attempt
} else if (a>g) {
System.out.print("Too Low! Try again: ");
Scanner in = new Scanner(System.in);
g = in.nextInt();
System.out.println("Your guess is: "+g); //Parrots guess
tooHighTooLow(a, g);
//Triggers "Too High" prompt and uses recursive to offer another attempt
}else
System.out.print("Too high! Try again: ");
Scanner in = new Scanner(System.in);
g = in.nextInt();
System.out.println("Your guess is: "+g); //Parrots guess
tooHighTooLow(a, g);
}
}
I got stuck on this one too, but your code helped me in arriving at a solution. Here's what I came up with:
import java.util.Random;
import java.util.Scanner;
public class Ch5Ex7 {
public static void compareNumbers(int userNumber,int randomNumber) {
if(userNumber == randomNumber) {
System.out.println("You got it!");
} else if ( userNumber > randomNumber ) {
System.out.println("Too high. Guess again: ");
Scanner in = new Scanner(System.in);
userNumber = in.nextInt();
compareNumbers(userNumber, randomNumber);
} else {
System.out.print("Too low. Guess again: ");
Scanner in = new Scanner(System.in);
userNumber = in.nextInt();
compareNumbers(userNumber,randomNumber);
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random random = new Random();
int randomNumber = random.nextInt(100) + 1;
int userNumber;
System.out.print("Type a number: ");
userNumber = in.nextInt();
compareNumbers(userNumber, randomNumber);
}
}
Thanks for pointing me in the right direction!

Simple Java way to input decimal and round to nearest integer

I am using the Java SDK to compile. Need I say, I am a beginner.
Here is the code I tried to use to "Ask user to input decimal and code should output an integer. (round to nearest integer)
import java.util.*;
public class readDecimal {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
double decimalNumber;
long intNumber;
System.out.println(“Please enter a decimal number:“);
decimalNumber = input.nextDouble();
intNumber = Math.round(decimalNumber);
System.out.println(decimalNumber +
“ rounded to the nearest integer is “ + intNumber);
}
}
What am I doing wrong? I saw the other posts however they seem much to complicated for a beginner. Can you please help?
Thank you,
Diane
Your quotation marks are incorrect; they are unicode for some reason. Replace all the quotations by manual typing them in, in you System.out.println statements.
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
double decimalNumber;
long intNumber;
System.out.println("Please enter a decimal number:");
decimalNumber = input.nextDouble();
intNumber = Math.round(decimalNumber);
System.out.println(decimalNumber +
" rounded to the nearest integer is " + intNumber);
}
You can round double numbers using Math.round method.
import java.util.*;
public class RoundingDecimal {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
double num1;
double num2;
System.out.print("Please enter a decimal number: ");
num1 = sc.nextDouble();
num2 = Math.round(num1);
System.out.println(" Rounded to the nearest integer is " + num2);
}
}

Java Averaging Program

Write a class called Average that can be used to calculate average of several integers. It should contain the following methods:
 A method that accepts two integer parameters and returns their average.
 A method that accepts three integer parameters and returns their average.
 A method that accepts two integer parameters that represent a range. Issue an error message and return zero if the second parameter is less than the first one. Otherwise, the method should return the average of the integers in that range (inclusive).
I am totally new to Java and programming, this has me completely lost! Here's what I've tried.
import java.util.Scanner;
public class Average {
public static void main(String[] args) {
double numb1, numb2, numb3;
System.out.println("Enter two numbers you'd like to be averaged.");
Scanner keyboard = new Scanner(System.in);
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
}
public double average (int num1, int num2) {
return (num1 + num2) / 2.0;
}
public double average (int num1, int num2, int num3)
{
return (num1 + num2 + num3) / 3.0;
}
}
The program doesn't go past getting the values from the user. Please help!
You have to actually call your methods.
Just place
Average avg = new Average();
System.out.println("The average is: " + avg.average(numb1, numb2));
at the end of your main method.
Alternatively you can make the methods static:
public static double average (int num1, int num2) {
return (num1 + num2) / 2.0;
}
More info on constructors and static.
It looks like your not actually printing out the results. Try the following.
System.out.print(average(numb1, numb2));
Let's detail what you did there.
public static void main(String[] args) {
//Create variables numb1, numb2 & numb3
double numb1, numb2, numb3;
System.out.println("Enter two numbers you'd like to be averaged.");
//Read standard input (keyboard)
Scanner keyboard = new Scanner(System.in);
//Retrieve first input as an int
numb1 = keyboard.nextInt();
//Retrieve second input as an int
numb2 = keyboard.nextInt();
}
Then your two next methods compute for two or three given integers their average.
The main method is the first method called during your program execution. The jvm will execute everything inside. So it will declare the three doubles, read two values from keyboard and then end.
If you want to compute the average of numb1 & numb2 using your method, you have to create an object Average and call your average method like this
public static void main(String[] args) {
//Create variables numb1, numb2 & numb3
double numb1, numb2, numb3;
System.out.println("Enter two numbers you'd like to be averaged.");
//Read standard input (keyboard)
Scanner keyboard = new Scanner(System.in);
//Retrieve first input as an int
numb1 = keyboard.nextInt();
//Retrieve second input as an int
numb2 = keyboard.nextInt();
//Declare the average value
double average;
//Create an average instance of the class average
Average averageObject = new Average();
//Call your average method
average = averageObject.average(numb1,numb2);
//Print the result
System.out.println("Average is : " + average);
}
Everything in Java is object (read about Object Oriented Programming).
Writing your class "Average" defines how your object is structured. It has attributes (characteristics) and methods (actions). Your Average object has no attributes. However it has two methods (average with two and three numbers) acting on integers.
However your class is just the skeleton of your object. You need to create an object from this skeleton using the keyword new as :
Average averageObject = new Average();
Sincerely
public class Marks {
int roll_no;
int subject1;
int subject2;
int subject3;
public int getRoll_no() {
return roll_no;
}
public void setRoll_no(int roll_no) {
this.roll_no = roll_no;
}
public int getSubject1() {
return subject1;
}
public void setSubject1(int subject1) {
this.subject1 = subject1;
}
public int getSubject2() {
return subject2;
}
public void setSubject2(int subject2) {
this.subject2 = subject2;
}
public int getSubject3() {
return subject3;
}
public void setSubject3(int subject3) {
this.subject3 = subject3;
}
public void getDetails(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the marks of subject1");
this.subject1 = sc.nextInt();
System.out.println("Enter the marks of subject2");
this.subject2 = sc.nextInt();
System.out.println("Enter the marks of subject3");
this.subject3 = sc.nextInt();
System.out.println("Enter the roll number");
this.roll_no = sc.nextInt();
}
public int getAverage(){
int avg = (getSubject1() + getSubject2() + getSubject3()) / 3;
return avg;
}
public void printAverage(){
System.out.println("The average is : " + getAverage());
}
public void printRollNum(){
System.out.println("The roll number of the student is: " + getRoll_no());
}
public static void main(String[] args){
Marks[] e1 = new Marks[8];
for(int i=0; i<2; i++) {
System.out.println("Enter the data of student with id:");
e1[i] = new Marks();
e1[i].getDetails();
e1[i].printAverage();
}
System.out.println("Roll number details");
for(int i=0; i<2; i++){
e1[i].printRollNum();
}
}
}
If you'd like your program to find the average you need to include a call to that method in your main method.
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
System.out.println("The average of " + numb1 + " and " + numb2 + " is " + average(numb1,numb2);
}
you need to call the methods that you have written after you accept the input.
...
System.out.println("Enter two numbers you'd like to be averaged.");
Scanner keyboard = new Scanner(System.in);
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
System.out.println(average (int numb1 , int numb2 ))
...
You probably want to provide a menu of options for the user to select to determine which method to call
System.out.println("Select one option");
System.out.println("1. Enter two numbers you'd like to be averaged.");
System.out.println("2. Enter the 3 numbers you want averaged.");
System.out.println("3. Enter the number Range you want averaged.");
and based on that answer you can determine which method to call
After the access specifier (public) and before the return type (double) place the Java keyword static. You shouldn't worry about what this means right now.
You have to use bitwise operators.
average of int a and b can be calculated as
avg= (a >> 1) + (b >> 1) + (((a & 1) + (b & 1)) >> 1);
The main method will only execute what it is asked to. If you want the average methods to be executed, you will have to create an object, pass the required variable and call the methods from the main method. Write the following lines in the main method after accepting the input.
Average avrg = new Average();
System.out.println("The average is: " + avrg.average(numb1, numb2, numb3));
Write only numb1 and numb2 if you want to average only two numbers.

Categories