local Variable may not have been initialized and a loop - java

I have a program that originally took two numbers passed the values to a method and returned the higher number. I got that so I decided to expand to the program and want the program to ask the user for the 2 numbers. I have 2 problems that I can not figure out. The first is that it is saying that my variables i and j are not initialized. The second is that the program loops 3 times. can someone offer me any assistance. I am coming from c# Thanks.
package javabook;
import java.util.Scanner;
public class Chapter5 {
public static void main(String[] args)
{
int i;
int j;
int k = max(num1(i),num2(j));
//Scanner input = new Scanner(System.in);
num1(i);
num2(j);
System.out.print("The maximum between " + num1(i) + " and " + num2(j) + " is " +k);
}
//Return the max between two numbers
public static int max(int num1, int num2)
{
int result;
if (num1>num2)
result = num1;
else
result = num2;
return result;
}//End Max Method
public static int num1(int i)
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter the first number: ");
input.nextInt();
input.close();
return i;
}//End num1 method
public static int num2(int j)
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter the second number: ");
input.nextInt();
input.close();
return j;
}//end num2 method
}

Local variable don't have same values as globally declared variable's thus you have to assign some value to use them. Global variable int has value 0 by default.
int i = 0;
int j = 0;
or
this.i = 0;
this.j = 0;

here:
int i;
int j; <---creates the var, but doesn't initialize it
int k = max(num1(i),num2(j));
^---using the var, without having initialized it
even a simple
j = 0;
would help.

Related

How to input two numbers in Main using Scanner and make it work with a method (Ascending order java)?

I'm trying to make this program that will print out numbers in ascending order between two input numbers. I made it work as a method and I can call the method in Main, but what I really want to do is to input the two numbers in Main and not in the method.
So something like this:
System.out.println(”Two numbers in ascending order”);
(input two numbers in console)
And then after this, call the method that will print in ascending order between the chosen numbers of Main.
I’m new to this and i’ve tried several things, but I can’t seem to figure out what to do. Would appreciate som help.
This is how the code looks now.
import java.util.Scanner;
public class AscendingOrder {
public static void main(String[] args) {
// calling method
int ascending1 = ascending();
}
public static int ascending() {
int min;
int max;
int total = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Two numbers in ascending order");
min = sc.nextInt();
max = sc.nextInt();
for (int i = min; i < max + 1; i++) {
System.out.print(i + " ");
total += i;
}
return total;
}
}
Pass in the two inputs as parameters to your method, something like :
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Two numbers in ascending order");
int min = sc.nextInt();
int max = sc.nextInt();
int ascending1 = ascending(min, max);
System.out.println(ascending1);
}
And now :
public static int ascending(int min, int max) {
int total = 0;
for (int i = min; i < max + 1; i++) {
System.out.print(i + " ");
total += i;
}
return total;
}
Notice that now the definition of ascending() takes in two parameters of type int. The values are passed from the main method to the method.
You can input the numbers in the main method and then pass them to another method:
public class AscendingOrder {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Two numbers in ascending order");
int min = sc.nextInt();
int max = sc.nextInt();
int ascending1 = ascending(min, max);
}
public static int ascending(int min, int max) {
int total = 0;
for (int i = min; i < max + 1; i++) {
System.out.print(i + " ");
total += i;
}
return total;
}
}
You can read the command line arguments or place the scanner in main function and pass the arguments
import java.util.Scanner;
public class AscendingOrder {
public static void main(String[] args) {
System.out.println("Entered first number is: "+args[0]);
System.out.println("Entered Secomd number is: "+args[1]);
int ascending1 = ascending(Integer.parseInt(args[0]),Integer.parseInt(args[1]));
}
public static int ascending(int min,int max) {
int total = 0;
for (int i = min; i < max + 1; i++) {
System.out.print(i + " ");
total += i;
}
return total;
}
}
You can get the numbers in main method and sort them in the main method itself. Java 8 makes it so easy with streams.
public static void main( String[] args ) throws Exception {
Framework.startup( );
Scanner sc = new Scanner( System.in );
System.out.println( "Two numbers in ascending order" );
int num1= sc.nextInt( );
int num2= sc.nextInt( );
Arrays.asList( num1, num2).stream( ).sorted( ).forEach( System.out::println );
}

