Home > Back-end >  A novice for help!
A novice for help!

Time:10-06

import java.util.Scanner;
Public class lab2_2 {
Public static void main (String args []) {
System. The out. Println (" Sum="+ sumArray ());
System. The out. Println (" business="+ aveArray ());
}
Public static int [] fillArray () {
Scanner sc=new Scanner(System.in);
String STR=sc. Next ();
Int length=Integer. ParseInt (STR);
An int array []=new int (length),
for(int i=0; i{
String str2=sc. Next ();
Int num=Integer. ParseInt (str2);
Array [I]=num;
}
Return array;
}
Public static int sumArray () {
Int array1 []=fillArray ();
Int sum=0;
for(int i=0; i{
Sum=sum + array1 [I];
}
Return the sum.
}
Public static int aveArray () {
Int array1 []=fillArray ();
Int sum=sumArray ();
Int length=array1. Length;
Int ave=sum/length;
Return ave.
}

}

Why the execution of a program when the main method of the second output does not show

CodePudding user response:

Sc. Next left her a newline after read the content in the input buffer, so if you don't empty the input buffer, next time will read in an empty string
To sc. NextLine

CodePudding user response:

reference 1st floor qybao response:
sc. The next read content after left the newline character in the input buffer, so if you don't empty the input buffer, next time will read in an empty string
To sc. NextLine

But with nextLine won't read the whole line? I want to a read a number

CodePudding user response:

Then you can put all of the data input by a space character on a line, such as
ABC input Spaces def space ghi,,, enter

If it is a one input, use nextLine no problem
The
ABC input enter
Input def enter
,,,

CodePudding user response:

reference qybao reply: 3/f
you are in a line with a space all the data input, such as
ABC input Spaces def space ghi,,, enter

If it is a one input, use nextLine no problem
The
ABC input enter
Input def enter
,,,

I feel it may not seem like the problem is the last method calls a method in the problem

CodePudding user response:

You say you are a one input or a line of input well
One input, one is the question about which a newline
You can use the code to do a test
String STR=sc. Next ();
String str2=sc. The nect ();//a one input, see need not to need you enter here? What is its value?
System. The out. Printf (" STR=% s, str2=% s \ n ", STR, str2);//a, an input str2 can be skipped, and is an empty string

CodePudding user response:

reference 5 floor qybao reply:
you say you are a one input or a line of input well
One input, one is the question about which a newline
You can use the code to do a test
String STR=sc. Next ();
String str2=sc. The nect ();//a one input, see need not to need you enter here? What is its value?
System. The out. Printf (" STR=% s, str2=% s \ n ", STR, str2);//a, an input str2 can be skipped, and is an empty string

I see what you mean thank the teacher for advice
  • Related