Java 程序跳过其中一个输入
当我的程序到达请求水果名称的部分时,它将输出请求名称的字符串,然后立即转到下一个字符串输出,而无需等待用户输入。 这似乎会自动为my name变量分配null值 Fruit.javaJava 程序跳过其中一个输入,java,arrays,eclipse,Java,Arrays,Eclipse,当我的程序到达请求水果名称的部分时,它将输出请求名称的字符串,然后立即转到下一个字符串输出,而无需等待用户输入。 这似乎会自动为my name变量分配null值 Fruit.java public class Fruit { String Name; int Quantity; double Mass; public Fruit(String Name, int Quantity, double Mass) { this.Name = Name
public class Fruit {
String Name;
int Quantity;
double Mass;
public Fruit(String Name, int Quantity, double Mass) {
this.Name = Name;
this.Quantity = Quantity;
this.Mass = Mass;
}
public void Information() {
System.out.println("This fruit is an " + Name + ", there's " + Quantity
+ " of it and it weighs " + Mass + " grams");
}
}
java
import java.util.Scanner;
public class Fruits {
public static void main(String[] args) {
Fruit menu[];
int number;
String name;
int quantity;
double mass;
System.out
.print("How many fruits would you like to add to the menu?: ");
Scanner input = new Scanner(System.in);
number = input.nextInt();
input.nextLine();
menu = new Fruit[number];
for (int i = 0; i < menu.length; i++) {
System.out.println("What would you like to name the fruit?: ");
name = input.nextLine();
System.out.println("How much fruits are there?: ");
quantity = input.nextInt();
System.out.println("What is the mass of the Fruit in grams?: ");
mass = input.nextDouble();
menu[i] = new Fruit(name, quantity, mass);
menu[i].Information();
}
input.close();
}
}
import java.util.Scanner;
公营水果{
公共静态void main(字符串[]args){
水果菜单[];
整数;
字符串名;
整数;
双质量;
系统输出
.print(“您想在菜单中添加多少水果?:”;
扫描仪输入=新扫描仪(System.in);
number=input.nextInt();
input.nextLine();
菜单=新水果[编号];
对于(int i=0;i
问题是扫描整数,然后再扫描下一行。当您运行.nexInt()时,我相信有一个换行符没有被扫描进来,所以这会立即与下面的.nextLine()发生冲突,因为它只接收换行符,后面什么也不接收
我所知道的最简单的解决办法是
number = input.nextInt();
input.nextLine();
menu = new Fruit[number];
然后剩下的代码就可以工作了
另一方面,通常从0开始循环,因为数组从0开始,第一个条目是空的,但我认为在这段特定的代码中这并不重要,问题是扫描int,然后是nextLine。当您运行.nexInt()时,我相信有一个换行符没有被扫描进来,所以这会立即与下面的.nextLine()发生冲突,因为它只接收换行符,后面什么也不接收 我所知道的最简单的解决办法是
number = input.nextInt();
input.nextLine();
menu = new Fruit[number];
然后剩下的代码就可以工作了
另一方面,通常从0开始循环,因为数组从0开始,第一个条目为空,但我认为在这段特定的代码中,这并不重要,而不是
input.nextInt()代码>使用Integer.parseInt(input.nextLine())
。它可能会解决您的问题。而不是input.nextInt()代码>使用Integer.parseInt(input.nextLine())
。它可能会解决您的问题。当您使用input.nextInt()
时,集线器中有一个%n
字符。您需要使用input.nextLine()
after删除换行符。您还可以对每个变量使用input.nextLine()
,然后自己解析它
警告!在java约定中,方法名称、属性名称和参数名称必须以小写字符开头。使用input.nextInt()
时,hub中有一个%n
字符。您需要使用input.nextLine()
after删除换行符。您还可以对每个变量使用input.nextLine()
,然后自己解析它
警告!在java约定中,方法名、属性名和参数名必须以小写字符开头。java中数组中可能重复的位置从0开始编号。我更正了你的代码。啊,是的,谢谢@Jagger。我认为这无关紧要,因为在Java中,数组中的位置可能是从0开始编号的。我更正了你的代码。啊,是的,谢谢@Jagger。我想这没关系,因为我有iYea可以用,谢谢!我也注意到了我的第二个错误,只是修复了它。是的,这很有效,谢谢!我也注意到了我的第二个错误,只是修正了它。你有最好的解释。谢谢你。我现在明白我的问题了,你有最好的解释。谢谢你。我现在明白我的问题了