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.
Related
My goal is currently to take a string looking like
"######
# #
# # ##"
# is here my "character" and "#" is walls that should be avoided, I want my character to get out of the box and return the pathway, I realize my example is pretty bad but I hope you understand. The idea I have currently is to read in a text-file with that String, then creating an array as a 2-D grid and then work from there, the code I have currently is:
package soko;
import java.io.*;
import java.util.*;
public class Sokoban2 {
static File file;
Scanner input;
static int b;
static int c;
static String[][] array;
public Sokoban2() {
//array = new String [9][9];
}
public int readFile() throws Exception{
Scanner input = new Scanner(System.in);
file = new File("C:/Users/joaki/Desktop/sokoban/readin.txt");
input = new Scanner(file);
while (input.hasNext()) {
b = b + 1;
String line = input.nextLine();
System.out.println(line);
}
input.close();
return b;
//array = new String[5][5];
}
public void insertStuff() {
//array[1][1]="2";
}
public void printStuff() {
for (int r = 0; r<2;r++){
String line2 = "";
for (int d = 0; d <2;d++){
line2+="["+array[d][r]+"]";
}
System.out.println(line2);
}
}
public static void main(String[] args) throws Exception{
Sokoban g = new Sokoban();
g.readFile();
//g.insertStuff();
//g.printStuff();
//g.creatingGrid(c,b);
//System.out.println(b);
}
}
I really want to print my b, at least check it's value, but my program wont return any value, it's not even returning a null or 0, I've tried to print it as well, no luck there either, ideas ?
You aren't returning the value to any variable, I just ran your code and it works fine, it counts the lines in the file.
int b = g.readFile();
System.out.println(b);
If you don't return the value to a variable you won't have access to the value of b in your main because it's out of scope, more about that here:
https://www.cs.umd.edu/~clin/MoreJava/Objects/local.html
Edit:
I actually just realized that you declared b in your class as static and I decided to run it as you have it above, I still get it printing out the amount of lines.
g.readFile();
System.out.println(b);
If you are going to have your function return a value and you don't plan on storing b then get rid of the static declaration in your class and just declare it in the function that returns b.
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.
String s contains a set of integers separated by white space (blanks, tabs, or newlines). Return the sum of the integers.
You can use a Scanner object to solve this problem. Create a new Scanner(s) and store it in a variable, say in. Then, use in.hasNextInt() to control a while loop. Each iteration of the while loop uses in.nextInt() to get the next integer from the String s. Accumulate this integer into a variable and return that variable when the loop exits.
You may use a main method to test your method by creating an instance of the Calculator class and calling sum(…) with several combinations of values using that instance.
For example, sum(“3 4 5 27 3”) is 42.
I have written this so far:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
}
public int sum(String s){
int i = 0;
Scanner in = new Scanner(s);
while (in.hasNextInt()) {
sum = sum + in.nextInt();
}
return sum;
}
}
To call the method from main and display the results make the sum method static and then call it and print the result:
public static void main(String[] args) {
System.out.println(sum("1 2 3"));
}
import java.util.Scanner;
public class Calculator{
public static void main(String[] args){
System.out.println(sum("1 2 3"));
}
public static int sum(String s){
int i = 0;
int sum = 0;
Scanner in = new Scanner(s);
while (in.hasNextInt()) {
sum = sum + in.nextInt();
}
return sum;
}
}
I was practicing on a bank account program , and I faced this small problem.
I made it as a method the make it easier to understand.
The main method
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
double b=0;
while(b!=-1){
b=in.nextInt();
ddd(b);
}
}
The addition method
public static void Addition(double b){
double g=0;
g+=b;
System.out.println( "GGGGGGGG"+ g );
}
The problem is that I get the same input I enter each time .
I know that the problem from the
double g=0;
Because each time I call the method addition g will be initialized to Zero because of this statement double g=0;, but I should to initial it, or I will get compilation error.
What should I do to fix this problem.
You can make the double g a member of the class by declaring it outside of methods. So here's an example class
class TestClass {
static double g = 0;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double b = 0;
while (b != -1) {
b = scan.nextDouble() //you need to change nextInt() to nextDouble()
add(b);
}
System.out.println(g);
}
public static void add(double b) {
g += b; //g refers to the variable about the main method
}
}
This may not be exactly how your class works, but using the variable g outside of a method makes sure the class retains its value even when the method has ended. Hope this helps!
Initialize it just before the while statement.
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.