Basically I am trying to use a scanner as a method. This is what I have (I've used int in the meantime because I have not been able to figure out how to use Scanner as a parameter)
public class LoopPatterns {
public static int sum(int number1, int number2){
int sum = number1 + number2;
return sum;
}
public static void main(String[] args) {
System.out.println(sum(3, 4));
}
}
So this is what I have so far. However, the main point is that I need to get the sum of an unspecified amount of digits. I need to use a scanner but I haven't been able to figure out how to use it as a parameter of my method. Anyway, I hope that was concise enough. Thanks!
Just set the method so it accepts a reference of the scanner instead of pre-written ints.
public static int sum(Scanner myScanner){
int sum = 0;
String line;
while((line = myScanner.nextLine()) != "")
sum += Integer.parseInt(line);
return sum;
}
This method will accept a scanner as a parameter and then keep inputting numbers into the sum until the user inputs a blank character.
Related
Good Evening All,
I need help writing a class that enables to write a code like:
int number = Utility.getInt("Enter an int", '>');
to replace something like:
System.out.println("Enter an int>");
Scanner scan = new Scanner(system.in);
int number = scan.nextInt();
Please find my solution below. I am not sure if I am understanding the prompt correctly, not sure if I need to use a Java pre-defined Utility class or if I just need to name the class Utility. Any help or tip would be greatly appreciated thanks!
public class Utility {
private int number;
public Auto setInt (int number){
return "Enter an int" + number;
if (number>0)
this.number = newNumber;
return this;
}
public int getInt(){
return newNumber;
}
}
Have you tried static methods like below ?
public class Utility {
public static Integer getInt(String message){
System.out.println(message);
Scanner scan = new Scanner(System.in);
Integer number = scan.nextInt();
return number;
}
}
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.
So I'm learning Java in class and I'm really loving it so far but its really hard to understand sometimes. Right now I'm trying to understand how methods work. My question is why my code is not working. I am trying to read in an integer from user input then square it.
Here is my code:
package freetime;
import java.util.Scanner;
public class methods {
public static void main(String []args){
Scanner input = new Scanner(System.in);
System.out.println( " enter a number ");
int number = input.nextInt();
square(number);
}
public static int square(int number){
int num;
num = number * number;
return (num);
}
}
Let's say I input 5 on the console, the program immediately terminates and I cannot figure out why.
As mentioned by others, you don't print the value and the console will close as soon as the program ends. So you could try something like this
public class ScannerTest {
public static void main(String []args){
while(true){
Scanner input = new Scanner(System.in);
System.out.println( " enter a number (-1 to stop)");
int number = input.nextInt();
if(number == -1){
break;
}
int output = square(number);
System.out.println(output);
}
}
public static int square(int number){
int num;
num = number * number;
return (num);
}
}
This will print the result and loop ask for new input as long as you don't stop the program.
In Java, when main method comes to end and if there aren't any non-deamon threads running, the JVM ends. Your program came to an end without printing out the result of the square() call.
/*here is your solution :*/
import java.util.*;
import java.lang.*;
import java.io.*;
/*in java everything has to be in a class */
class SquareNumber
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner input = new Scanner(System.in);
System.out.println( " enter a number ");
int number = input.nextInt();
System.out.println(square(number));
/*something to print the squared number*/
}
public static int square(int number){
int num;
num = number * number;
return (num);
}
}
Your program is terminated because there is no other statement after square(number); statement. So your program executes square(...) method and after then it found end of main function so the program is terminated. To see some output you must print result of square(...) method.
package freetime;
import java.util.Scanner;
public class methods {
public static void main(String []args){
Scanner input = new Scanner(System.in);
System.out.println( " enter a number ");
int number = input.nextInt();
int result=square(number);//executing square(...) method and store the returned value of square method to result variable
System.out.println("Square of "+number+" is : "+ result);//printing result
}
public static int square(int number){
int num;
num = number * number;
return (num);
}
}
Need some help trying to set up this assignment. I am not to good with arrays, nor setting up methods to be used in the main. I need to make an array of 10 random numbers 1-100, that can be compared to the user input. I only need the comparison true/false to display. Here is what I have.
I get several errors in trying to print, so i haven't even tried to compare it to the user input yet.
Thanks,
import java.util.*;
public class Final {
public static void main(String[] args) {
System.out.print("Enter Player's Free Throw Percentage: ");
Scanner input = new Scanner(System.in);
int percent = input.nextInt();
print(shots);
}
public int [] getRandomNumbers(){
int [] shots = new int [10];
Random r = new Random();
for(int i = 0; i < 10; i++)
shots[i] = r.nextInt(100);
return shots;
}
public static void print(int shots[]) {
for (int i=0; i<shots.length; i++) {
System.out.print(shots[i]);
if (i < shots.length-1) {
System.out.print(", ");
}
else {
System.out.println("");
}
}
}
}
As commentors said, please provide error messages.
However, I can pick out several issues just for starters. Let's look at your main method...
public static void main(String[] args) {
System.out.print("Enter Player's Free Throw Percentage: ");
Scanner input = new Scanner(System.in);
int percent = input.nextInt();
print int [](shots);
}
In this call to the print method, why do you have int [] in there? Are you trying to cast something to an int array? Anyways, that has to come out.
Also, you are passing the print method some shots variable that doesn't exist.
Your print method takes an int array as its only argument, so you have to pass it a valid int array. Perhaps you meant to call getRandomNumbers() and pass the int array that it returns to the print method?
Also, what's with the nested classes you're showing. You have this class Final with another class ShotClass defined inside of it. And your closing brackets are all out of whack.
In short, you need to do as the comments ask and format your code and then work through each individual error message, because you've got a whole lot to fix.
EDIT
I'm not sure if I'm doing you more harm than good by giving you the answer to your homework assignment, but I feel for you so here it is. Please just look very carefully at the exact differences between what you posted in your question and what I show below. There's several mistakes you made, including bad syntax and a misunderstanding of how scope works, and I can't properly explain all the problems without typing several pages, so I hope you can learn from this example instead...
import java.util.*;
public class Final {
public static void main(String[] args) {
System.out.print("Enter Player's Free Throw Percentage: ");
Scanner input = new Scanner(System.in);
int percent = input.nextInt();
int[] shots = getRandomNumbers();
print(shots);
}
public static int[] getRandomNumbers(){
int [] shots = new int [10];
Random r = new Random();
for(int i = 0; i < 10; i++) {
shots[i] = r.nextInt(100);
}
return shots;
}
public static void print(int[] shots) {
for (int i=0; i<shots.length; i++) {
System.out.print(shots[i]);
if (i < shots.length-1) {
System.out.print(", ");
}
else {
System.out.println("");
}
}
}
}//END class
This is my assignment.
public class Fighter {
public static void main(String[] args){
String name;
int hitPoints;
int defenseLevel;
int attackSpeed;
Scanner input=new Scanner(System.in);
public static void hitPoints(){
int hitPoints;
do{
Scanner input=new Scanner(System.in);
System.out.println("What is the hit points for the fighter");
hitPoints=input.nextInt();
return hitPoints;
}while (hitPoints<=50);
return 0;
}
}
I'm pretty sure that looping it is completely wrong. I get an error Syntax error on token "void", # expected".
I also tried it with different types such as int and double. No dice.
The assignment says to only use one void method:
Write two methods inside of Fighter Class;
public void input()
public boolean attack(Fighter opponent)
However, I couldn't figure out how to do it with one so I was going to use 4 or 5.
First things first. You need to have hitPoints() method outside the main. You can't nest it inside the main() method.
And also, the return type of your hitPoints() is void, you have return statements in the method. Change the return type to int, so that you can return an int value from this method to the calling method.
public static int hitPoints(){
Also, since its a do-while loop(exit check loop), you don't need the default return. Instead initialize your hitPoints to 0 by default.
public static int hitPoints() { // return type is int, to return an int value
int hitPoints = 0; // default value
do {
Scanner input = new Scanner(System.in);
System.out.println("What is the hit points for the fighter");
hitPoints = input.nextInt();
return hitPoints;
} while (hitPoints <= 50);
// return 0; // not required, as its a do-while loop above
}
Two prblems:
Firstly, you are trying to encapsulate a method inside a method that is not legal. Move your hitPoints outside main method.
Secondly you are trying to return an integer value from your hitPoints method but that does not return anything as per its definition:
public static void hitPoints()
So either change your hitPoints method signature to return an int or remove the return statement from the method as mentioned here:
return 0;