简体   繁体   English

如果指定了总和,如何使Java忽略先前的指令?

[英]How to make Java ignore previous instructions if specified sum is given?

Literally started with Java today, and my professor has given my class the task of modifying some very basic code. 从字面上看,今天从Java开始,我的教授已经给我的班级修改一些非常基本的代码的任务。

I want to modify the code to make it print a message if the sum of n1 and n2 is 666, but I don't want it to print the actual sum or the message that would normally go attached to it. 如果n1和n2的总和是666,我想修改代码以使其显示一条消息,但是我不希望它打印实际的总和或通常附加到它的消息。 I saw somewhere around here that a similar question was asked, but the solution doesn't seem to work for me. 我在这里周围的某个地方看到了类似的问题,但该解决方案似乎对我不起作用。 I have no idea why. 我不知道为什么。 Please help. 请帮忙。

import java.io.Console;
import java.util.Scanner;


public class FirstProgram{

Console t = new Console();

    public static void main(String[] args)
    {

        System.out.println("Hello out there.");
        System.out.println("I will add two numbers for you.");
        System.out.println("Enter two whole numbers on a line:");

        int n1, n2;

        Scanner keyboard = new Scanner(System.in);
        n1 = keyboard.nextInt( );
        n2 = keyboard.nextInt( );

        //This should print normally when the sum is anything BUT 666

        System.out.println("The sum of those two numbers is");
        System.out.println(n1 + n2);

        //If the sum IS 666, I don't want it to print the above lines, just the one below.

        if (n1 + n2 == 666);

        t.println("Nice try, Satan");
    }
}

It gives two major errors: the constructor Console() is not visible, and that I cannot make a static reference to a non-static field t. 它给出了两个主要错误:构造函数Console()不可见,并且我无法对非静态字段t进行静态引用。 I have no idea what any of that means or how to fix it. 我不知道这意味着什么或如何解决。

You should learn how to make conditional statements. 您应该学习如何进行条件语句。 Java will not "ignore" and pass to another thing if you don't tell it how to do that. 如果您不告诉Java如何做到这一点,Java不会“忽略”并传递给另一件事。 Remeber: computer can't do anything if one do not tell it to do and how to do that. 记住:如果计算机不告诉用户要执行的操作以及如何执行操作,则计算机将无法执行任何操作。

You are not initializing n1 and n2, they should be initialized after getting the value from the input. 您没有初始化n1和n2,它们应该在从输入中获取值后进行初始化。

And as said in the comments, always wrap loops, conditional statements within curly braces{} to make sure the code that will be executed be the one inside braces. 如注释中所述,请始终在大括号{}中包装循环和条件语句,以确保将要执行的代码是大括号内的代码。

import java.util.Scanner;

    public class FirstProgramm{

                public static void main(String[] args){

                System.out.println("Hello out there.");
                System.out.println("I will add two numbers for you.");
                System.out.println("Enter two whole numbers on a line:");



               Scanner keyboard = new Scanner(System.in);
               int n1 = keyboard.nextInt( );
               int n2 = keyboard.nextInt( );

               //See? the result is stored inside this variable
               int sum = n1 + n2;


                //If the sum is equal 666 then print the message
                if(sum == 666) {
                    System.out.println("Nice try, Satan");
                }else {
                  //Else if the sum is something else, print it
                System.out.println("The sum of those two numbers is");
                System.out.println(sum);
                }


        }

}

You can even play with the operator that the if uses to evaluates the condition: 您甚至可以与if用来评估条件的运算符一起玩:

        if(sum != 666) { //If sum is `not equal to` 666... if the sum is anything else than 666, print it
                System.out.println("The sum of those two numbers is");
                System.out.println(sum);

            }else {// But if it is 666, print what is inside the parentheses

                System.out.println("Nice try, Satan");
            }

I will try to help you out here. 我会在这里帮助您。

Firstly: the constructor Console() is not visible 首先: the constructor Console() is not visible