There is something wrong in my code but i'm not sure what it is?

I'm trying to print the sum of digits of the numbers that the user inputs,
what's wrong in my code? it appears to me that sum is underlined in the S.O.P..
but why is that? and how can I fix it?
package assignment7;
import java.util.Scanner;
public class Assignment7_4_5 {
public static void main(String[] args) {
Scanner input= new Scanner (System.in);
System.out.print("Enter a number: ");
int number=input.nextInt();
System.out.println("sum: "+sumDigits (sum));
}
public static int sumDigits(int sum) {
int number = 0;
while (number > 0) {
sum = sum + number % 10;
number = number / 10;
}
return sum;
}
}
You need to change sumDigits(sum) to sumDigits(number) because number is the variable that you are passing to the method, the variable sum is not even declared before using the method sumDigits. Also in the function, the while loop will never execute because number is set to zero and the condition is (number > 0) which is never true.
You have sum and number the wrong way around. You need to pass in number, as this is what you get from the user. Sum needs to be initialised to 0 in sumDigits, not number. Then you're incrementing sum and dividing down number, returning sum once you're finished. You also don't then skip over your while loop!
package assignment7;
import java.util.Scanner;
public class Assignment7_4_5 {
public static void main(String[] args) {
Scanner input= new Scanner (System.in);
System.out.print("Enter a number: ");
int number=input.nextInt();
System.out.println("sum: "+sumDigits (number));
}
public static int sumDigits(int number) {
int sum = 0;
while (number > 0) {
sum = sum + number % 10;
number = number / 10;
}
return sum;
}
}

Changing input variables in a java loop

