Error when looping on keyboard input - java

I have a loop that is supposed to store information into an array of objects, but for some reason, it always skips the first input.
public class GerbilData {
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("How many different food items do the gerbils eat?");
int n1 = keyboard.nextInt();
Food[] gerbilFood = new Food[n1];
String temp;
int temp2;
int count = 1;
for (int a = 0; a < n1; a++){
gerbilFood[a] = new Food();
}
int j = 0;
while (j < n1){
System.out.println("Name of food item " + count + ":");
temp = keyboard.nextLine();
gerbilFood[j].setName(temp);
count++;
j++;
}

keyboard.nextInt() is only reading an integer from the keyboard, not reading the return character. So, when you first call keyboard.nextLine() you get the \n of the getInt().
Try this instead :
int n1 = keyboard.nextInt();
keyboard.nextLine();

Related

Finding the minimum of scanner input in a method

I am trying to find the minimum of a variable input of the scanner class. I have as many inputs as the user wants but I cannot seem to find out how to find the minimum of multiple inputs. Any help would be appreciated.
public static void minimum(int count)
{
double input;
boolean lessThan;
double lesser = 0;
for(count = count; count > 0; count--)
{
System.out.print("Enter a double: ");
input = console.nextDouble();
lessThan = input < input;
if(lessThan = true)
{
lesser = input;
}
else
{
lesser = input;
}
}
System.out.println("The minimum is " + lesser);
}
public static void main(String [] args){
Scanner scanner = new Scanner(System.in);
System.out.println("How many inputs?: ");
int answer = scanner.nextInt();
int arr[] = new int[answer];
int y = 0;
while(y < answer){
System.out.println("Enter a value: ");
arr[y] = scanner.nextInt();
y++;
}
int smallNum = arr[arr.length - 1];
for(int i = arr.length; i > 0; i--){
if(smallNum > arr[i - 1]){
smallNum = arr[i - 1];
}
}
System.out.println("Minimum is: " + smallNum);
}
Here is the answer but my answer is a little bit different. Firstly I created an initialized array because we need to execute the code several times, then I stored the user inputs into the array after that I found the min value using array indexes.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double arr[] = new double[5];
for (int i = 0; i < arr.length; i++) {
System.out.println("Enter the double");
arr[i] = scanner.nextDouble();
}
double min = arr[0];
for (int j=0;j<arr.length;j++){
if(arr[j]<min)
min=arr[j];
}
System.out.println("min value is"+" "+min);
}

Multiplication based on input integer and return array- Need help in storing array while looping

Do multiplication based on user input integer and return array in Java.
Eg: User Input 2
1*1=1
1*2=2
2*1=2
2*2=4
Output array should have [1,2,2,4]
Scanner scan = new Scanner (System.in);
int value = scan.nextInt();
int totalSize= value * value ;
int [] a= new int [totalSize];
for(int i=1; i<=totalSize;i++)
{
for(int j=1;j<=value ;j++)
{
a[i-1]=i*j;
}
How to proceed ?
Try this
System.out.println("Enter number of entries");
Scanner scan = new Scanner (System.in);
int i,j,k,index=0;
int value = scan.nextInt();
int totalSize= value * value ;
int [] a= new int [totalSize];
for(i=1; i<=value;i++) {
for (j = 1; j <= value; j++) {
a[index++] = i * j;
}
}
for(k=0; k<totalSize;k++) {
System.out.println(a[k]);
}

Java exception error for input string

I am a beginner in Java programming. I am trying to write a simple program to take size of input followed by list of numbers separated by spaces to compute the sum.
The first input is getting in fine for the second one system shows error as it is trying to parse a blank string into integer. Can you please help with the mistake I am making?
import java.util.Scanner;
public class InputStringforarray {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print(" Enter size of input ");
int num = scan.nextInt();
System.out.println("Enter data separated by spaces: ");
String line = scan.nextLine();
String[] str = line.split(" ");
int[] A = new int[num];
int sum = 0;
for (int i = 0; i < num; i++)
A[i] =Integer.parseInt(str[i]);
for (int i = 0; i < num; i++)
sum = sum + A[i];
System.out.println("Sum is " + sum);
}
}
The reason you get an exception in your code is because int num = scan.nextInt(); does not process the newline character after the number.
So when the statement String line = scan.nextLine(); is used, it processes the newline character and hence you get an empty string ""
You can either fetch the entire line and parse it to Integer, like this:
int num = Integer.parseInt(scan.nextLine());
or you can go with using nextInt() and then use a blank scan.nextLine() to process the new line after the number, like this:
int num = scan.nextInt();
scan.nextLine();
Your Program has only one error that you were making only one scan object of scanner class, you have to make two scanner class object one will help in getting array size while another will help in getting array element.
import java.util.Scanner;
public class InputStringforarray {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scan1 = new Scanner(System.in); // change 1
System.out.print(" Enter size of input ");
int num = scan.nextInt();`enter code here`
System.out.println("Enter data separated by spaces: ");
String line = scan1.nextLine();// change 2
String[] str = line.split(" ");
int[] A = new int[num];
int sum = 0;
for (int i = 0; i < num; i++)
A[i] =Integer.parseInt(str[i]);
for (int i = 0; i < num; i++)
sum = sum + A[i];
System.out.println("Sum is " + sum);
}
}

