[英]How do I perform two tests with different test values?
I am a college student and this is my first semester learning Java programming.我是一名大学生,这是我学习 Java 编程的第一学期。 For the past few days I've been stuck on some things when learning Java.在过去的几天里,我在学习 Java 时遇到了一些事情。 One activity I'm stuck on for my class is this one:我为 class 坚持的一项活动是:
Retype the statements, correcting the syntax errors.重新键入语句,更正语法错误。
System.out.println("Num: " + songnum);
System.out.println(int songNum);
System.out.println(songNum " songs");
Note: These activities may test code with different test values.注意:这些活动可能会使用不同的测试值测试代码。 This activity will perform two tests: the first with songNum = 5, the second with songNum = 9.此活动将执行两个测试:第一个测试 songNum = 5,第二个测试 songNum = 9。
This is what I have so far:这是我到目前为止所拥有的:
import java.util.Scanner;
public class Errors {
public static void main (String [] args) {
int songNum;
songNum = 5;
System.out.println("Num: " + songNum);
System.out.println("5");
System.out.println("5 " + "songs");
The website we are using called Zybooks says the code above is correct for outputting:我们使用的名为 Zybooks 的网站说上面的代码对于输出是正确的:
Num: 5
5
5 songs
But I can't figure out what to do to output the same but with the number 9. I've tried doing the same 3 lines for it but it says it's not the correct way to do it.但我不知道如何对 output 做同样的事情,但数字为 9。我试过为它做同样的 3 行,但它说这不是正确的方法。 How do output both 5 and 9 for the values? output 5 和 9 的值如何?
Change the 2nd and 3rd print statements to the following:将第 2 和第 3 个打印语句更改为以下内容:
System.out.println(songNum);
System.out.println(songNum + " songs");
The problem was you hardcoded the value of 5
within a string making it impossible to change.问题是您在字符串中硬编码了5
的值,因此无法更改。
You cannot print the number nine with the code that you wrote.您无法使用您编写的代码打印数字九。 if you want to get the number nine then you have to change the code and create a new variable eg x = 9;如果你想得到数字九,那么你必须更改代码并创建一个新变量,例如 x = 9; What you can do something like that:你可以做这样的事情:
import java.util.Scanner;
public class Errors {
public static void main (String [] args) {
int songNum;
songNum = 5;
x = 9;
System.out.println("Num: " + songNum);
System.out.println(songNum);
System.out.println(songNum + " songs");
System.out.println("Num: " + x);
System.out.println(x);
System.out.println(x+ " songs");
Your main issue is that you had cached your value (5) into a string, rendering it unchangeable.您的主要问题是您已将值 (5) 缓存到字符串中,使其不可更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.