Sorting Arrays, duplicate local variable, error - java

I am working on this code all day, and I just can't seem to get it right :(
import java.util.Random;
import java.util.Scanner;
import java.io.*;
public class TrialSixthree{
public static void main(String[]args){
Scanner i = new Scanner(System.in);
int c;
int choice;
Random t = new Random();
for (c = 1; c <= 5; c++) {
System.out.println(t.nextInt(1000));
}
System.out.println(" \n1: BUBBLE SORT ");
System.out.println(" 2: SELECTION SORT ");
System.out.println(" 3: QUICK SORT ");
System.out.println(" Choose a number from 1-3 ");
choice= i.nextInt();
if(choice == 1){
System.out.print("You chose BUBBLE sort!");
System.out.println(x[i]+"");//I don't know what's wrong in this line
for(int i = 0 ; i < x.length-1 ; i++){
for (int j = 0 ; j < x.length-1 ; j++){
if ( x[j] > x[j]){
temp = x[j];
x[j] = x[j+1];
x[j+1] = temp;
}
}
}
} else if(choice == 2){
System.out.print("You chose SELECTION sort!");
System.out.println(x[i]+"");
int temp, min;
for(int i=0;i<x.length-1;i++) {
min = i;
for(int j=i+1;j<x.length;j++) {
if(x[min]>x[j]) {
min = j;
}
if(min!=i) {
temp = x[min];
x[min] = x[i];
x[i] = temp;
}
}
}
} else if(choice == 3){
System.out.println("You chose QUICK sort!");
System.out.println(x[i]+"");
int temp;
for(int i=0;i<x.length-1;i++) {
for(int j=i+1;j<x.length;j++) {
if(x[i]>x[j]) {
temp = x[i];
x[i] = x[j];
x[j] = temp;
}
}
}
} else {
System.out.println("Not in the choices!");
}
}
}
I just can't seem to get this right. I'm still new to java. There's an error that says duplicate local variable. It's my homework. Please help me :(

You declared i twice :
Scanner i = new Scanner(System.in);
and
for(int i = 0 ; i < x.length-1 ; i++)
I suggest you give the Scanner variable a more meaningful name.

You are used a i variable in multiple time
So rename a i variable
Scanner i=new Scanner(System.in);
Rename a i varible
Scanner scan=new Scanner(System.in);

Related

Finding the mode of an array from user input java

So I'm making a program that gets an array from user-inputed values but I'm having trouble writing the code for finding the mode of the array. I tried writing my own code and then tried using a version of someone else's code but that didn't work out because I didn't fully understand it to be honest.
import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int length;
Statistics stats = new Statistics();
System.out.println("Welcome to our statistics program!");
System.out.print("Enter the amount of numbers you want to store: ");
length=Integer.parseInt(keyboard.next());
int[] nums = new int[length];
for(int i=0; i<length; i++) {
System.out.println("Enter a number: ");
nums[i]=keyboard.nextInt();
}
System.out.println("Array elements are: ");
for (int i=0; i<length; i++) {
System.out.println(nums[i]);
}
public int Mode (int[] nums) {
double maxValue = -1.0d;
int maxCount = 0;
for(int i = 0; i < data.length; i++) {
double currentValue = data[i];
int currentCount = 1;
for(int j = i + 1; j < data.length; ++j) {
if(Math.abs(data[j] - currentValue) < epsilon) {
++currentCount;
}
}
}
if (currentCount > maxCount) {
maxCount = currentCount;
maxValue = currentValue;
} else if (currentCount == maxCount) {
maxValue = Double.NaN;
}
}
System.out.println("The minimum number is " + stats.Mode(nums));
You could consider using a HashMap to maintain the frequencies of the values in the array in your loop:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static int getIntegerInput(String prompt, Scanner scanner) {
System.out.print(prompt);
int validInteger = -1;
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
validInteger = scanner.nextInt();
break;
} else {
System.out.println("Error: Invalid input, try again...");
System.out.print(prompt);
scanner.next();
}
}
return validInteger;
}
public static int getPositiveIntegerInput(String prompt, Scanner scanner) {
int num = getIntegerInput(prompt, scanner);
while (num <= 0) {
System.out.println("Error: Integer must be positive.");
num = getIntegerInput(prompt, scanner);
}
return num;
}
public static int getMode(int[] nums) {
if (nums.length == 0) {
throw new IllegalArgumentException("nums cannot be empty");
}
Map<Integer, Integer> valueFrequencies = new HashMap<>();
valueFrequencies.put(nums[0], 1);
int maxFreq = 1;
int candidateMode = nums[0];
for (int i = 1; i < nums.length; i++) {
int value = nums[i];
valueFrequencies.merge(value, 1, Integer::sum);
int candidateFreq = valueFrequencies.get(value);
if (candidateFreq > maxFreq) {
candidateMode = value;
maxFreq = candidateFreq;
}
}
return candidateMode;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numsLength = getPositiveIntegerInput("Enter how many numbers you want to store: ", scanner);
int[] nums = new int[numsLength];
for (int i = 0; i < numsLength; i++) {
nums[i] = getIntegerInput(String.format("Enter number %d: ", i + 1), scanner);
}
int mode = getMode(nums);
System.out.printf("Mode: %d%n", mode);
}
}
Example Usage:
Enter how many numbers you want to store: 0
Error: Integer must be positive.
Enter how many numbers you want to store: 6
Enter number 1: 3
Enter number 2: 2
Enter number 3: 5
Enter number 4: 5
Enter number 5: 3
Enter number 6: 3
Mode: 3

