Find the minimum of a set of data input from the keyboard - java

I have an algorithm in my textbook written in pseudocode which is then supposed to be "implemented to a Java method". It goes like this:
read min;
while not eoln do
read x
if x < min then
min <- x
end if
end while
print min;
Then I'm given this code:
import java.util.Scanner;
int min() {
Scanner input = new Scanner(System.in);
System.out.println("x=? (999 to end)");
int x = input.nextInt();
int min = x;
while (x!=999) {
System.out.println("x=? (999 to end)");
x = input.nextInt();
if (x < min) {
min = x;
}
}
return min;
}
I put everything below import.Scanner inside of the main method and inside of a class like this:
public class MyAlgorithm {
public static void main(String[] args) {
// code here
}
}
But then I get this error message in Terminal:
MyAlgorithm.java:7: error: ';' expected
int min() {
^
1 error
Am I missing something? If I put the semicolon there, the whole thing just won't work.

It seems like you put your min method inside of main, this is defining methods from within other methods which will not work properly and cannot compile. The main method is the commands you want to run as soon as you start your program, any other functions in the class should be declared outside of it, and if you want them to run in main you do a method call.
it should look something like this:
import java.util.Scanner;
public class MyAlgorithm {
int min() {
//(min code)
}
public static void main(String[] args) {
// code here
//corrected according to Uli's comment
MyAlgorithm m = new MyAlgorithm();
int result = m.min();
}
}
I suggest reading up on how java programs are structured. Here's an article on methods.

Don't put your method min() inside the main() method. In Java, you can not define a method inside a method. In Java, you need an object to call its methods (Except you make the methods static). So your final Code looks something like this.
import java.util.Scanner;
public class MyAlgorithm {
public static void main(String[] args) {
MyAlgorithm m = new MyAlgorithm ();
m.min();
}
int min(){
//Your min code goes here
return min_value;
// min_value is the same as your min variable. It has another name to
// prevent name collisions
}
}
If you are allowed to use static methods, (which I don't think) you can use the following alternative:
static int min(){
//Your min code goes here
return min_value;
// min_value is the same as your min variable. It has another name to
// prevent name collisions
}
public static void main(String[] args) {
int result = MyAlgorithm.min();
}

Related

Java program without main method

For my class I need to write code that adds up the numbers 1-100 which will produce the number 5050. He told us not to use a main method and use a for loop. Is a main method 'public static void main (String[] args)' or something else. I am just still very confused on what exactly the main method is. Here is the code I have so far that works
public class SumAndAverageForLoop{
public static void main (String[] args) {
int sum = 0;
for (int i = 1; i <= 100; i++) sum += i;
System.out.println("The sum is " + sum);
}
}
From what I read more and after talking to some other kids in the class they said I need to make another class with a main method that calls this class but how do you call one class from another?
How to call one class from another that has a main method?
Yes the public static void main(String[] args) signature is the main method.
It sounds like you're writing library style code. So just create a method with a meaningful name for what your code does. Like AddOnetoOneHundred or similar.
You can create a method like this:
public static int CountUp() {
// code that was in your main method before
}
Double check your assignment, your teaching might have specified a class and method name and already has a program that will test your code.
A main method is fundamental to any given program as the Java compiler searches for the method as a starting point of execution. However, you are trying to make a utility class so:
class SumAndAverageForLoop {
// no main method
public static int sum() {
int sum = 0;
for (int i = 1; i <= 100; i++) sum += i;
System.out.println("The sum is " + sum);
}
}
class MainClassProgram {
// main in another class
public static void main() {
SumAndAverageForLoop.sum();
}
}
Try to create a method to do the calculation. The idea is create code that is unit testable.
public class SumAndAverageForLoop{
public static void main (String[] args) {
int returned = SumUp(1, 100);
System.Out.Println("sum is " + returned);
}
public int SumUp(int startInt, int endInt) {
int sum = 0;
if (endInt > startInt) {
for (int i = startInt; i <= endInt; i++) sum += i;
}
return sum;
}
}
Short Answer:
Yes, that (public static void main (String[] args)) is the main method.
Long Answer:
The main method is the entry point for an application. Without it, you may have code, but that code must somehow link to a main method or it cannot be ran. Counter-intuitively, the main method doesn't actually have to be a method. In C, you can create an integer array called main and execute it. It will translate the integers into hexadecimal and execute a corresponding Assembly command for each one, iteratively.
If you do what the professor says, you will not be able to test the program as an executable. He probably has a program made to run your code and test it for him, which is why he doesn't want a main method.
I'm not sure by what your teacher means by, "not using a main method". But you can declare a method outside of you main method and call it from there;
public class SumAndAverageForLoop{
public static void main (String[] args) {
makeSum();
}
public static void makeSum() {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println(sum);
}
}
Also, since one of your comments asked "How to create a method?".
I suggest you read up on some books for beginners. I'd recommend the book Head First Java.

method returning average of double array

Im new with programming and have been trying to solve this problem for a while, been looking at similar questions but im not understanding whats wrong with my code.
So the assignment is to write a method that takes an array that has three doubles in it. Then return the average of the three doubles. Then write a main that should call and then type the method.
Thanks!
Main
public class Tenta131031upg1main {
public static void main (String[]args){
double []arr ={3.15, 4.41, 7.64};
Tenta131031upg1.genomsnitt(double arr[]);
System.out.println(Tenta131031upg1.genomsnitt(arr));
}
}
Class
public class Tenta131031upg1 {
static int i =0;
static double sammanlagd=0;
static double genomsnitt=0;
public static double genomsnitt(double[]arr){
while(i<arr[].length()){
sammanlagd = sammanlagd + arr[i];
i++;
}
genomsnitt = sammanlagd/arr[].length();
return genomsnitt;
}
}
PS. they are two different classes with 1 main and 1 class they are not in the same file!
The error:
Syntax error on token "double", new expected
Variable must provide either dimension expressions or an array initializer
arr cannot be resolved to a type
at Tenta131031upg1main.main(Tenta131031upg1main.java:7)
Please correct the two lines in the first file like this:
double[] arr ={3.15, 4.41, 7.64};
Tenta131031upg1.genomsnitt(arr);
You were creating a new, empty array in the second line.
Try this:
Main
public class Tenta131031upg1main {
public static void main (String[]args){
double[] arr ={3.15, 4.41, 7.64};
System.out.println(Tenta131031upg1.genomsnitt(arr));
}
}
Class
public class Tenta131031upg1 {
static int i =0;
static double sammanlagd=0;
static double genomsnitt=0;
public static double genomsnitt(double[] arr){
while(i<arr.length){
sammanlagd = sammanlagd + arr[i];
i++;
}
genomsnitt = sammanlagd/arr.length;
return genomsnitt;
}
}
Changes are:
change in method call
arr.length instead of arr[].length()

Why can't I print a variable that is provided by user inside a loop?

I apologize if the answer to this question is so obvious I shouldn't even be posting this here but I've already looked up the error compiling the following code results in and found no explanation capable of penetrating my thick, uneducated skull.
What this program is meant to do is get 2 integers from the user and print them, but I have somehow managed to mess up doing just that.
import java.util.Scanner;
public class Exercise2
{
int integerone, integertwo; //putting ''static'' here doesn't solve the problem
static int number=1;
static Scanner kbinput = new Scanner(System.in);
public static void main(String [] args)
{
while (number<3){
System.out.println("Type in integer "+number+":");
if (number<2)
{
int integerone = kbinput.nextInt(); //the integer I can't access
}
number++;
}
int integertwo = kbinput.nextInt();
System.out.println(integerone); //how do I fix this line?
System.out.println(integertwo);
}
}
Explanation or a link to the right literature would be greatly appreciated.
EDIT: I want to use a loop here for the sake of exploring multiple ways of doing what this is meant to do.
Remove the int keyword when using the same variable for the second time. Because when you do that, it is essentially declaring another variable with the same name.
static int integerone, integertwo; // make them static to access in a static context
... // other code
while (number<3){
System.out.println("Type in integer "+number+":");
if (number<2)
{
integerone = kbinput.nextInt(); //no int keyword
}
number++;
}
integertwo = kbinput.nextInt(); // no int keyword
And it needs to be static as well since you're trying to access it in a static context (i.e) the main method.
The other option would be to declare it inside the main() method but before your loop starts so that it'll be accessible throughout the main method(as suggested by "Patricia Shanahan").
public static void main(String [] args) {
int integerone, integertwo; // declare them here without the static
... // rest of the code
}
How about:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kbinput = new Scanner(System.in);
System.out.println("Type in an integer: ");
int integerone = kbinput.nextInt();
System.out.println("Type another: ");
int integertwo = kbinput.nextInt();
System.out.println(integerone);
System.out.println(integertwo);
}
}