I have an assignment, and I need to use a loop to allow a user to enter ten different numbers in a programme which then adds up the variables.
I have found various pieces of code and stitched them together to create this:
import javax.swing.*;
import java.util.Scanner;
public class exercise6
{
public static void main (String []args)
{
//Input
String totalNum, num1, num2, num3, num4, num5, num6, num7, num8, num9, num10;
Scanner in = new Scanner (System.in);
System.out.println("Please enter ten numbers:");
int[] inputs = new int[10];
for (int i = 0; i < inputs.length; ++i)
{
inputs[i] = in.next();
}
//Process
totalNum = num1 + num2 + num3 + num4 + num5 + num6 + num7 + num8 + num9 + num10;
//Output
JOptionPane.showMessageDialog(null, "Total = " + totalNum);
}
}
It's not great, but it's the best I have so far. Please help?
You don't need the variables num1 to num10. You can simply sum up in the loop itself. Like:
int sum = 0;
for (int i = 0; i < 10; i++) {
sum += = in.next(); // sum = sum + in.next();
}
Furthermore you assigned your variables as Strings, but you need int. In your case it would print something like 1111111111, if the input would always be a 1.
Take a look here how you would handle Integers properly.
You can achieve that in two ways, either inside the loop itself just add the number or if you need to keep track of them for later just add them to the array.
import javax.swing.*;
import java.util.Scanner;
public class exercise6
{
public static void main (String []args)
{
String total;
Scanner in = new Scanner (System.in);
int numOfInputValues = 10;
System.out.println("Please enter ten numbers:");
int[] inputs = new int[numOfInputValues];
for (int i = 0; i < numOfInputValues; ++i)
{
// Append to array only if you need to keep track of input
inputs[i] = in.next();
// Parses to integer
total += in.nextInt();
}
//Output
JOptionPane.showMessageDialog(null, "Total = " + totalNum);
}
}
First of all, your class should be in CamelCase. First letter is always in capital letter.
Second, you don't need an array to save those numbers.
Third you should make a global variable that you can change with ease. That is a good practice.
And you should always close stream objects like Scanner, because they leak memory.
import java.util.Scanner;
public class Exercise6 {
public static void main(String[] args) {
int numberQuantity = 10;
int totalNum = 0;
Scanner in = new Scanner(System.in);
System.out.println("Please enter ten numbers:");
for (int i = 0; i <= numberQuantity; i++) {
totalNum += in.nextInt();
}
in.close();
System.out.println(totalNum);
}
}
So the simplest answer I found is:
import javax.swing.*;
import java.util.Scanner;
public class exercise6
{
public static void main (String []args)
{
//Input
int totalNum, num1;
totalNum = 0;
for (int numbers = 1 /*declare*/; numbers <= 10/*initialise*/; numbers ++/*increment*/)
{
num1 = Integer.parseInt(JOptionPane.showInputDialog("Input any number:"));
totalNum = totalNum + num1;
}
//Output
JOptionPane.showMessageDialog(null, "Total = " + totalNum);
Try this way I only re-edit your code:
import javax.swing.*;
public class InputNums {
public static void main(String[] args) {
int total = 0;
for (int i = 0, n = 0; i < 10;) {
boolean flag = false;
try {
n = Integer.parseInt(JOptionPane
.showInputDialog("Input any number:"));
} catch (NumberFormatException nfe) {
flag = true;
}
if (flag) {
flag = false;
JOptionPane.showMessageDialog(null,
"Invalid no Entered\nEnter Again...");
continue;
}
total += n;
i++;
}
JOptionPane.showMessageDialog(null, "Total = " + total);
}
}

I am getting error messages concerning my coding. I know Scanf is not a java function, so I am hoping to get help converting it

I know that scanf is not a java function, so i'm hoping someone can help me to understand how to convert this. Research on this topic is difficult to piece together.
This is my code:
import java.util.Scanner;
public class Average {
Scanner Scanner = new Scanner (System.in);
int main (){
int counter;
int number;
int total;
float average;
total = 0;
counter = 0;
System.out.println("Enter the number 0 to end: ");
Scanf("%d", &number);
While (number != 0) {
total = total + number;
counter = counter + 1;
System.out.println("Enter the number 0 to end: ");
Scanf("%d", &number);
}
if(counter != 0) {
average = (float) total / counter;
System.out.println("Average is %.2f\n", average);
} else {
System.out.println("No valid numbers have been entered.");
return 0;
}
}
}
use input like this`
public class seting{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);`
int total = 0;
System.out.printlnln("Enter the value of total :");
total = scan.nextInt(); // use integer input
}
}
You cannot use the same name for the object as for the class. Change Scanner initialization as follows:
Scanner scanObj = new Scanner(System.in);
Replace all your scanf statements with the below:
number = scanObj.nextInt();
These are the changes done to your code:
import java.util.Scanner;
public class one {
public static void main(String[] args) {
Scanner Scanner = new Scanner (System.in);
int counter;
int number = 1;
int total;
float average;
total = 0;
counter = 0;
while(number != 0){
System.out.println("Enter the number 0 to end: ");
number = Scanner.nextInt();
System.out.printf("%d", number);
total = total + number;
counter = counter + 1;
}
if(counter != 0){
average = ((float)total /(float)counter);
System.out.printf("Average is %.2f\n", average);
}
else{
System.out.println("No valid numbers have been entered.");
//return 0;
}
}
}
First the Scanner takes the value the user entered. number = Scanner.nextInt(); This must be done inside your while loop since its the one that check the condition.
The next thing I changed was average = (float) total / counter;
This casts the total value only to a float. use brackets to both ends.
average = ((float)total /(float)counter); like this

Why doesn't my array work?