How do I make a random int into a variable I can use and compare in Java?

its not great code I know but I need help at line 30 with if (guess == roll) im trying to make it if you guess the number right it will say you win and if not it will not say you win.
import java.util.Random;
import java.util.Scanner;
public class diceGame
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
diceGame test = new diceGame();
System.out.println("Number of rolls?: ");
int numRoll = scan.nextInt();
System.out.println("Gues the number/most common number: ");
int guess = scan.nextInt();
Random rand = new Random();
for(int i = 0; i < roll.length; i++)
{
roll[i] = rand.nextInt(6)+1;
}
for(int i = 0; i < roll.length; i++)
{
System.out.print(roll[i] + ", ");
}
if (guess == roll)
{
System.out.println("Good job you guess correct");
}
else
{
System.out.println("You did not guess correct");
}
}
}
If you would like to guess the number with the highest frequency after n number of rolls, you can update the count of each roll into an array instead of storing the roll outcome of each roll into the array:
for(int i = 0; i < roll.length; i++)
{
roll[rand.nextInt(6)]++; //store count of each roll
}
To find out if you guessed the most frequency roll, find the maximum value (most commonly rolled number) of the array:
int maxIdx = 0;
for(int i = 0; i < roll.length; i++)
{
if(roll[i] > roll[maxIdx])
maxIdx = i;
}
To compare your guess against the most common number:
if (guess == maxIdx+1) //+1 to maxIdx to offset array start index
{
System.out.println("Good job you guess correct");
}
else
{
System.out.println("You did not guess correct");
}

Error when transferring code

I'm writing code for class, and the code works fine when I run it in Dr. Java in class. However when I input it for grading, I get an error that reads:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Main.main(Main.java:247)
at Ideone.assertRegex(Main.java:94)
at Ideone.test(Main.java:42)
at Ideone.main(Main.java:29)
I have no idea what this means, we haven't covered this sort of thing and I am not a very experienced programmer, sorry. My code is as follows;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int indexFirst = 0;
int indexSecond = 0;
int[] first = new int[10000];
int[] second = new int[10000];
System.out.println("Enter the values for the first array, up to 10000 values, enter a negative number to quit");
do {int value = scanner.nextInt();
if (value < 0) {
break;
}
first[indexFirst++] = value;
} while(true);
System.out.println("Enter the values for the second array, up to 10000 values, enter a negative number to quit");
do {int value = scanner.nextInt();
if (value <= 0) {
break;
}
second[indexSecond++] = value;
} while(true);
System.out.println("First Array:");
for (int i = 0; i < indexFirst; i++) {
System.out.print(first[i] + " ");
}
System.out.println("\n");
System.out.println("Second Array:");
for (int i = 0; i < indexSecond; i++) {
System.out.print(second[i] + " ");
}
System.out.println("\n");
for (int i = 1; i < indexFirst; i++) {
if (first[i-1] > first[i] ) {
System.out.println("ERROR: Array not in correct order");
return;
}
}
for (int i = 1; i < indexSecond; i++) {
if (second[i-1] > second[i] ) {
System.out.println("ERROR: Array not in correct order");
return;
}
}
int[] merged = new int[indexFirst + indexSecond];
int curIdx1 = 0;
int curIdx2 = 0;
for(int mergedIdx = 0; mergedIdx < merged.length; mergedIdx++) {
if (curIdx2 == indexSecond) {
merged[mergedIdx] = first[curIdx1++];
} else if (curIdx1 == indexFirst) {
merged[mergedIdx] = second[curIdx2++];
} else if (first[curIdx1] < second[curIdx2]) {
merged[mergedIdx] = first[curIdx1++];
} else {
merged[mergedIdx] = second[curIdx2++];
}
}
System.out.println("Merged Array:");
for (int i = 0; i < merged.length; i++) {
System.out.print(merged[i] + " ");
}
}
}
If anyone has any input on how to fix this, it would be much appreciated.

Why is my code not incrementing?