Getting value to display for Java CurrentAccount class

package bankAccount;
public class CurrentAccount {
int account[];
int lastMove;
int startingBalance = 1000;
CurrentAccount() {
lastMove = 0;
account = new int[10];
}
public void deposit(int value) {
account[lastMove] = value;
lastMove++;
}
public void draw(int value) {
account[lastMove] = value;
lastMove++;
}
public int settlement() {
int result = 0;
for (int i=0; i<account.length; i++) {
result = result + account[i] + startingBalance;
System.out.println("Result = " + result);
}
return result;
}
public static void main(String args[]) {
CurrentAccount c = new CurrentAccount();
c.deposit(10);
}
}
At the moment, when I run the class, the expected System.out.println does not appear, and if I simply move public static void main(String[] args) to the top, this generates multiple red points. What is the best way for me to refactor my code so it works in the expected way?
you can have another class called Main in the file Main.java in which you can write your
public static void main(String args[])
and call
c.settlement();
in you main() to print.
Also one more advice,
in your constructor you have
account = new int[10];
which can hold only 10 ints.
in your deposit() and draw() you are not checking the account size. When the value of lastMove is more than 10 , the whole code blows up.
Hence I suggest you to use ArrayList
You never called the settlement method...
public static void main(String args[]) {
CurrentAccount c = new CurrentAccount();
c.deposit(10);
c.settlement();
}
I have the feeling that you come from some non-OOP language, like C or PHP. So some explanation:
The main method is static: that means it "exists" even when there is no object instance created, it can be thought of as if it belonged to the class instance.
on the contrary, for the other methods to "work", an instance is required.
This way the main method can be (and is actually) used as the entry point of the application
It is executed, and when it exists, (if no other threads are left running) the application terminates.
so nothing else is run that is outside of this method just by itself...
so if you don't call c.settlement(); - it won't happen...
Other notes:
Running main doesn't create an instance of the enclosing class
with new CurrentAccount(), you create an object instance, which has states it stores, and can be manipulated
be careful with arrays, they have to be taken care of, which tends to be inconvenient at times...
Why do you expect the printed output to appear? You don't actually call the settlement method, so that command is not executed.
You did not call settlement.. so nothing appears
if you add c.settlement... it is fine..
You have not called deposit() and settlement() in the main method untill you call, You cannot get expected output.