I'm very new to java (only been using it for 2 days now), and am trying to make a class that lets you input three numbers, and then outputs the average of all three. When the code is like this the output always equals 0 and I don't know why? I am able to get it to work if I change add "static" to all the public integers, but why do I have to do that? Is there another way I can do it without making them static?
import java.util.Scanner;
public class lettuce
{
public int num1;
public int num2;
public int num3;
public static void main(String args[])
{
lettuce lettuceObject = new lettuce();
int total = 0;
int average;
int array[] = {lettuceObject.num1,lettuceObject.num2,lettuceObject.num3};
lettuceObject.getNum1();
System.out.println(lettuceObject.num1);
System.out.println(array[0]);
lettuceObject.getNum2();
System.out.println(lettuceObject.num2);
System.out.println(array[1]);
lettuceObject.getNum3();
System.out.println(lettuceObject.num3);
System.out.println(array[2]);
for(int counter = 0; counter < array.length;counter++)
{
total = total + array[counter];
}
average = total/array.length;
System.out.println("The average of the three numbers is: " + average);
}
public int getNum1()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type your first number: ");
return num1 = keyboard.nextInt();
}
public int getNum2()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type your second number: ");
return num2 = keyboard.nextInt();
}
public int getNum3()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type your third number: ");
return num3 = keyboard.nextInt();
}
}
The output is 0 because you have never initialized your num(s), you're assigning to them on get(s) which you never call - and you're trying to set them in get(s) which isn't the customary approach.
public int num1 = 3;
public int num2 = 3;
public int num3 = 3;
And you should get 3. A getter should look like
public int getNum1()
{
return num1;
}
A setter should look like
public void setNum1(int num1) {
this.num1 = num1;
}
And then you would customarily name your class Lettuce and call it from main like
Lettuce lettuce = new Lettuce();
lettuce.setNum1(10);
System.out.println(lettuce.getNum1());
You would customarily also make your fields private and access them through your mutator and accessor methods (getters and setters)
private int num1;
private int num2;
private int num3;
You could choose to create a constructor
public Lettuce(int num1, int num2, int num3) {
this.num1 = num1;
this.num2 = num2;
this.num3 = num3;
}
You could also calculate the average from "lettuce" with something like
public double average() {
return (num1 + num2 + num3) / 3.0;
}
Edit
Please don't edit your question like that. Also, consider the order of your operations. Your get methods are what set the values. So call them before you create your array!
lettuceObject.getNum1();
lettuceObject.getNum2();
lettuceObject.getNum3();
// Each of those values is 0 until you call the previous three lines.
int array[] = {lettuceObject.num1,lettuceObject.num2,lettuceObject.num3};
System.out.println(array[0]);
System.out.println(array[1]);
System.out.println(array[2]);
As you are new I will give you some more tips they making this work.
1: The static modifier specifies that you don't need to instanciate a Class to use that attribute (variable or method ).
For example, if you have a class with one static variable:
public class Clazz {
static int variable=1;
}
You may call it without creating an instance of Clazz. System.out.println(Clazz.variable); would compile with no problems.
Otherwise, a non-staticattribute will need an Instance of Clazz to be accessed:
Clazz instanceOfClazz = new Clazz();
System.out.println(instanceOfClazz.variable);
2: The type intis native. So, when you create your array, you are passing no values, and after reading the output, your array is not updated.
3: a double variable would be more precise to store the result of an average.
4: last but not least, your getNum method could be merged into just 1 method receiving the message as parameter, so you hace a best and clear reuse of the code. That can be staticbecause it doesn't need to interact with any object of the class Lettuce (with receive as parameter all it needs to execute and return the integer sent by the user, you can assing the return outside the method)
Ps.: by notation, the class name should start with capital letter.
Your final class would look better this way:
import java.util.Scanner;
public class Lettuce
{
public int num1;
public int num2;
public int num3;
public static void main(String args[])
{
Lettuce lettuceObject = new Lettuce();
int total = 0;
double average;
lettuceObject.num1 = lettuceObject.getNum("Please type your first number: ");
System.out.println(lettuceObject.num1);
System.out.println(array[0]);
lettuceObject.num2 = lettuceObject.getNum("Please type your second number: ");
System.out.println(lettuceObject.num2);
System.out.println(array[1]);
lettuceObject.num2 = lettuceObject.getNum("Please type your third number: ");
System.out.println(lettuceObject.num3);
System.out.println(array[2]);
int array[] = {lettuceObject.num1,lettuceObject.num2,lettuceObject.num3};
for(int counter = 0; counter < array.length;counter++)
{
total = total + array[counter];
}
average = total/array.length;
System.out.println("The average of the three numbers is: " + average);
}
public int getNum(String message)
{
Scanner keyboard = new Scanner(System.in);
System.out.println(message);
return keyboard.nextInt();
}
}
Hope this helped.

Categories