Click here to Skip to main content
15,895,142 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello guys, after write input variable in running programme, i dont get any reaction.
Eclipse say:
C#
Resource leak: 'sc' is never closed


It is the Code...

C#
package stoneddog;

import java.util.Scanner;

public class StonedDog {

	public static int i = 0; 
	public static void addFood(int i) {
		Scanner input = new Scanner(System.in, "Windows-1250");
		Food [] objFood = new Food[20]; 
		System.out.println("Zadaj nazov jedlo, kalorie, sacharidy a bliekoviny v tomto poradi");
		String name = input.next();
		int calories = Integer.parseInt(input.next());
		int carbohyd = Integer.parseInt(input.next());
		int protein = Integer.parseInt(input.next());;
		objFood[i] = new Food(name, calories, carbohyd, protein); 
	}
		
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in, "Windows-1250");
		System.out.println("Chces pridat jedlo y/n");
		String yeasNo = sc.next();
		if(yeasNo == "y"){
			addFood(i);
		}
		
		if(yeasNo == "n" ){
			System.out.println("Nothing");
		}

	}

}


C#
package stoneddog;

public class Food {
	private int calories; 
	private int carbohyd; 
	private int protein; 
	private String name; 
	
	public Food (String name, int calories, int carbohyd, int protein){
		this.name = name; 
		this.calories = calories; 
		this.carbohyd = carbohyd;
		this.protein = protein; 
	}
}


What I have tried:

I tried change name of Scanner and adjust if(). Nothing worked.
Posted
Updated 16-Dec-16 23:02pm

1 solution

You are comparing the input string (which contains a newline character) with a single character, so both your if statements will fail. You should do something like:
Java
String yeasNo = sc.next();
if(yeasNo.substring(0,1).equals("y")) {
    addFood(i);
}
else if(yeasNo.substring(0,1).equals("n")) {
    System.out.println("Nothing");
}
else {
    System.out.println("Bad input");
}

However, you still have the problem that after calling addFood your program will terminate. And even if you fix that, every time you call addFood it creates a new array of Food objects, but then when the method returns that array is disposed so it no longer exists.

You obviously need more Java study, and I recommend spending time going through The Java™ Tutorials[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900