I don't understand why this runs but does not print anything. (I am new to coding altogether, so any advice is great.)
import java.util.Scanner;
import java.util.Random;
public class ArrayDoubleValues{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
// Length input
System.out.println("Length: ");
int length = scan.nextInt();
int[] list = new int[length];
for (int i = 0; i == list.length; i++){
list[i] =(int)(Math.random()+ 1) * 100;
System.out.print(list.length);
}
for(int i = 0; i == list.length; i++){
System.out.println(list[i]);
}
}
}
You have a wrong condition here --
for (int i = 0; i == list.length; i++){
Your program never enters these loops because i is not equal to list.length when you reach them. Instead, it should be
for (int i = 0; i < list.length; i++) { ... }
Related
g cannot be resolved to a variable is the error popping up. I've initialised g in the for loop, so why this error ? I'm a beginner, so can anybody explain in as many simple and understandable words as possible.
import java.util.Scanner;
public class Bellman {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of nodes");
int n = sc.nextInt();
System.out.println("Enter the cost matrix");
for (int j = 0; j<n; j++) {
for (int k = 0; k<n; k++) {
int g[j][j] = sc.nextInt();
}
}
}
}
g cannot be resolved to a variable. I've initialised g in the for loop, so why this error ?
this is most likely what you want to achieve:
int g[][] = new int[n][n];
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
g[j][k] = sc.nextInt();
}
}
You have to initialize the array with a specific size, only then you can assign values at a given indexes.
I had an assignment for a class where I had to develop a simple number sort program.
My main is supposed to receive the user input and my sort class is supposed to interrupt and spit out the resulting numbers in ascending and descending order. The problem is that my main is taking the input but it's not putting it in order at all and I'm unsure why.
package main;
import sort.Sort;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int arr[] = new int[5];
Scanner myScanner = new Scanner(System.in);
for(int i=0; i<5; i++) {
System.out.print("Enter a number: ");
myScanner.nextLine();
}
Sort sortObj = new Sort();
sortObj.ascendingsort(arr);
}
}
package sort;
public class Sort {
public void ascendingsort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n-1; i++)
{
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
void descendingsort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n-1; i++)
{
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
}
I know I'm missing something in my Main, because I'm fairly certain I don't need to put anything else into the sort class.
You're code is perfect. You just missed one assignment in your main method.
Instead of myScanner.nextLine(); you should have written arr[i] = myScanner.nextLine();
myScanner.nextLine(); is getting the next line you enter in the console but it isn't saving it anywhere. arr[i] = myScanner.nextLine(); will save the value of the console in the arr array.
Everything else should work after that.
First you are getting user input using myScanner.nextLine() but not storing it. myScanner.nextLine() won't save anything which user enters .
Thus you need to store it in an array and then use it later. So your main method after the changes should be like this.
public static void main(String[] args) {
int arr[] = new int[3];
Scanner myScanner = new Scanner(System.in);
for(int i=0; i<3; i++) {
System.out.print("Enter a number: ");
arr[i] = myScanner.nextInt();
}
Sort sortObj = new Sort();
sortObj.ascendingsort(arr);
}
And your sorting functions are also wrong. There you do some mis-calculations and return / log nothing. Thus you will not see anything in the console if you are not logging or returning anything.
public void descendingsort(int array[]) {
int n = array.length;
int i, j, temp;
for (i = 0; i < ( n- 1 ); i++) {
for (j = 0; j < n - i - 1; j++) {
if (array[j] < array[j+1])
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
for (i = 0; i < n; i++){
System.out.println(array[i]);
}
}
public void ascendingsort(int array[]) {
int n = array.length;
int i, j, temp;
for (i = 0; i < ( n- 1 ); i++) {
for (j = 0; j < n - i - 1; j++) {
if (array[j] > array[j+1])
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
for (i = 0; i < n; i++){
System.out.println(array[i]);
}
}
I hope this functions will work for your use case of ascending and descending sort.
I need to populate a double array with user input by using nested while loops only. This is what I have so far:
public static double[][] score() {
int col = 3;
int row = 3;
int size = 0;
Scanner in = new Scanner(System.in);
double[][] scores = new double[row][col];
System.out.println("Enter your scores: ");
while (in.hasNextDouble() && size < scores.length) {
while (size < scores[size].length) {
scores[][] = in.hasNextDouble();
size++;
}
return scores;
}
The most common way to do this is through for loops since they allow you to specify the index counters you need in a concise way:
for(int i = 0; i < scores.length; i++){
for(int j = 0; j < scores[i].length; j++){
scores[i][j] = in.nextDouble();
}
}
If you specifically need to use while loops you can do pretty much the same thing, its just broken up into multiple lines:
int i = 0;
while(i < scores.length){
int j = 0;
while(j < scores[i].length){
scores[i][j] = in.nextDouble();
j++;
}
i++;
}
I am writing a small program that reads the input and sets an array size, fills in the array and adds the numbers. My problem is that while I don't get any errors the program stops after the while. Any pointers as to what I am doing wrong would be very appreciated.
public class test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] numbers = new int[in.nextInt()];
int sum = 0;
System.out.println("\n" + "numbers: " + numbers.length);
while (in.hasNextLine()) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = in.nextInt();
// System.out.println(numbers[i]);
}
}
for (int i = 0; i <= numbers.length; i++) {
sum += numbers[i];
}
System.out.println(sum);
}
}
As the JavaDoc for Scanner.hashNextLine() states:
Returns true if there is another line in the input of this scanner.
This method may block while waiting for input. The scanner does not
advance past any input.
So your while loop will never finish:
while (in.hasNextLine())
Just remove this loop, your for loop inside is already doing the right job.
PS: And as jipr311 stated fix your second for loop or you will face an ArrayIndexOutOfBoundsException:
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
the while loop is not needed
for (int i = 0; i < numbers.length; i++) {
if(in.hasNextInt())
numbers[i] = in.nextInt();
// System.out.println(numbers[i]);
}
There is no use of while loop. Remove that.
And edit the for loop like
for (int i = 0; i < numbers.length; i++)
This should work:
public static void main(String[] args) {
Scanner in = null;
try{
in = new Scanner(System.in);
int[] numbers = new int[in.nextInt()];
int sum = 0;
System.out.println("\n" + "numbers: " + numbers.length);
int count = 0;
while (count < numbers.length) {
numbers[count] = in.nextInt();
count++;
}
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
System.out.println(sum);
}finally{
if(null != in){
in.close();
}
}
}
There also was a resource leak in the program as scanner object was not closed. I have corrected it.
So I have to fill a 2D array with chars, print out the array, let people search for words, and then print out the number of instances of that word and the array with the instances of that word highlit.
here is my code so far:
import java.util.Scanner;
import java.util.*;
public class testSearchMatrix {
public static void printArray(char[][] myArray){
for(int i = 0; i < myArray.length; i++){
for(int j = 0; j < myArray.length; j++){
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
}
public static void searchArray(char[][] a){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a query to search: ");
String query = keyboard.next();
int queryNum = 0;
int w = 0;
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[i].length; j++){
if(a[i][j] == query.charAt(w)){
queryNum += 1;
}
}
}
System.out.println(queryNum);
}
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
Random random = new Random();
//Create an alphabet array so I can use this to fill in the searchBox array
char[] alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
System.out.println("Please choose an array size: ");
int a = keyboard.nextInt();
//Create a square array
char[][] searchBox = new char[a][a];
//Fill in the array with random chars
for(int i = 0; i < searchBox.length; i++){
for(int j = 0; j < searchBox[i].length; j++){
int randNum = random.nextInt(25);
searchBox[i][j] = alphabet[randNum];
}
}
//Implement my method to print the array to the screen
System.out.println("Here is the square matrix with random letters: ");
printArray(searchBox);
System.out.println("Enter a query to search: ");
searchArray(searchBox);
}
}
This will print out my array but I can't seem to get the search to work.
Modified Your searchArray function
public static void searchArray(char[][] a){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a query to search: ");
String query = keyboard.next();
int queryNum = 0;
String out = null;
int w = 0;
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[i].length; j++){
if(a[i][j] == query.charAt(w)){
//System.out.println(i+":"+j+a[i][j]);
//w+=1;
if(out==null)
{
out=String.valueOf(a[i][j]);
}else
out=out+a[i][j];
for(int f = 1; f < query.length(); f++){
if(j+f<5){
if(a[i][j+f] == query.charAt(w+f)){
// System.out.println(i+"Index:w+f"+w+f+query.charAt(w+f)+"query.charAt(w+f)Index"+query.indexOf(query.charAt(w+f)));
// System.out.println(i+":"+j+a[i][j+f]);
out=out+a[i][j+f];
System.out.println(out+":"+query+"here"+out.length()+query.length());
if(out.equals(query))
{
System.out.println("Seach Found ");
queryNum += 1;
out=null;
}
}
}
} if(out!=null)
if(out.equals(query))
{
System.out.println("Seach Found ");
queryNum += 1;
out=null;
}
out=null;
}
}
}
System.out.println(queryNum);
}
OuptPut