Creating a loop for Scanner for arrays - java

I want to create a loop that asks for the Scanner to input each number one after the another for a certain amount in an array (I'm thinking of 10). Any suggestions?
import java.util.Scanner;
public class AssignSeven
{
public static void main(String[] args)
{
int [] array1 = new int[10];
System.out.println("Enter 10 numbers");
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
for (int i = 0; i < 9; i++)
{
array1[i] = a;
}
}
}

change to
for (int i = 0; i < 9; i++)
{
int a = sc.nextInt();
array1[i] = a;
}
or even
for (int i = 0; i < 9; i++)
{
array1[i] = sc.nextInt();
}

It's simple, you can just assign the value of the scanner object's input to the indices of the array:
import java.util.Scanner;
public class AssignSeven
{
public static void main(String[] args)
{
int [] array1 = new int[10];
System.out.println("Enter 10 numbers");
Scanner sc = new Scanner(System.in);
// Where you had the original input
// int a = sc.nextInt();
for (int i = 0; i < 9; i++)
{
// Instead of array1[i] = a; you have
array1[i] = sc.nextInt();
}
}
}
Hope this helped!

Related

Creating a Nth size grid using an array

How would I create an Nth size array where all the values are the same such that it can form a grid. I'm pretty new to coding and just started with arrays.
This is my code so far.
import java.util.Scanner;
public class Array_design {
public static void main(String[] args) {
Scanner Row = new Scanner(System.in);
System.out.println("Enter length of row");
int row = Row.nextInt();
Scanner Col = new Scanner(System.in);
System.out.println("Enter length of column");
int col = Col.nextInt();
// TODO Auto-generated method stub
String[][] GameBoard = new String [row][col];
GameBoard[][] = for (int J = 1; J <= row; J = J + 1) {
for (int I = 1; I <= col; I = I + 1) {
System.out.print("*");
}
// if user input equal declared variable
System.out.println("");
}
}
}
}
You don't need 2 scanners, one will do. Also, if you're only going to store a single character on each space, use a char instead of a String. You should move this to a GameBoard class and create an init() and output() method.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter length of row");
int row = scanner.nextInt();
System.out.println("Enter length of column");
int col = scanner.nextInt();
char[][] gameBoard = new char [row][col];
//Init the board
for (int i = 0; i < gameBoard.length; i++) {
Arrays.fill(gameBoard[i], '*');
}
//output the board
for (int i = 0; i < gameBoard.length; i++) {
System.out.println(Arrays.toString(gameBoard[i]));
}
}
What is going on with your code?
GameBoard[][] = for (int J = 1; J <= row; J = J + 1)
Anyway, the way I would do this is probably
public class Array_design
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in); //initialize Scanner from System.in
System.out.println("Enter length of row");
int row = input.nextInt(); //input row
System.out.println("Enter length of column");
int col = input.nextInt(); //input column
String[][] GameBoard = new String[row][col]; //initialize gameboard
for (String[] arr : GameBoard) for (String s : arr) //enhanced-for loops
s = "*"; //assign a value to every element in GameBoard; change this to whatever
}
}

i m not getting correct output?

import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String[] in = new String[n];
for (int i = 0; i < n; i++) {
in[i] = sc.nextLine();
}
for (int i = 0; i < n; i++) {
System.out.println(in[i]);
}
}
}
Input:
2
Ankit
Output:
Ankit
That's because of the Scanner.nextInt method does not read the newline character in your input created by hitting "Enter" and so the call to Scanner.nextLine returns after reading that newline.
There are two options to resolve this issue,
1. read the input through Scanner.nextLine and convert your input to the proper format you need
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
String[] in = new String[n];
for (int i = 0; i < n; i++)
{
in[i] = sc.nextLine();
}
for (int i = 0; i < n; i++)
{
System.out.println(in[i]);
}
2. Add Scanner.nextLine call after each Scanner.nextInt
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
String[] in = new String[n];
for (int i = 0; i < n; i++)
{
in[i] = sc.nextLine();
}
for (int i = 0; i < n; i++)
{
System.out.println(in[i]);
}
the Scanner class skips next line after nextint so you can fix it by editting your code like this-
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
sc.nextLine();
String[] in=new String[n];
for(int i=0;i<n;i++){
in[i]=sc.nextLine();
}
for(int i=0;i<n;i++){
System.out.println(in[i]);
}
}
}

I have to print the array , but for each loop is not working

