英文:
Longest Name in the list and Average birth date of all
问题
以下是代码的翻译部分:
import java.util.ArrayList;
import java.util.Scanner;
public class PersonalDetails {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int sum = 0, count = 0;
double avg = 0;
String name;
String[] pcs;
String txt;
while(true){
txt = in.nextLine();
pcs = txt.split(",");
if(txt.equals("")){
break;
}
sum += Integer.valueOf(pcs[1]);
count++;
}
String lng = "";
int low = pcs[0].length();
for(int i=0; i<txt.length(); i++){
if(low < pcs[i].length()){
lng = pcs[i];
}
}
if(count>0){
avg = (double) sum/count;
}
System.out.println("Longest Name: " + lng);
System.out.println("Average of the birth years: " + avg);
}
}
注意:代码中可能存在一些错误,例如循环中的一些逻辑错误,可能需要进一步检查和修复。
英文:
My aim is to calculate the birth date of each person in the list we input as shown below and also output the longest name between them.
Desired output:
sauli,1948
tarja,1943
martti,1936
mauno,1923
urho,1900
Longest name: martti
Average of the birth years: 1930.0
My Code is working but it doesn't output the longest name and correct average.
import java.util.ArrayList;
import java.util.Scanner;
public class PersonalDetails {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int sum = 0, count = 0;
double avg = 0;
String name;
String[] pcs;
String txt;
while(true){
txt = in.nextLine();
pcs = txt.split(",");
if(txt.equals("")){
break;
}
sum += Integer.valueOf(pcs[1]);
count++;
}
String lng = "";
int low = pcs[0].length();
for(int i=0; i<txt.length(); i++){
if(low < pcs[i].length()){
lng = pcs[i];
}
}
if(count>0){
avg = (double) sum/count;
}
System.out.println("Longest Name: " + lng);
System.out.println("Average of the birth years: " + avg);
}
}
`
答案1
得分: 1
name = names.get(0);
for (int i = 1; i < names.size(); i++) {
if (name.length() < names.get(i).length()) {
name = names.get(i);
}
}
/* Another way to resolve your issue is by comparing each input directly and saving it to a variable. */
while (true) {
txt = in.nextLine();
pcs = txt.split(",");
if (name.length() < pcs[0].length()) {
name = pcs[0];
}
if (txt.equals("")) {
break;
}
sum += Integer.valueOf(pcs[1]);
count++;
}
英文:
/* Because you don't save your names to an array and try to get the last input from the scanner which is only empty! to make your program work, you need to initialize an array and save your names to it, after that try to find which name is the longest */
name = names.get(0);
for(int i=1; i<names.size(); i++){
if ( name.length()< names.get(i).length()) {
name = names.get(i);
}
}
/* Another way to resolve your issue is by comparing each input directly and saving it to a variable. */
while(true){
txt = in.nextLine();
pcs = txt.split(",");
if(name.length()< pcs[0].length()) {
name=pcs[0];
}
if(txt.equals("")){
break;
}
sum += Integer.valueOf(pcs[1]);
count++;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论