Java , variable cant be read after If selection - java

I have a problem here , I want to print the hp2 but it says error. How can I solve this problem? How can I print that hp2 without an error? Thank you and sorry for my bad english.
import java.util.Scanner;
public class lala {
public static void main (String []args) {
Scanner scan = new Scanner(System.in);
int hp=100;
int hp1;
int go=10;
int a;
hp1=hp-go;
System.out.println(hp1);
a=scan.nextInt();
int hp2;
if (a==1) {
hp2=hp1-10;
} else {}
System.out.println(hp2);
}
}

Initialize the local variable. If you don't initialize the local variable then you get compile time error.
int hp1 = 0;
int hp2 = 0;
int a = 0;
Initialize all local variable and the hp1 because if condition become false then this variable become uninitialize and bottom you are printing it.

import java.util.Scanner;
public class Test
{
public static void main (String []args)
{
Scanner scan = new Scanner(System.in);
int hp=100;
int hp1;
int go=10;
int a;
hp1=hp-go;
System.out.println(hp1);
a=scan.nextInt();
int hp2 = 0;
if (a==1)
{
hp2=hp1-10;
}
else
{
}
System.out.println(hp2);
}
}

Initialize each and every variable before u use it in any of the part of the application

Initialize each of the variables. At least give each variable that isn't currently assigned a value a 0.

Related

How to make the array size 6 in the following program by passing it like I did here?

I am practising dynamic coding so I want to create a list for class. I hereby Initialized a list for class and want to create an array with different length for each iteration in list. But It doesnt initialize it like I expected instead its length says 0.
import java.io.*;
import java.util.*;
class testcase
{
int N;
int play []= new int [N];
int villain[]=new int [N];
String status;
}
public class Main {
public static void main(String args[] ) throws Exception {
List<testcase> caseno=new ArrayList<testcase>();
Scanner sc=new Scanner(System.in);
int n1=1;
//int n1=sc.nextInt();
int i,j;
testcase t;
for(i=0;i<n1;i++)
{
int n=6;
//int n=sc.nextInt();
t=new testcase();
t.N=n;
System.out.println(t.N+" "+t.play.length);
}
}
}
The array length should print 6 instead it shows 0
You have to create a parametrized constructor in which you'll pass the value of N and then initilaze the arrays. Like
class testcase // Name should be in PASCAL
{
int N;
int [] play;
int [] villain;
String status;
public testcase (int n) { // Constructor
this.N=n;
play = new int [N];
villain=new int [N];
}
}
And in the main methos you create object like this
int n= . . .;//taking input from user
testcase t=new testcase(n);
You need to write a constructor which does these assignment based on the value passed.
// Implement your constructor something like this
public Testcase(int value) {
this.N = value;
play = new int [value];
// Some more assignment based on the need
}
And after that, you need to create the object instance
int N = 6;
Testcase newTestcase = Testcase(N);
NOTE: Clase name should always start with a capital letter.
Try declaring these variable like N, status, play e.t.c as private. After that assign and access them using getter() and setter().

'.class error' in java

