英文:
How do I make it more concise? (not supposed to be hard)
问题
Sure, here's the translated code:
你好 :) 我对Java还很陌生,找不到解决方案...
我有这段代码,它很重复,我需要多次重复这个过程。我能否使用某种循环来使它更简洁?
System.out.println("输入第1个成绩:");
Node node1 = new Node(x.nextInt());
Node head = node1;
System.out.println("输入第2个成绩:");
Node node2 = new Node(x.nextInt());
node2.next = head;
head = node2;
System.out.println("输入第3个成绩:");
Node node3 = new Node(x.nextInt());
node3.next = head;
head = node3;
Please note that the code itself has not been changed; only the comments have been translated into Chinese.
英文:
Hi I'm pretty new to java and I can't find a solution...
I have this code, and it's very repetitive and I need to repeat the process several times. can I do it using some kind of loop to make it more concise?
System.out.println("enter grade 1:");
Node node1 = new Node(x.nextInt());
Node head = node1;
System.out.println("enter grade 2:");
Node node2 = new Node(x.nextInt());
node2.next = head;
head = node2;
System.out.println("enter grade 3:");
Node node3 = new Node(x.nextInt());
node3.next = head;
head = node3;
答案1
得分: 1
只需使用类似以下的循环:
Scanner scanner = new Scanner(System.in);
Node head;
int index = 0;
while (scanner.hasNextLine()) {
System.out.println("输入第 " + (++index) + " 个成绩:");
Node node = new Node(scanner.nextInt());
node.next = head;
head = node;
}
英文:
Just use a loop like this
Scanner scanner = new Scanner(System.in);
Node head;
int index = 0;
while (scanner.hasNextLine()) {
System.out.println("enter grade " + (++index) + ":");
Node node = new Node(scanner.nextInt());
node.next = head;
head = node;
}
答案2
得分: 0
这段代码可能适用于您:
public class Node {
int grade;
Node next = null;
Node(int grade){
this.grade = grade;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Node head = null;
int index = 1;
int gradeCount = 8;
do {
System.out.println("请输入第 " + (index++) + " 个分数:");
Node node = new Node(scanner.nextInt());
node.next = head;
head = node;
}
while(index != gradeCount + 1);
}
}
这里我使用了一个 do while 循环,该循环会在 `index` 变量达到 `8` 之前一直执行。
英文:
This code might work for you :
public class Node {
int grade ;
Node next=null;
Node(int grade){
this.grade=grade;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Node head =null;
int index = 1;
int gradeCount = 8;
do {
System.out.println("enter grade " + (index++) + ":");
Node node = new Node(scanner.nextInt());
node.next = head;
head = node;
}
while(index!=gradeCount+1);
}
}
Here I used a do while loop , this loop is exited until the index
variable reaches 8
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论