import java.util.Scanner;
public class TeacherCoins {
public static void main(String[] args){
int k;
System.out.print("Enter total number of coins :");
Scanner sc = new Scanner(System.in);
k =sc.nextInt();
int [] arr= new int[k-1];
System.out.print("Enter array :");
for(int i=0;i<=(k-1);i++)
{
Scanner sc1 = new Scanner(System.in);
arr[i] =sc1.nextInt();
}
for(int element :arr)
{
System.out.println("Print array");
System.out.println(element);
}
}
I am giving output using Scanner class. But is not printing the array.
You don't need to declare the Scanner again inside the loop. Another thing that you should do to be sure of your code, is to have this condition on the loop if i < arr.length. Lastly, I moved the "Print array" message outside the last for.
public class TeacherCoins {
public static void main(String[] args){
int k;
System.out.print("Enter total number of coins :");
Scanner sc = new Scanner(System.in);
k =sc.nextInt();
int [] arr = new int[k];
System.out.print("Enter array :");
for(int i=0; i<arr.length; i++) {
arr[i] =sc1.nextInt();
}
System.out.println("Print array");
for(int element :arr){
System.out.println(element);
}
}
}
There are two problems with this code,
1. You don't need to create a new Scanner object for each user input.
2. You are declaring an array size of k-1 and then asking user input k times.
public static void main(String[] args) {
int k;
System.out.print("Enter total number of coins :");
Scanner sc = new Scanner(System.in);
k = sc.nextInt();
int[] arr = new int[k]; // To store k elements, you need k sized array
System.out.print("Enter array :");
for (int i = 0; i <= (k - 1); i++) {
// Scanner sc1 = new Scanner(System.in); / / Not required here
arr[i] = sc.nextInt();
}
System.out.println("Print array");
for (int element : arr) {
System.out.println(element);
}
}
There is only one problem in your code you are declaring the size of array as k-1 instead declare it for k elements.You just need to give each inputs in new line. For more refer this :Scanner class.
And your for each loop is correct and working.
import java.util.Scanner;
public class TeacherCoins {
public static void main(String[] args){
int k;
System.out.print("Enter total number of coins :");
Scanner sc = new Scanner(System.in);
k =sc.nextInt();
int [] arr= new int[k];//it was giving java.lang.ArrayIndexOutOfBoundsException
System.out.print("Enter array :");
for(int i=0;i<=(k-1);i++)
{
Scanner sc1 = new Scanner(System.in);//not required
arr[i] =sc1.nextInt();//use arr[i] =sc.nextInt();
}
for(int element :arr)
{
System.out.println("Print array");
System.out.println(element);
}
}
}
Above code will work. But you don't need new scanner objects for taking input, creating only single object will work.
import java.util.Scanner;
public class TeacherCoins {
public static void main(String[] args) {
int k;
System.out.print("Enter total number of coins :");
Scanner sc = new Scanner(System.in);
k = sc.nextInt();
int[] arr = new int[k];
System.out.print("Enter array :");
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
}
sc.close();
System.out.println("Print array");
for (int element : arr) {
System.out.println(element);
}
for (int i = 0; i < arr.length; i++) {
int count = 0;
for (int j = 0; i < arr.length; j++) {
arr[i] = arr[j];
count++;
}
System.out.println(arr[i] + " " + count);
}
}
}

Arrays - static method to return sum, but nothing is returned

Create a Java program that reads 10 numbers from the console Scanner
input = new Scanner(System.in); .Store the numbers as Floats in the array. Create static methods to perform the following actions on the array and returns the result.Add all the items in the array and return the result. Name this method"add".
So this is my code, but when the user inputs the 10 numbers, nothing is returned. Any suggestions?
public static void main(String[] args) {
float[] myArray = new float[10];
Scanner input = new Scanner(System.in);
for (int i = 0; i < myArray.length; i++) {
System.out.println("please enter number");
myArray[(i)] = input.nextFloat();
}
}
public static float add(float[] array) {
float sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i];
}
return sum;
}
You are not calling the method :
public static void main(String[] args) {
float[] myArray = new float[10];
Scanner input = new Scanner(System.in);
for (int i = 0; i < myArray.length; i++) {
System.out.println("please enter number");
myArray[(i)] = input.nextFloat();
}
System.out.println(add(myArray)); // need to make this call
}
At the end of for loop you need to call the add method.
System.out.println(add(myArray));

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;
}
}

Categories

Resources