Hi there I am super new to coding and I keep getting a '.class' error when I try to run the code below. What am I missing?
import java.util.Scanner;
import java.util.Scanner;
public class PeopleWeights {
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
userWeight = new int[5];
int i = 0;
userWeight[0] = 0;
userWeight[1] = 5;
userWeight[2] = 6;
userWeight[3] = 7;
userWeight[4] = 9;
System.out.println("Enter weight 1: ");
userWeight = scnr.nextInt[];
return;
}
}
This is the problem
userWeight = scnr.nextInt[];
Solve this by:
userWeight[0] = scnr.nextInt(); //If you intended to change the first weight
OR
userWeight[1] = scnr.nextInt(); //If you intended to change the value of userWeight at index 1 (ie. the second userWeight)
Should work
PS: As a precaution do not import the Scanner class twice. Doing it once would be enough
I understood your intension and below are two possible ways to implement your thought:
I see you are giving values manually as userWeight[0]=0;
If you wanna give manually I suggest not to go with scanner as below.
public static void main(String[] args) {
int[] userWeight={0, 5, 6,7,9};
System.out.println("Weights are" +userWeight);//as you are giving values.
}
If your intension is to get values at run time or from user, please follow below approach
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("This is runtime and you need to enter input");
int[] userWeight = new int[5];
for (int i= 0; i < userWeight.length; i++) {
userWeight[i] = sc.nextInt();
System.out.println(userWeight[i]);
}
}
PS:
I seen you are using util package import for two times, instead you may import all at once as import java.util.*;
Also you are trying to return. Please note for void methods its not need for return values. VOID excepts nothing in return.
First of all do not import packages more than once, now lets go to the actual "bugs".
Here:
import java.util.Scanner;
public class PeopleWeights {
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
int userWeight[] = new int[5];//You need to declare the type
//of a variable, in this case its int name[]
//because its an array of ints
int i = 0;
userWeight[0] = 0;
userWeight[1] = 5;
userWeight[2] = 6;
userWeight[3] = 7;
userWeight[4] = 9;
System.out.println("Enter weight 1: ");
userWeight[0] = scnr.nextInt();//I belive that you wanted to change
// the first element of the array here.
//Also nextInt() is a method you can't use nextInt[]
//since it doesn't exists
//return; You dont need it, because the method is void, thus it doesnt have to return anything.
}
}
Also instead of this:
userWeight[0] = 0;
userWeight[1] = 5;
userWeight[2] = 6;
userWeight[3] = 7;
userWeight[4] = 9;
you can do this during the declaration of an array:
int userWeight[] = {0,5,6,7,9};//instantiate it with 5 integers

Is it possible to acces a method int inside another method?

First of all I am new to JAVA, so I still dont understand everything and how it works. But I was working on something and was wondering if it could be done like this.
import java.util.Scanner;
public class Main {
public static int calc(){
Scanner sc = new Scanner(System.in);
String number1 = sc.nextLine();
int y = Integer.parseInt(number1);
System.out.println("+");
String number2 = sc.nextLine();
int z = Integer.parseInt(number2);
int Result = y + z;
sc.close();
return Result;
}
public static void printText(){
System.out.println(Result);
}
public static void main(String args[]) {
calc();
printText();
}
}
In the first method I was calculating the "Result" and in the second I just wanted it to make it so that it takes the "Result" and prints it.. but How I understand is that what happens in a method stays in the method. But I was wondering if it is possible to let method "printText" access the int from "calc".
I know I could place the code into the main and print it from there, but still it buggs me if it could be done like that :)
You can't access a local variable from a different method, no. (Once the method has completed, the local variable doesn't exist any more.) However, you can use the return value from your calc method, and pass that to the printText method:
public static void printText(int result) {
System.out.println(result);
}
public static void main(String args[]) {
int result = calc();
printText(result);
}
In order to do something like that1, you would need to give Result visibility. Since your methods are static it would also need to be static. Also, don't call close on a Scanner wrapping System.in (that's a global, and you can't re-open it). Something like,
private static int Result;
public static int calc(){
Scanner sc = new Scanner(System.in);
String number1 = sc.nextLine();
int y = Integer.parseInt(number1);
System.out.println("+");
String number2 = sc.nextLine();
int z = Integer.parseInt(number2);
Result = y + z;
return Result;
}
1As opposed to using the returned value, or passing it into your second method.

Loop not recognizing variables previously defined

