我在理解使用外部变量的方法调用时遇到了最困难的时期。这是我尝试以打印形式执行的操作,下面我将粘贴两次尝试。当我尝试修复我正在做的事情时,我不断收到相同的错误消息循环。我还希望用户输入一个数字来选择一个选项,我需要在其他地方使用它。这一切都可以在 main 中轻松完成,但我正在尝试练习来回传递参数......
附件是picture详细说明我想要做什么,下面是代码。
import java.util.Scanner;
public class SandwichShop {
private String MOTTO = "Come back for another!";
private int rye = 150;
private int white = 120;
public int decision;
public void breadCals (int r, int w) {
int sel;
r = rye;
w = white;
if (sel == 1) {
System.out.println("you entered 1 " + r);
} else {
System.out.println("you entered 2 ");
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter ");
int decision = input.nextInt();
SandwichShop.decision();
}
}
或者
import java.util.Scanner;
public class TestSandwich {
private int calsR;
private int calsW;
private int ryeB;
private int whiteB;
private int decision = 0;
private int selection;
private String MOTTO = "Come back for another!";
public static void main(String [] args) {
breadType();
//TestSandwich decision = new TestSandwich();
//decision.Display();
}
public static int breadType() {
int ryeB = 1;
int whiteB = 2;
Scanner input = new Scanner(System.in);
//System.out.println("What type of bread do you want?");
//System.out.println("Please enter 1 for Rye and 2 for White");
int decision = input.nextInt();
return decision;
}
public void bCals(){
int calsR = 150;
int calsW = 120;
}
public void Display(int decision) {
int selection = decision;
System.out.println("What type of bread do you want?");
System.out.println("Please enter 1 for Rye and 2 for White");
if (selection == 1) {
System.out.println("Rye bread has " + calsR + " calories.");
} else {
System.out.println("White bread has " + calsW + " calories.");
}
//System.out.println(MOTTO);
}
//!main - btype - display -bcals
/*
public static int calsAmt( int cals) {
TestSandwich.display();
}*/
}
最佳答案
这是对您的第一个代码的快速更改,这样您可能会了解更多。我试图保留你的大部分代码。
public class FirstClass {
public static int decision;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter ");
decision = input.nextInt();
System.out.println(decision);
SecondClass.breadCals(); //gets the method
}}
二等舱
Public class SecondClass{
private static int rye = 150;
private static int white = 120; //static for a call like that
public int decision;
public static void breadCals () {
//method needs to be static to call it like i did
int sel=FirstClass.decision;
int r = rye;
int w = white;
if (sel == 1) System.out.println("you entered 1 " + r);
else if(sel== 2) System.out.println("you entered 2 "+ w);
else System.out.println("Wrong number");
}
}
关于java - 如何在方法调用中传递数据并使用用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51912108/