Luse Constructor With Variable Inside

I'm learning about constructors.
When I try to compile the following code, I get the error "variable input and shape are not initialized."
Could anyone tell me why and how to solve it?
public class Try {
public static void main(String[] args)
{
String input;//user key in the height and width
int shape;//triangle or square
Count gen = new Count(input , shape);//is this the right way to code?
gen.solve();
}
}
public class Count {
public Count(String inp, int shp) {
String input_value = inp;
shape_type = shp;
}
public void solve () {
if shape_type==3{
//count the triangle
}
else if shape_type==4{
//count the square
}
}
}
You haven't given shape or input values yet before you try using them. Either you can give them dummy values for now, like
String input = "test";
int shape = 3;
Or get the string and integer from the user; in that case, you might want to take a look at how to use a Scanner.
By leaving input and shape without values, at:
String input;
int shape;
they are uninitialized, so Java doesn't know what their values really are.
I assume this is some kind of homework. I took the liberty of reformating and fixing your code a little.
You have to initialize any variable you are going to use. The only exception is when you are using class members (those are initialized automatically to some default value). See below that the members of the Count class aren't explicitly initialized.
This is some working code. Also note that i change the solve method a little (the if blocks should have had () around the expression. But what you are trying to do is usually better done with a switch block as shown below. Also I declared two members inside the Count class to remember the values provided at construction time in order to be able to use them when calling the solve() method.
public class Try {
public static void main(String[] args) {
String input = null; //user key in the height and width
int shape = 0; //triangle or square
Count gen = new Count(input, shape);//is this the right way to code?
gen.solve();
}
}
class Count {
String input_value;
int shape_type;
public Count(String inp, int shp) {
this.input_value = inp;
this.shape_type = shp;
}
public void solve() {
switch (this.shape_type) {
case 3:
// count the triangle
break;
case 4:
// count the square
break;
}
}
}
Proper formatting of the code usually helps :).

Categories