Runtime Error on CodeChef KOL1506

When i compiled and ran this code on Eclipse, this runs fine but on Codechef it shows a runtime error. Can anyone help me find why it does not run on the website. The website link is: https://www.codechef.com/viewsolution/10987533
and the problem link is : https://www.codechef.com/problems/KOL1506/
import java.util.Scanner;
class SamosaBhai {
public static void main(String[] args){
int n =0;
Scanner keyboard = new Scanner(System.in);
Scanner input = new Scanner(System.in);
System.out.println("Enter number of test Cases:");
n = keyboard.nextInt();
int[] ans = new int[n];
for(int i = 0; i< n ;i++){
//no. of houses and power 'd' is stored here
String get = input.nextLine();
String[] numarray = get.split(" "); // splitting string by spaces
int num = Integer.parseInt(numarray[0]); // number of houses
int d = Integer.parseInt(numarray[1]); // power to be raised
// positions of the houses is stored here
String entry = input.nextLine();
Scanner scanner = new Scanner(entry);
int[] pos = new int[num];
for (int j= 0;j<num;j++) {
pos[j] = scanner.nextInt();
}
scanner.close();
ans[i] = postalCharge(pos, d, n);
}
keyboard.close();
input.close();
for(int p =0; p<n; p++)
System.out.println(ans[p]);
}
// function to calculate the postal charges between all the houses
public static int postalCharge(int[] location, int d, int n){
int total =0;
for (int i = 0; i<n; i++){
for(int j =0; j< n; j++){
int n1 = location[i];
int n2 = location[j];
total += Math.pow(Math.abs(n1-n2),d);
}
}
return total;
}
}

How do I add user input to an Array in java?

public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int i;
int n;
String a;
System.out.println("Enter the Class:");
a = user_input.next();
System.out.println("Enter the number of Students:");
n = user_input.nextInt();
for (i= 1; i <= n; i++) {
String g = a + i;
System.out.println(g);
}
}
This is my program. It gets user input for the Class and prints the Roll Number for the students.
For example: If the class is 10A and the number of students is 10, it prints a series like 10A1 , 10A2, 10A3 ... 10A10
How do I get the program to store these as elements in an array?
For example:
array[0] = 10A1;
array[1] = 10A2;
array[2] = 10A3;
etc.
Your code should look like this:
public static void main (String args[])
{
Scanner user_input = new Scanner(System.in);
int i;
int n;
String a;
System.out.println("Enter the Class:");
a = user_input.next();
System.out.println("Enter the number of Students:");
n = user_input.nextInt();
String []strings = new String[n]; // Creating an are of string with the given number
for(i= 0; i < n ;){
strings[i] = a + ++i; // Storing strings on to the array !
System.out.println(strings[i-1]);
}
}
You can just edit each index in your current for loop:
String[] arr;
for(i=0; i < n ; i++){
int j = i+1;
String g = a + j;
System.out.println(g);
arr[i] = g;
}
So all your printed g's will be part of the array arr.
First, declare a String array of the appropriate size.
Second, in your for loop, assign the strings you are currently printing, to positions in the array.
String[] things = new String[n];
for (i=1; i <= n; i++) {
String g = a + i;
System.out.println(g);
things[i-1] = g;
}
The strings are now in an array.
Following code is modified, for storing values in array.
public static void main(String[] args) {
// TODO code application logic here
Scanner user_input = new Scanner(System.in);
int i;
int n;
String a;
System.out.println("Enter the Class:");
a = user_input.next();
System.out.println("Enter the number of Students:");
n = user_input.nextInt();
String[] arr = new String[n]; // create string array of size n.
for(i= 1; i <= n ; i++){
String g = a + i;
System.out.println(g);
arr[i-1]=g; // assign your g veriable vale to array index
}
for(String s : arr){
System.out.println(s); // print your array
}
}

Categories

Resources