I think this is in reference to the fact that Console was not really meant to be accessed like that. 我认为这是参考Console并不是真的要这样访问这一事实。 The constructor of Console is private , meaning that outside classes cannot access it. Console的构造函数是private ,这意味着外部类无法访问它。 To remedy this issue, when you want to print to the console, use System.console . 要解决此问题,当您想打印到控制台时,请使用System.console

Secondly: I cannot make a static reference to a non-static field t 其次: I cannot make a static reference to a non-static field t

This one is a bit difficult to explain to someone new. 这对新人来说有点难以解释。 Your main function is static , which means it can be accessed without having to instantiate the class that contains it. 您的main功能是static ,这意味着无需实例化包含它的类就可以对其进行访问。 Your variable t is a instance variable, meaning that it can be accessed by every function in the class when the class has be initialized. 变量t是一个实例变量,这意味着在初始化类后,类中的每个函数都可以访问它。 However, because the main function is static , you cannot access a non-static variable, because it may not be initialized yet. 但是,由于main函数是static ,因此您无法访问非静态变量,因为它可能尚未初始化。 If you want to access a instance variable in a static function, you need to make that variable static as well, making it a class variable, which will always be accessible. 如果要在static函数中访问实例变量,则还需要将该变量也设置为static ,使其成为始终可访问的类变量。

Lastly 最后

To getting your code working, you need to read up on if statements. 为了使代码正常工作,您需要阅读if语句。 This is a conditional statement that is basically asking if this statement is true, do this . 这是一个条件语句,基本上是在询问if this statement is true, do this There is an else if and else statements as well that say else if this statement is true, do this and else do this . 还有一个else ifelse语句, else if this statement is true, do this else do this

Example of proper if / else if / else statement: 正确的if / else if / else语句的示例:

if(iAmTrue == true)
{
    //do this
}
else if(theOtherIAmTrue == true)
{
    //do this
}
else
{
    //do this because everything else was not true
}

So to fix your code, you would need to do this: 因此,要修复您的代码,您需要执行以下操作:

if(n1 + n2 == 666)
{
    System.out.println("Nice try, Satan");
}
else
{
    //Put your other print message(s) here.
}

I have rewritten the code for you with a few recommendations to achieve what you need. 我为您重写了代码,并提供了一些建议,以实现您所需的功能。

import java.util.Scanner;

public class FirstProgram {
  // I have removed the Console variable, you don't need that.
  // System.out.println prints to the console.

  // Use constants for any number or string used to give them meaning
  private static final int DEVILS_NUMBER = 666;

  public static void main(String[] args) {
    System.out.println("Hello out there.");
    System.out.println("I will add two numbers for you.");
    System.out.println("Enter two whole numbers on a line:");

    Scanner keyboard = new Scanner(System.in);
    // declare variables next to where they are used.
    // additionally, never declare more than one variable per line.
    // never do this: int n1, n2;
    int n1 = keyboard.nextInt();
    int n2 = keyboard.nextInt();
    // store the sum in a variable so you can refer to it without doing the sum many times
    int sum = n1 + n2;

    //If the sum IS DEVILS_NUMBER, I don't want it to print the above lines, just the one below.
    // always test the positive possibility first, never the negation
    if (DEVILS_NUMBER == sum) {
      System.out.println("Nice try, Satan");
    } else {
      //This should print normally when the sum is anything BUT DEVILS_NUMBER
      System.out.println("The sum of those two numbers is");
      System.out.println(n1 + n2);
    }
}

Last but not least, have a look at Java Google Style for tips on how to properly format your code. 最后但并非最不重要的一点,请查看Java Google Style,以获取有关如何正确设置代码格式的提示。 If you are using an IDE like Eclipse, Intellij or NetBeans it can automatically format the code for you. 如果您使用的是Eclipse,Intellij或NetBeans之类的IDE,它将自动为您设置代码格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM