Question

Greetings Gentelmens ; So i have an object MilkBottle and i want to give it an input using the java scanner. Where is my error ?

import java.util.Scanner;

public class MyClassBottle{

 String material;
 String volume;

 public static void main(String[] args){
 Scanner input = new Scanner(System.in);
 MyClassBottle MilkBottle = new MyClassBottle();
 System.out.println("Enter bottle material: ");
 Scanner one = MilkBottle.material, next();
 System.out.println("Enter bottle volume:  ");
 Scanner two = MilkBottle.volume, next();

System.out.println(MilkBottle.material);
System.out.println(MilkBottle.volume);

 }
}

I am still a noob so don t blame too much for my code !

P.s. Thank you in advance !

Was it helpful?

Solution

That's not valid Java. You need to use assignments to assign the return values of the scanner:

MyClassBottle MilkBottle = new MyClassBottle();
System.out.println("Enter bottle material: ");
MilkBottle.material = input.next();
System.out.println("Enter bottle volume:  ");
MilkBottle.volume = input.next();

That being said, the goal of this website is to make the asker a better programmer, so I'll point out other things that can be improved:

  • Naming conventions: Class names are capitalized, variable names are not. MyClassBottle MilkBottle = new MyClassBottle(); should be MyClassBottle milkBottle = new MyClassBottle(); and all accesses to MilkBottle should get the lowercase name.
  • Types: As String, your bottle's volume could be "1.2", "100000000000000", "15L", or "green eggs and ham". You should use a more useful type for this like int for integers or double for decimal values, and use nextInt() or nextDouble() on the scanner instead.
  • Constructors can be used to more cleanly create instances of MyClassBottle. Read scanner input to local variables then pass to constructor,
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top