Java,输出不断在同一行输出

时间:2014-11-15 06:38:48

标签: java constructor while-loop println

我对此程序的问题是,当用户输入相机品牌名称后跟像素数时,程序开始将品牌名称和像素请求放在一行上。我只是希望程序在整个程序中输出和输入相同的内容!

这可能是一个简单的问题;但是,这让我感到困惑。

这是类文件:

public class DigitalCamera {

public String brand;
public int megaPixels;
public int price;

DigitalCamera( String receivedBrand, int pixelsReceived) {
    brand = receivedBrand;
    if (pixelsReceived >= 10)
        megaPixels = 10;
    if (megaPixels <= 6)
        price = 99;
    else
        price = 129;
}

public void returnDigitalCameraDetails() {
    System.out.println("You ordered a " + brand + " camera with " + megaPixels + " megapixels at a cost of $" + price);
    }
}

这是主文件:

import java.util.*;

public class TestDigitalCamera {
public static void main(String[] args) {

Scanner scan = new Scanner(System.in);
String cameraName;
int pixelsForCamera;
int x = 1;

    while (x <= 5) {

System.out.println("Enter in brand of the camera: ");
    cameraName = scan.nextLine();
System.out.println("Enter in the number of pixels: ");
    pixelsForCamera =  scan.nextInt();
DigitalCamera camera(x) = new DigitalCamera(cameraName, pixelsForCamera);
camera(x).returnDigitalCameraDetails();
System.out.println();
x++;
}

2 个答案:

答案 0 :(得分:0)

改变这个:

cameraName = scan.nextLine();

由:

cameraName = scan.next();

答案 1 :(得分:0)

尝试使用此代码作为主要方法:

public static void main(String[] args) {

    String cameraName;
    int pixelsForCamera;
    int x = 1;

    while (x <= 5) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter in brand of the camera: ");
        cameraName = scan.nextLine();
        System.out.println("Enter in the number of pixels: ");
        pixelsForCamera = scan.nextInt();
        DigitalCamera camera = new DigitalCamera(cameraName, pixelsForCamera);
        camera.returnDigitalCameraDetails();
        System.out.println();
        x++;
    }
}