我认为,在Mac上,您可以使用CMD+D
(⌘+D
)标记输入到shell的末尾。参见:https://www.jetbrains.com/help/idea/debug-tool-window-console.html
键盘快捷键
的⌘D键组合,可以发送EOF(文件结束),即以 信号没有更多的数据可以从数据源读取。
论算法提供的普林斯顿图书馆的问题 - 在Coursera的课程第1部分,你可以玩了一下他们的代码,特别是在类import edu.princeton.cs.algs4.StdIn;
。使用该代码的实现可能不是最先进的与概念玩:
while (!StdIn.isEmpty()) {
int p = StdIn.readInt();
int q = StdIn.readInt();
if (!uf.connected(p, q)) {
uf.union(p, q);
StdOut.println(p + " " + q);
}
}
这里就是我所做的:
- 创建新的Java项目的IntelliJ
- 创建新的Java包(将在src下)
- 为他们的示例创建新类,这将有一个主要方法
- 在项目中创建libs文件夹
- 从http://algs4.cs.princeton.edu/code/algs4.jar下载它们的代码并将该jar放到libs文件夹中
- 将该lib添加到项目 - 在IntelliJ的项目选项卡上,右键单击项目>打开模块设置>单击依赖项选项卡>单击'+'> JAR或目录...>从012s
- 以上的库文件夹中选择jar我更改了上面的while循环中的代码,以便在shell上有更好的用户交互(这里是创意 - 而不是使用isEmpty()使用p并且q例如是0以标记输入的结束。
现在运行,只需右键单击带有主静态方法的类的代码,然后选择运行(CTRL + SHIFT + R)。
这将避免可怕的CMD + d,如果你想从while循环之后编写更多的代码与之相伴的一些问题 - 例如,我添加的代码检查,如果2个对象是连接:
StdOut.println("Check if 2 objects are connected: ");
try {
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter first object: ");
int n = reader.nextInt(); // Scans the next token of the input as an int.
System.out.println("Enter second object: ");
int m = reader.nextInt(); // Scans the next token of the input as an int.
StdOut.println(uf.connected(n, m) ? "Connected" : "Not Connected");
} catch(Exception e) {
// whatever...
}
这是我非常快速和肮脏的解决问题的方法:
package com.algorithms;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.UF;
import java.util.Scanner;
public class Week1 {
private static UF uf;
public static void main(String[] args)
{
StdOut.println("Enter the total number of objects: ");
int N = StdIn.readInt();
StdOut.println("Enter the unions between any of those objects...");
Week1.uf = new UF(N);
while (true) {
int p = StdIn.readInt();
int q = StdIn.readInt();
if (!uf.connected(p, q)) {
Week1.uf.union(p, q);
StdOut.println(p + " " + q);
}
if(p==0 && q==0) break;
}
checkIfConnected();
}
private static void checkIfConnected()
{
StdOut.println("Check if 2 objects are connected: ");
try {
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter first object: ");
int n = reader.nextInt(); // Scans the next token of the input as an int.
System.out.println("Enter second object: ");
int m = reader.nextInt(); // Scans the next token of the input as an int.
StdOut.println(Week1.uf.connected(n, m) ? "Connected" : "Not Connected");
} catch(Exception e) {}
}
}
尝试按下Ctrl + Z。 – shmosel
我已经试过了。我在Mac btw。 – RB34
我认为你应该使用hasNextLine而不是isEmpty。尝试在另一个窗口中关闭命令以停止程序(https://www.howtogeek.com/209658/how-to-force-applications-and-processes-to-quit-on-os-x/)。 –