I'm working on a Guessing Game that will uses arrays to store both the names of all the players and their guesses. I'm fairly new to arrays, so my plan to get user input into the array was to get them to enter the amount of people playing, set that up as a variable and then use a loop to keep asking for names until I reached the necessary amount of names for the stated number of players. However, I am running into what probably is a very simple problem with the loop. Here's a small bit of my code thus far:
public class GuessGame {
int w = 0;
int[] Players = new int[100];
String[] PlayerNames = new String[100];
String numStart = JOptionPane.showInputDialog("How many players?");
int j = Integer.parseInt(numStart);
while (w <= j)
{
String Name = JOptionPane.showInputDialog("What is your name?");
PlayerNames[w] = Name;
w++;
}
The problem is, I'm getting an error regarding the variables in my loop, w and j. The error statement says something to the effect of it cannot find the symbols for class w or class j. I don't intend for them to be classes, and I've run similar code in other projects without a hitch, so I really don't know what's going wrong here. I'm sure it's something stupidly simple, but *'ve been stuck at this wall for some time now and can't really progress until I get this sorted. This is part of a project with three separate classes. The class posted here, a Player class, and a Tester class, which is my main method. I had the whole thing working in a more simplified form earlier, but now I need to adjust it for actual player input and the arrays. Regardless, the tester class is supposed to be my main class. I am using Netbeans if it matters. Thank you. Here are the other two classes for reference:
package GuessGame;
public class GameLauncher {
public static void main(String[] args) {
GuessGame game = new GuessGame();
game.startGame();
}
}
and
package GuessGame;
import java.util.Random;
public class Player {
int number = 0; //where guess goes
String name;
public void guess() {
Random r = new Random();
number = 1 + r.nextInt(21);
System.out.println("I'm guessing " + number);
}
}
All your code needs to be in a method. You cannot have anything except variable declarations at the class level. Move all this into a method, for example public static void main(String[] args) main method.
public class GuessGame {
public static void main (String[] args)
{
int w = 0;
int[] Players = new int[100];
String[] PlayerNames = new String[100];
String numStart = JOptionPane.showInputDialog("How many players?");
int j = Integer.parseInt(numStart);
while (w <= j)
{
String Name = JOptionPane.showInputDialog("What is your name?");
PlayerNames[w] = Name;
w++;
}
}
}
public class GuessGame {
public void getPlayerName()
{
int w = 0;
int[] Players = new int[100];
String[] PlayerNames = new String[100];
String numStart = JOptionPane.showInputDialog("How many players?");
int j = Integer.parseInt(numStart);
while (w <= j)
{
String Name = JOptionPane.showInputDialog("What is your name?");
PlayerNames[w] = Name;
w++;
}
}
public static void main (String[] args)
{
GuessGame gg = new GuessGame();
g.getPlayerName();
}}
You can put in the methos as well and execute in the main method. But, if you declaring any variable inside the method (local variable), the variable must be initialised. Refer here for more details.
public class GuessGame
{
static int w = 0;
int[] Players = new int[100];
static String[] PlayerNames = new String[100];
public static void main(String[] args) {
// TODO Auto-generated method stub
String numStart = JOptionPane.showInputDialog("How many players?");
int j = Integer.parseInt(numStart);
while (w <= j)
{
String Name = JOptionPane.showInputDialog("What is your name?");
PlayerNames[w] = Name;
w++;
}
}
}
Everything should be in a method except variables.Class is template for variables and methods !!

I have an error with a math operation Java?

I created a code that is meant to accept a user-input then add 5 to it, this is the code. When I enter any number, It returns 0. EDIT: I moved the reCalculate down under main, nothing changes
package files;
import java.util.*;
public class CalculatorTest {
static Scanner userFirstNumber = new Scanner(System.in);
static int numberReCalculated;
public static int reCalculate(int a){
int numberReCalculated = a + 5;
return numberReCalculated;
}
public static void main(String[] args){
int bobson;
System.out.print("Enter a number, I will do the rest : ");
bobson = userFirstNumber.nextInt();
reCalculate(bobson);
System.out.println(numberReCalculated);
}
}
Your declaration of int numberReCalculated = a + 5; shadows the field declaration static int numberReCalculated;. Either change int numberReCalculated = a + 5; to numberReCalculated = a + 5;, or rewrite the entire code to be idiomatic and organized:
public class CalculatorTest {
static Scanner userFirstNumber = new Scanner(System.in);
public static int reCalculate(int a){
return a + 5;
}
public static void main(String[] args){
int input;
System.out.print("Enter a number, I will do the rest : ");
input = userFirstNumber.nextInt();
int result = reCalculate(bobson);
System.out.println(result);
}
}
I have no idea how "bobson" is a descriptive and self-documenting variable name.

Categories

Resources