So my professor had us do an assignment that asks the user for 5 numbers that are valid (51-99) and unique (non-repeating). I just can't figure out why my nested for loop inside the while loop is not incrementing the i, I suspect it is the break; but without that the for loop keeps looping. Any help would be awesome. Thank you.
public static void main(String[] args) {
int[] userArray;
userArray = new int[5];
int real = 0;
System.out.println("Please print out 5 numbers between 50 and 100. ");
Scanner entry = new Scanner(System.in);
while (real < 5) {
int count = entry.nextInt();
boolean aCount = isValid(count);
if (aCount == true) {
for (int i =0; i < userArray.length; i++) {
userArray[i] = count;
real++;
break;
}
} else {
System.out.println("That is not a valid number.");
}
}
}
public static boolean isValid(int a) {
if (a > 50 && a < 100) {
return true;
} else {
return false;
}
}
I got it guys! I just had to remove the for loop and put this in:
userArray[i] = count;
i++;
real++;
Thank you schmidt73 and everyone that helped!
int i=0;
while (real < 5) {
int count = entry.nextInt();
boolean aCount = isValid(count);
if (aCount == true) {
userArray[i++] = count;
real++;
} else {
System.out.println("That is not a valid number.");
}
}
I guess this is what you are trying to do.
First, you also need to test if the array contains the value you are trying to add (in validate). You could do something like
public static boolean isValid(int[] arr, int real, int a) {
if (a > 50 && a < 100) {
for (int i = 0; i < real; i++) {
if (arr[i] == a) {
return false;
}
}
return true;
}
return false;
}
Then your main method might be written like
int[] userArray = new int[5];
int real = 0;
System.out.println("Please print out 5 numbers between 50 and 100. ");
Scanner entry = new Scanner(System.in);
while (real < 5) {
int count = entry.nextInt();
if (isValid(userArray, real, count)) {
userArray[real++] = count;
} else {
System.out.println("That is not a valid number.");
}
}
System.out.println("The array contains: " + Arrays.toString(userArray));

How can I achieve this specific output using for loops to simplify storing data in an array?

public class IndividualProject2 {
public static void main(String[] args) {
int i;
for( i = 0; i < 7; i++){
Scanner gradeInput = new Scanner(System.in);
System.out.println("Enter midterm 1 score: ");
int num1 = gradeInput.nextInt();
System.out.println("Enter midterm 2 score: ");
int num2 = gradeInput.nextInt();
System.out.println("Enter final score: ");
int num3 = gradeInput.nextInt();
}
}
public static char function (int grade){
String[] name = new String[7];
char[] finalGrade = new char[7];
char letter;
if (grade >= 90){
letter = 'A';
System.out.println(letter);
}
else if (grade >= 80 && grade < 90){
letter = 'B';
System.out.println(letter);
}
else if(grade >= 70 && grade < 80){
letter = 'C';
System.out.println(letter);
}
else{
letter = 'F';
System.out.println(letter);
}
for(int counter=0; counter < finalGrade.length; counter++ ){
finalGrade[counter] = letter;
}
return letter;
}
public static int function (int midtermOne, int midtermTwo) {
int result;
int[] midterm = new int[7];
if ( midtermOne > midtermTwo)
{
result = midtermOne;
}
else{
result = midtermTwo;
}
for(int counter=0; counter < midterm.length; counter++ ){
midterm[counter] = result;
}
return result;
}
public static double function (int num1, int num2, int num3){
double result;
double[] average = new double[7];
result = (num1 + num2 + num3)/3.0;
for(int counter=0; counter < average.length; counter++ ){
average[counter] = result;
}
return result;
}
}
The output should look like this http://i.imgur.com/GHo2YS6.png
I am having difficulty creating a loop that match this specific output.How do I take the inputs in the the loop while using the three function methods to store the values in the arrays. I feel very overwhelmed on how to do this.
Move Scanner gradeInput = new Scanner(System.in); before the for loop in your main. In this way you can avoid doing the same thing 7 times which is not useful in anyway.
Declare four arrays - name, midTerm1, midTerm2 and avg for holding 4 values for each student. You can define them at the class level or inside main.
Fill these four arrays for each student something like
for(int i = 0; i < 7; i++){
System.out.println("Student number " + (i + 1) );
System.out.print("Enter student's name: ");
name[i] = gradeInput.next();
System.out.print("Enter midterm 1 score: ");
midTerm1[i] = gradeInput.nextInt();
System.out.print("Enter midterm 2 score: ");
midTerm2[i] = gradeInput.nextInt();
System.out.print("Enter final score: ");
avg[i] = gradeInput.nextInt();
}
Once, this is done do as below
System.out.printf("%-8s %6s %8s %8s\n", "name", "final", "midterm", "average");
for(int i = 0; i < 7; i++) {
System.out.printf("%-8s %6c %8d %2.6f\n", name[i] , function(avg[i]), function(md1[i], md2[i]), function(md1[i], md2[i], avg[i]));
}
Remove all the print statements from function (int grade).
One side note It is also possible not to hard code the value for number of students - in your case 7 and pass it from command line. In this case, you can use that number to initialize all the four arrays sizes and modify the for loops appropriately.
For example - inside main, you can do something like
public static void main(String[] args) {
int noOfStudents;
if (args.length == 1) {
noOfStudents = Integer.parseInt(args[0]);
name = new String[noOfStudents];
midTerm1 = new int[noOfStudents];
midTerm2 = new int[noOfStudents];
avg = new int[noOfStudents];
} else {
System.out.println("please provide a value for no of students data that need to be processed");
return;
}
}

Categories